No Reverse Match Error, When creating a new user (new user application) it should direct back to home (to the core application)
For this project, I have made 2 applications: Core and Users Creating a new user is the 2nd application. I am trying to direct the new user after registration to 'home' I keep getting NoReverse Match Error This is the view.py this is the code: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'Account created for {username} ! Show us your Designs') return redirect('home') else: form = UserCreationForm() return render(request, 'register.html', {'form': form}) This is the url.py in the core application: urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', checkout, name='checkout'), path('product//', ItemDetailView.as_view(), name='product'), path('score/', PostListView.as_view(), name='score'), path('register/', user_views.register, name='register'), ] What do I need to do to fix this issue, Thank you all in advance -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4584668f-3cf5-40fe-930c-69c75b74b23d%40googlegroups.com.
General Question Regarding Django Password Validation differences
I have used UserCreationForm and got this result below with no validations regarding the password while there are other Usercreationforms with password validations. I am using Django 2.2 -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2822d82b-7854-46f6-88b9-89ab37325816%40googlegroups.com.
Getting approval from Admin first before posting a blog in Django
Hi all, I have made a blog as a project and I have set users to submit posts for the blog directly but i want to direct this post to the admin first for approval before showing on the website. here is the Post Create View Class. class PostCreateView(CreateView): model = Post fields = ['title', 'content'] template_name = "post_form.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Thank you in Advance -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/95facfb3-dedb-476d-957f-80ef2eb72e44%40googlegroups.com.
save() got an unexpected keyword argument 'force_insert'
Hi all, Got this unexpected error all of a sudden, how to fix it. save() got an unexpected keyword argument 'force_insert' def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f 'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'register.html', {'form': form}) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com.
Re: save() got an unexpected keyword argument 'force_insert'
Model Form UserCreationForm On Tuesday, April 21, 2020 at 11:02:13 PM UTC-4, Motaz Hejaze wrote: > > what kind of forms is this ? regular form or model form ? > > > On Wed, Apr 22, 2020 at 4:57 AM Ahmed Khairy > wrote: > >> Hi all, >> >> Got this unexpected error all of a sudden, how to fix it. >> >> save() got an unexpected keyword argument 'force_insert' >> >> >> >> def register(request): >> if request.method == 'POST': >> form = UserRegisterForm(request.POST) >> if form.is_valid(): >> form.save() >> username = form.cleaned_data.get('username') >> messages.success( >> request, f >> 'Your account has been created! You are now able to log in') >> return redirect('login') >> else: >> form = UserRegisterForm() >> return render(request, 'register.html', {'form': form}) >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com.
Re: save() got an unexpected keyword argument 'force_insert'
What do you mean ? On Tuesday, April 21, 2020 at 11:13:16 PM UTC-4, Motaz Hejaze wrote: > > did you define managers ? > > On Wed, Apr 22, 2020 at 5:06 AM Ahmed Khairy > wrote: > >> Model Form >> >> UserCreationForm >> >> On Tuesday, April 21, 2020 at 11:02:13 PM UTC-4, Motaz Hejaze wrote: >>> >>> what kind of forms is this ? regular form or model form ? >>> >>> >>> On Wed, Apr 22, 2020 at 4:57 AM Ahmed Khairy >>> wrote: >>> >>>> Hi all, >>>> >>>> Got this unexpected error all of a sudden, how to fix it. >>>> >>>> save() got an unexpected keyword argument 'force_insert' >>>> >>>> >>>> >>>> def register(request): >>>> if request.method == 'POST': >>>> form = UserRegisterForm(request.POST) >>>> if form.is_valid(): >>>> form.save() >>>> username = form.cleaned_data.get('username') >>>> messages.success( >>>> request, f >>>> 'Your account has been created! You are now able to log in') >>>> return redirect('login') >>>> else: >>>> form = UserRegisterForm() >>>> return render(request, 'register.html', {'form': form}) >>>> >>>> -- >>>> You received this message because you are subscribed to the Google >>>> Groups "Django users" group. >>>> To unsubscribe from this group and stop receiving emails from it, send >>>> an email to django...@googlegroups.com. >>>> To view this discussion on the web visit >>>> https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com >>>> >>>> <https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com?utm_medium=email&utm_source=footer> >>>> . >>>> >>> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/affd82c8-1b8c-46a0-85c0-a3a5c6939abe%40googlegroups.com.
Re: save() got an unexpected keyword argument 'force_insert'
Thank you so much it is realyy helpfull. Fixed it On Tuesday, April 21, 2020 at 11:23:10 PM UTC-4, Motaz Hejaze wrote: > > check this out > > https://wsvincent.com/django-allauth-tutorial-custom-user-model/ > > On Wed, Apr 22, 2020 at 5:18 AM Ahmed Khairy > wrote: > >> What do you mean ? >> >> On Tuesday, April 21, 2020 at 11:13:16 PM UTC-4, Motaz Hejaze wrote: >>> >>> did you define managers ? >>> >>> On Wed, Apr 22, 2020 at 5:06 AM Ahmed Khairy >>> wrote: >>> >>>> Model Form >>>> >>>> UserCreationForm >>>> >>>> On Tuesday, April 21, 2020 at 11:02:13 PM UTC-4, Motaz Hejaze wrote: >>>>> >>>>> what kind of forms is this ? regular form or model form ? >>>>> >>>>> >>>>> On Wed, Apr 22, 2020 at 4:57 AM Ahmed Khairy >>>>> wrote: >>>>> >>>>>> Hi all, >>>>>> >>>>>> Got this unexpected error all of a sudden, how to fix it. >>>>>> >>>>>> save() got an unexpected keyword argument 'force_insert' >>>>>> >>>>>> >>>>>> >>>>>> def register(request): >>>>>> if request.method == 'POST': >>>>>> form = UserRegisterForm(request.POST) >>>>>> if form.is_valid(): >>>>>> form.save() >>>>>> username = form.cleaned_data.get('username') >>>>>> messages.success( >>>>>> request, f >>>>>> 'Your account has been created! You are now able to log in') >>>>>> return redirect('login') >>>>>> else: >>>>>> form = UserRegisterForm() >>>>>> return render(request, 'register.html', {'form': form}) >>>>>> >>>>>> -- >>>>>> You received this message because you are subscribed to the Google >>>>>> Groups "Django users" group. >>>>>> To unsubscribe from this group and stop receiving emails from it, >>>>>> send an email to django...@googlegroups.com. >>>>>> To view this discussion on the web visit >>>>>> https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com >>>>>> >>>>>> <https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com?utm_medium=email&utm_source=footer> >>>>>> . >>>>>> >>>>> -- >>>> You received this message because you are subscribed to the Google >>>> Groups "Django users" group. >>>> To unsubscribe from this group and stop receiving emails from it, send >>>> an email to django...@googlegroups.com. >>>> To view this discussion on the web visit >>>> https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com >>>> >>>> <https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com?utm_medium=email&utm_source=footer> >>>> . >>>> >>> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/affd82c8-1b8c-46a0-85c0-a3a5c6939abe%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/affd82c8-1b8c-46a0-85c0-a3a5c6939abe%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3983161c-10b7-4e0d-b2ba-8dbf83e3b890%40googlegroups.com.
Re: save() got an unexpected keyword argument 'force_insert'
Thank you so much it realyy helpfull. Fixed it On Tuesday, April 21, 2020 at 11:23:10 PM UTC-4, Motaz Hejaze wrote: > > check this out > > https://wsvincent.com/django-allauth-tutorial-custom-user-model/ > > On Wed, Apr 22, 2020 at 5:18 AM Ahmed Khairy > wrote: > >> What do you mean ? >> >> On Tuesday, April 21, 2020 at 11:13:16 PM UTC-4, Motaz Hejaze wrote: >>> >>> did you define managers ? >>> >>> On Wed, Apr 22, 2020 at 5:06 AM Ahmed Khairy >>> wrote: >>> >>>> Model Form >>>> >>>> UserCreationForm >>>> >>>> On Tuesday, April 21, 2020 at 11:02:13 PM UTC-4, Motaz Hejaze wrote: >>>>> >>>>> what kind of forms is this ? regular form or model form ? >>>>> >>>>> >>>>> On Wed, Apr 22, 2020 at 4:57 AM Ahmed Khairy >>>>> wrote: >>>>> >>>>>> Hi all, >>>>>> >>>>>> Got this unexpected error all of a sudden, how to fix it. >>>>>> >>>>>> save() got an unexpected keyword argument 'force_insert' >>>>>> >>>>>> >>>>>> >>>>>> def register(request): >>>>>> if request.method == 'POST': >>>>>> form = UserRegisterForm(request.POST) >>>>>> if form.is_valid(): >>>>>> form.save() >>>>>> username = form.cleaned_data.get('username') >>>>>> messages.success( >>>>>> request, f >>>>>> 'Your account has been created! You are now able to log in') >>>>>> return redirect('login') >>>>>> else: >>>>>> form = UserRegisterForm() >>>>>> return render(request, 'register.html', {'form': form}) >>>>>> >>>>>> -- >>>>>> You received this message because you are subscribed to the Google >>>>>> Groups "Django users" group. >>>>>> To unsubscribe from this group and stop receiving emails from it, >>>>>> send an email to django...@googlegroups.com. >>>>>> To view this discussion on the web visit >>>>>> https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com >>>>>> >>>>>> <https://groups.google.com/d/msgid/django-users/be6de004-4a69-4346-8a12-99eced8d76a3%40googlegroups.com?utm_medium=email&utm_source=footer> >>>>>> . >>>>>> >>>>> -- >>>> You received this message because you are subscribed to the Google >>>> Groups "Django users" group. >>>> To unsubscribe from this group and stop receiving emails from it, send >>>> an email to django...@googlegroups.com. >>>> To view this discussion on the web visit >>>> https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com >>>> >>>> <https://groups.google.com/d/msgid/django-users/4a164104-3cab-4d97-a6ac-47b9a3ed98dd%40googlegroups.com?utm_medium=email&utm_source=footer> >>>> . >>>> >>> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/affd82c8-1b8c-46a0-85c0-a3a5c6939abe%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/affd82c8-1b8c-46a0-85c0-a3a5c6939abe%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2633ef13-a6a3-449e-ae91-f175cf7ea37a%40googlegroups.com.
Success Message after Submitting a form
I have created this class with the success message but I am not receiving the success message I requested, other pages are showing them but this one is not What might be wrong? In the views: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['caption', 'design'] template_name = "post_form.html" success_url = '/score' success_message = "Your Design has been submitted for Review" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) in the HTML {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} Thank you -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7ca1c7ad-b38e-4df5-a3c1-93f57219c140%40googlegroups.com.
Re: Success Message after Submitting a form
Thank you Ramadan Kareem On Friday, April 24, 2020 at 12:11:09 AM UTC-4, mohamed khaled wrote: > > just use SuccessMessageMixin > > from django.contrib.messages.views import SuccessMessageMixin > > class PostCreateView(LoginRequiredMixin,SuccessMessageMixin, CreateView): > model = Post > fields = ['caption', 'design'] > template_name = "post_form.html" > success_url = '/score' > success_message = "Your Design has been submitted for Review" > > > > it will work > > On Friday, 24 April 2020 03:24:56 UTC+2, Ahmed Khairy wrote: >> >> I have created this class with the success message but I am not receiving >> the success message I requested, other pages are showing them but this one >> is not >> >> What might be wrong? >> In the views: >> class PostCreateView(LoginRequiredMixin, CreateView): >> model = Post >> fields = ['caption', 'design'] >> template_name = "post_form.html" >> success_url = '/score' >> success_message = "Your Design has been submitted for Review" >> >> def form_valid(self, form): >> form.instance.author = self.request.user >> return super().form_valid(form) >> >> >> in the HTML >> >> {% if messages %} >> {% for message in messages %} >> >> {{ message }} >> >> {% endfor %} >> {% endif %} >> >> >> >> Thank you >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3be300cd-16b1-4b2b-8d52-1f4cd95f5015%40googlegroups.com.
NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
I have created a new app in a project and moved one of the classes from one app to the new app I checked every step but I keep getting No Reverse match I wrote the name of the app before the namespace but still HTML : Upload Designs URLS from django.urls import include, path from . import views from .views import (PostCreateView, PostDeleteView, PostDetailView, PostListView, PostUpdateView, UserPostListView) app_name = 'score' urlpatterns = [ path('user/', UserPostListView.as_view(), name='user-posts '), path('score/', PostListView.as_view(), name='score'), path('score//', PostDetailView.as_view(), name='post-detail'), path('score/new/', include(('post-create.urls', 'post-create' ), PostCreateView.as_view(), name='post-create'), path('score//update/', PostUpdateView.as_view(), name=' post-update'), path('score//delete/', PostDeleteView.as_view(), name=' post-delete') ] settings: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, path from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('core.urls', namespace='core')), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), views from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.contrib.messages.views import SuccessMessageMixin from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView) from .models import Post class PostListView(ListView): model = Post template_name = "score.html" context_object_name = 'posts' class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['caption', 'design'] template_name = "score/post_form.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.shortcuts import reverse from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') def __str__(self): return self.caption def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a5bf9872-8877-42dd-b76b-cfd1cd316ef5%40googlegroups.com.
Re: NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
I was trying to include the urls originally it was path('score/new/', PostCreateView.as_view(), name='post-create'), but still both not working On Friday, April 24, 2020 at 11:33:48 PM UTC-4, Motaz Hejaze wrote: > > path('score/new/', include(('post-create.urls', 'post-create' > ), PostCreateView.as_view(), name='post-create'), > > explain this line ? > > On Sat, Apr 25, 2020 at 5:30 AM Ahmed Khairy > wrote: > >> I have created a new app in a project and moved one of the classes from >> one app to the new app >> >> I checked every step but I keep getting No Reverse match I wrote the name >> of the app before the namespace but still >> >> >> HTML : >> >> > > Upload Designs >> >> >> >> URLS >> from django.urls import include, path >> >> from . import views >> from .views import (PostCreateView, PostDeleteView, PostDetailView, >> PostListView, PostUpdateView, UserPostListView) >> >> app_name = 'score' >> >> urlpatterns = [ >> path('user/', UserPostListView.as_view(), name=' >> user-posts'), >> path('score/', PostListView.as_view(), name='score'), >> path('score//', PostDetailView.as_view(), name='post-detail' >> ), >> path('score/new/', include(('post-create.urls', 'post-create' >> ), PostCreateView.as_view(), name='post-create'), >> path('score//update/', PostUpdateView.as_view(), name=' >> post-update'), >> path('score//delete/', PostDeleteView.as_view(), name=' >> post-delete') >> ] >> >> >> settings: >> from django.conf import settings >> from django.conf.urls.static import static >> from django.contrib import admin >> from django.contrib.auth import views as auth_views >> from django.contrib.staticfiles.urls import staticfiles_urlpatterns >> from django.urls import include, path >> >> from users import views as user_views >> >> urlpatterns = [ >> path('admin/', admin.site.urls), >> path('accounts/', include('allauth.urls')), >> path('', include('core.urls', namespace='core')), >> path('register/', user_views.register, name='register'), >> path('profile/', user_views.profile, name='profile'), >> >> views >> from django.contrib import messages >> from django.contrib.auth.mixins import >> LoginRequiredMixin, UserPassesTestMixin >> from django.contrib.auth.models import User >> from django.contrib.messages.views import SuccessMessageMixin >> from django.http import HttpResponse >> from django.shortcuts import get_object_or_404, redirect, render >> from django.utils import timezone >> from django.views.generic import ( >> CreateView, DeleteView, DetailView, ListView, UpdateView) >> >> from .models import Post >> >> >> >> class PostListView(ListView): >> model = Post >> template_name = "score.html" >> context_object_name = 'posts' >> >> class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView >> ): >> model = Post >> fields = ['caption', 'design'] >> template_name = "score/post_form.html" >> >> def form_valid(self, form): >> form.instance.author = self.request.user >> return super().form_valid(form) >> >> models >> >> from django.conf import settings >> from django.contrib.auth.models import User >> from django.db import models >> from django.shortcuts import reverse >> from django.utils import timezone >> >> >> # Create your models here. >> class Post(models.Model): >> author = models.ForeignKey(User, on_delete=models.CASCADE) >> design = models.ImageField( >> blank=False, null=True, upload_to='new designs') >> >> def __str__(self): >> return self.caption >> >> def get_absolute_url(self): >> return reverse("score:post-detail", kwargs={"pk": self.pk}) >> >> >> >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/a5bf9872-8877-42dd-b76b-cfd1cd316ef5%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/a5bf9872-8877-42dd-b76b-cfd1cd316ef5%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/298223b8-f349-4ce6-9183-3b077c6d573a%40googlegroups.com.
Re: NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
I tried to include the urls originally it was path('score/new/', PostCreateView.as_view(), name='post-create'), but both didn't work On Friday, April 24, 2020 at 11:29:41 PM UTC-4, Ahmed Khairy wrote: > > I have created a new app in a project and moved one of the classes from > one app to the new app > > I checked every step but I keep getting No Reverse match I wrote the name > of the app before the namespace but still > > > HTML : > >> Upload Designs > > > > URLS > from django.urls import include, path > > from . import views > from .views import (PostCreateView, PostDeleteView, PostDetailView, > PostListView, PostUpdateView, UserPostListView) > > app_name = 'score' > > urlpatterns = [ > path('user/', UserPostListView.as_view(), name=' > user-posts'), > path('score/', PostListView.as_view(), name='score'), > path('score//', PostDetailView.as_view(), name='post-detail'), > path('score/new/', include(('post-create.urls', 'post-create' > ), PostCreateView.as_view(), name='post-create'), > path('score//update/', PostUpdateView.as_view(), name=' > post-update'), > path('score//delete/', PostDeleteView.as_view(), name=' > post-delete') > ] > > > settings: > from django.conf import settings > from django.conf.urls.static import static > from django.contrib import admin > from django.contrib.auth import views as auth_views > from django.contrib.staticfiles.urls import staticfiles_urlpatterns > from django.urls import include, path > > from users import views as user_views > > urlpatterns = [ > path('admin/', admin.site.urls), > path('accounts/', include('allauth.urls')), > path('', include('core.urls', namespace='core')), > path('register/', user_views.register, name='register'), > path('profile/', user_views.profile, name='profile'), > > views > from django.contrib import messages > from django.contrib.auth.mixins import > LoginRequiredMixin, UserPassesTestMixin > from django.contrib.auth.models import User > from django.contrib.messages.views import SuccessMessageMixin > from django.http import HttpResponse > from django.shortcuts import get_object_or_404, redirect, render > from django.utils import timezone > from django.views.generic import ( > CreateView, DeleteView, DetailView, ListView, UpdateView) > > from .models import Post > > > > class PostListView(ListView): > model = Post > template_name = "score.html" > context_object_name = 'posts' > > class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): > model = Post > fields = ['caption', 'design'] > template_name = "score/post_form.html" > > def form_valid(self, form): > form.instance.author = self.request.user > return super().form_valid(form) > > models > > from django.conf import settings > from django.contrib.auth.models import User > from django.db import models > from django.shortcuts import reverse > from django.utils import timezone > > > # Create your models here. > class Post(models.Model): > author = models.ForeignKey(User, on_delete=models.CASCADE) > design = models.ImageField( > blank=False, null=True, upload_to='new designs') > > def __str__(self): > return self.caption > > def get_absolute_url(self): > return reverse("score:post-detail", kwargs={"pk": self.pk}) > > > > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c813a663-e0dc-447e-94a9-a5dda31b3ac6%40googlegroups.com.
Re: NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
yes INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'users.apps.UsersConfig', 'core', 'crispy_forms', 'django_filters', 'score' ] On Saturday, April 25, 2020 at 12:31:30 AM UTC-4, Motaz Hejaze wrote: > > did you add your new app to installed apps in settings.py > > On Sat, Apr 25, 2020 at 6:29 AM Motaz Hejaze > wrote: > >> you don't need the include part because you already copied the class to >> the new app >> >> On Sat, Apr 25, 2020 at 6:16 AM Ahmed Khairy > > wrote: >> >>> I tried to include the urls >>> >>> originally it was >>> >>> path('score/new/', PostCreateView.as_view(), name='post-create'), >>> >>> but both didn't work >>> >>> On Friday, April 24, 2020 at 11:29:41 PM UTC-4, Ahmed Khairy wrote: >>>> >>>> I have created a new app in a project and moved one of the classes from >>>> one app to the new app >>>> >>>> I checked every step but I keep getting No Reverse match I wrote the >>>> name of the app before the namespace but still >>>> >>>> >>>> HTML : >>>> >>>> >>> > Upload Designs >>>> >>>> >>>> >>>> URLS >>>> from django.urls import include, path >>>> >>>> from . import views >>>> from .views import (PostCreateView, PostDeleteView, PostDetailView, >>>> PostListView, PostUpdateView, UserPostListView) >>>> >>>> app_name = 'score' >>>> >>>> urlpatterns = [ >>>> path('user/', UserPostListView.as_view(), name=' >>>> user-posts'), >>>> path('score/', PostListView.as_view(), name='score'), >>>> path('score//', PostDetailView.as_view(), name='post-detail >>>> '), >>>> path('score/new/', include(('post-create.urls', 'post-create' >>>> ), PostCreateView.as_view(), name='post-create'), >>>> path('score//update/', PostUpdateView.as_view(), name=' >>>> post-update'), >>>> path('score//delete/', PostDeleteView.as_view(), name=' >>>> post-delete') >>>> ] >>>> >>>> >>>> settings: >>>> from django.conf import settings >>>> from django.conf.urls.static import static >>>> from django.contrib import admin >>>> from django.contrib.auth import views as auth_views >>>> from django.contrib.staticfiles.urls import staticfiles_urlpatterns >>>> from django.urls import include, path >>>> >>>> from users import views as user_views >>>> >>>> urlpatterns = [ >>>> path('admin/', admin.site.urls), >>>> path('accounts/', include('allauth.urls')), >>>> path('', include('core.urls', namespace='core')), >>>> path('register/', user_views.register, name='register'), >>>> path('profile/', user_views.profile, name='profile'), >>>> >>>> views >>>> from django.contrib import messages >>>> from django.contrib.auth.mixins import >>>> LoginRequiredMixin, UserPassesTestMixin >>>> from django.contrib.auth.models import User >>>> from django.contrib.messages.views import SuccessMessageMixin >>>> from django.http import HttpResponse >>>> from django.shortcuts import get_object_or_404, redirect, render >>>> from django.utils import timezone >>>> from django.views.generic import ( >>>> CreateView, DeleteView, DetailView, ListView, UpdateView) >>>> >>>> from .models import Post >>>> >>>> >>>> >>>> class PostListView(ListView): >>>> model = Post >>>> template_name = "score.html" >>>> context_object_name = 'posts' >>>> >>>>
Re: NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
Yes i tried other urls from other models it worked but anything related to the new app is not linked On Saturday, April 25, 2020 at 12:42:14 AM UTC-4, Motaz Hejaze wrote: > > did you try to change the name 'post-create' to something else ? > > On Sat, Apr 25, 2020 at 6:34 AM Ahmed Khairy > wrote: > >> yes >> >> INSTALLED_APPS = [ >> 'django.contrib.admin', >> 'django.contrib.auth', >> 'django.contrib.contenttypes', >> 'django.contrib.sessions', >> 'django.contrib.messages', >> 'django.contrib.staticfiles', >> 'django.contrib.sites', >> 'allauth', >> 'allauth.account', >> 'users.apps.UsersConfig', >> 'core', >> 'crispy_forms', >> 'django_filters', >> 'score' >> ] >> >> >> On Saturday, April 25, 2020 at 12:31:30 AM UTC-4, Motaz Hejaze wrote: >>> >>> did you add your new app to installed apps in settings.py >>> >>> On Sat, Apr 25, 2020 at 6:29 AM Motaz Hejaze wrote: >>> >>>> you don't need the include part because you already copied the class to >>>> the new app >>>> >>>> On Sat, Apr 25, 2020 at 6:16 AM Ahmed Khairy >>>> wrote: >>>> >>>>> I tried to include the urls >>>>> >>>>> originally it was >>>>> >>>>> path('score/new/', PostCreateView.as_view(), name='post-create'), >>>>> >>>>> but both didn't work >>>>> >>>>> On Friday, April 24, 2020 at 11:29:41 PM UTC-4, Ahmed Khairy wrote: >>>>>> >>>>>> I have created a new app in a project and moved one of the classes >>>>>> from one app to the new app >>>>>> >>>>>> I checked every step but I keep getting No Reverse match I wrote the >>>>>> name of the app before the namespace but still >>>>>> >>>>>> >>>>>> HTML : >>>>>> >>>>>> Upload Designs >>>>>> >>>>>> >>>>>> >>>>>> URLS >>>>>> from django.urls import include, path >>>>>> >>>>>> from . import views >>>>>> from .views import (PostCreateView, PostDeleteView, PostDetailView, >>>>>> PostListView, PostUpdateView, UserPostListView) >>>>>> >>>>>> app_name = 'score' >>>>>> >>>>>> urlpatterns = [ >>>>>> path('user/', UserPostListView.as_view(), name=' >>>>>> user-posts'), >>>>>> path('score/', PostListView.as_view(), name='score'), >>>>>> path('score//', PostDetailView.as_view(), name=' >>>>>> post-detail'), >>>>>> path('score/new/', include(('post-create.urls', 'post-create' >>>>>> ), PostCreateView.as_view(), name='post-create'), >>>>>> path('score//update/', PostUpdateView.as_view(), name=' >>>>>> post-update'), >>>>>> path('score//delete/', PostDeleteView.as_view(), name=' >>>>>> post-delete') >>>>>> ] >>>>>> >>>>>> >>>>>> settings: >>>>>> from django.conf import settings >>>>>> from django.conf.urls.static import static >>>>>> from django.contrib import admin >>>>>> from django.contrib.auth import views as auth_views >>>>>> from django.contrib.staticfiles.urls import staticfiles_urlpatterns >>>>>> from django.urls import include, path >>>>>> >>>>>> from users import views as user_views >>>>>> >>>>>> urlpatterns = [ >>>>>> path('admin/', admin.site.urls), >>>>>> path('accounts/', include('allauth.urls')), >>>>>> path('', include('core.urls', namespace='core')), >>>>>> path('register/', user_views.register, name='register'), >>>>>>
Re: NoReverseMatch at , I have Recently a class from one app and added it to a new app and I revised everything but keep receiving this Error, what did i miss?
I added the new app urls to the main project URLs I think this was the mistake but now I have to change the URLs location as I'm getting 404 error score/score/ Thank you, your first question is what made me find the issue On Saturday, April 25, 2020 at 1:13:08 AM UTC-4, Ahmed Khairy wrote: > > Yes i tried other urls from other models it worked but anything related to > the new app is not linked > > On Saturday, April 25, 2020 at 12:42:14 AM UTC-4, Motaz Hejaze wrote: >> >> did you try to change the name 'post-create' to something else ? >> >> On Sat, Apr 25, 2020 at 6:34 AM Ahmed Khairy >> wrote: >> >>> yes >>> >>> INSTALLED_APPS = [ >>> 'django.contrib.admin', >>> 'django.contrib.auth', >>> 'django.contrib.contenttypes', >>> 'django.contrib.sessions', >>> 'django.contrib.messages', >>> 'django.contrib.staticfiles', >>> 'django.contrib.sites', >>> 'allauth', >>> 'allauth.account', >>> 'users.apps.UsersConfig', >>> 'core', >>> 'crispy_forms', >>> 'django_filters', >>> 'score' >>> ] >>> >>> >>> On Saturday, April 25, 2020 at 12:31:30 AM UTC-4, Motaz Hejaze wrote: >>>> >>>> did you add your new app to installed apps in settings.py >>>> >>>> On Sat, Apr 25, 2020 at 6:29 AM Motaz Hejaze wrote: >>>> >>>>> you don't need the include part because you already copied the class >>>>> to the new app >>>>> >>>>> On Sat, Apr 25, 2020 at 6:16 AM Ahmed Khairy >>>>> wrote: >>>>> >>>>>> I tried to include the urls >>>>>> >>>>>> originally it was >>>>>> >>>>>> path('score/new/', PostCreateView.as_view(), name='post-create'), >>>>>> >>>>>> but both didn't work >>>>>> >>>>>> On Friday, April 24, 2020 at 11:29:41 PM UTC-4, Ahmed Khairy wrote: >>>>>>> >>>>>>> I have created a new app in a project and moved one of the classes >>>>>>> from one app to the new app >>>>>>> >>>>>>> I checked every step but I keep getting No Reverse match I wrote the >>>>>>> name of the app before the namespace but still >>>>>>> >>>>>>> >>>>>>> HTML : >>>>>>> >>>>>>> Upload Designs >>>>>>> >>>>>>> >>>>>>> >>>>>>> URLS >>>>>>> from django.urls import include, path >>>>>>> >>>>>>> from . import views >>>>>>> from .views import (PostCreateView, PostDeleteView, PostDetailView, >>>>>>> PostListView, PostUpdateView, UserPostListView) >>>>>>> >>>>>>> app_name = 'score' >>>>>>> >>>>>>> urlpatterns = [ >>>>>>> path('user/', UserPostListView.as_view(), name=' >>>>>>> user-posts'), >>>>>>> path('score/', PostListView.as_view(), name='score'), >>>>>>> path('score//', PostDetailView.as_view(), name=' >>>>>>> post-detail'), >>>>>>> path('score/new/', include(('post-create.urls', 'post-create' >>>>>>> ), PostCreateView.as_view(), name='post-create'), >>>>>>> path('score//update/', PostUpdateView.as_view(), name=' >>>>>>> post-update'), >>>>>>> path('score//delete/', PostDeleteView.as_view(), name=' >>>>>>> post-delete') >>>>>>> ] >>>>>>> >>>>>>> >>>>>>> settings: >>>>>>> from django.conf import settings >>>>>>> from django.conf.urls.static import static >>>>>>> from django.contrib import admin >>>>>>> from django.contrib.auth import views as auth_views >>>>>>>
Testing an online payment Form using Django Keep getting Not Authenticated Error. Is it because of the Testing Credit Card numbers?
I am making a project for an online payment e-commerce I think I got everything right as am following a Tutorial Keep getting this Error: Not Authenticated Error I used the testing CC Numbers for testing purposes My question is the following codes correct and I'm getting Not Authenticated Error because they are testing Credit Card Numbers.? class PaymentView(View): def get(self, *args, **kwargs): # order return render(self.request, "payment.html") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your Order was Successful ! ") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") # Since it's a decline, stripe.error.CardError will be caught return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate Limit Error") return redirect("/") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid Parameters") return redirect("/") except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed # (maybe you changed API keys recently) messages.error(self.request, "Not Authenticated") return redirect("/") except stripe.error.APIConnectionError as e: # Network communication with Stripe failed messages.error(self.request, "Network Error") return redirect("/") except stripe.error.StripeError as e: # Display a very generic error to the user, and maybe send # yourself an email messages.error( self.request, "Something went wrong. You were not charged. Please Try Again.") return redirect("/") except Exception as e: # Something else happened, completely unrelated to Stripe # send an email to ourselves messages.error( self.request, "A serious Error Occured. We have been notified.") return redirect("/") -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bba17951-6ca3-4480-9423-e5d39e6ed270%40googlegroups.com.
How to get previously uploaded Images in Django
I am using Django 2.2 to make a project where designers upload designs and when I want to post them from admin, I want to choose their names and after I choose their names only their designs appear in the drop down list. So far I have reach the reach the designer name in a drop down list but I don't know how to link only their designs in the designs drop list. I am using 2 different apps: 1."Score" where designers can upload their designs 2."Core" where I can list the items First in the Score .model where designers upload the designs class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) Second in the Core App Model: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() designer_name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='imgs') **How can I make this a drop down list with the selected user's (designer's) all previously uploaded images to choose from instead of uploading new images** def __str__(self): return self.title -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c25a66ad-ba1d-4351-89b6-53698b96997d%40googlegroups.com.
Template Variations title not showing
Hello all, I have made a variation to an Item class in models.py and I think i got the template syntax right but apparently there are something wrong which i can't figure it out Here is the model class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() slug = models.SlugField(unique=True) image = models.ImageField(blank=False, upload_to='approved designs') def __str__(self): return self.title class Meta: unique_together = ('title', 'slug') class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.title and here is the template {% if item.variation_set.all %} {% for items in item.variation_set.all %} {{title.title|capfirst}} {% endfor %} {% endif %} -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4df44e82-6d21-4f41-be78-ba72d9d60c4f%40googlegroups.com.
How to create variables for an e-commerce website
Hi am looking for resources to create variables such as size and color to an e-commerce website -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e6ce14b0-c0ff-46fa-8903-635ed60c4459%40googlegroups.com.
Messages not appearing after creating an app for it in Django
I created an app called marketing app which customizes messages to be written on top of website page. My problem is that these messages are not showing when everything is configured and I don't know why is that might be the template because {{ marketing_message.message}} is only not showing This is the model of the Marketing App class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) start_date = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) end = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) def __str__(self): return str(self.message[:12]) this is the views for the core app: class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['marketing_message'] = MarketingMessage.objects.all() this is the template: {% if marketing_message %} × Marketing Message ! : {{ marketing_message.message}} {% endif %} This is the admin.py of marketing from django.contrib import admin from .models import MarketingMessage # Register your models here. class MarketingMessageAdmin(admin.ModelAdmin): class Meta: model = MarketingMessage admin.site.register(MarketingMessage, MarketingMessageAdmin) return context -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a68d848e-6373-41ef-a614-e4333e974e5c%40googlegroups.com.
Adding a default Variation when creating a new Item
I have created this code for defining a default everytime I create a new product, It is working fine and whenever I create a new Item a new variable (size) is create I want to check whether this code is correct or not as I have had help from someone and I think we could have created an easier way for it class Item(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=True) def __str__(self): return self.title class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) objects = VariationManager() updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title @receiver(post_save, sender=Item) def add_default_Variant(sender, instance, **kwargs): small_size = Variation.objects.create( item=instance, category='size', title='Small') medium_size = Variation.objects.create( item=instance, category='size', title='Medium') large_size = Variation.objects.create( item=instance, category='size', title='Large') @receiver(post_save, sender=Item) def add_default_Variant(sender, instance, **kwargs): variant, created = Variation.objects.get_or_create( title="Small", item=instance) variant, created = Variation.objects.get_or_create( title="Medium", item=instance) variant, created = Variation.objects.get_or_create( title="Large", item=instance) print(f"default variant created : {variant}") -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/dea775b8-f39d-4da8-a539-fc0c10af1bcd%40googlegroups.com.
How to over ride the get context data method in view
I am currently trying to create a like button for my posts in Django I have reached to the part where I can add a like but I am facing difficulty writing the code related to the view which linking the PostListView if there is user who liked it or not. I am getting an error: page Error 404 although everything is correct this the views: class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 5 def get_context_data(self, **kwargs): post = get_object_or_404(Post, id=self.request.POST.get('post_id')) context = super(PostListView, self).get_context_data(**kwargs) context['posts'][0].likes.filter(id=self.request.user.id).exists() is_liked = False if post.likes.filter(id=self.request.user.id).exists(): is_liked = True context = {'post': post, 'is_like': is_liked, } return context def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) This is the model class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='likes') def __str__(self): return self.title Here is the path('like/', like_post, name='like_post'), here is the template: {% extends "base.html"%} {% block content %} {% for post in posts %} {{post.title}} {% csrf_token %} {% if is_like %} Unlike {% else %} Like {% endif %}Likes {% endfor %} {% endblock content %} -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/583492d8-5252-4f86-8e8f-7593b582d404%40googlegroups.com.
Re: How to over ride the get context data method in view
Hi Andréas Kühne, Regarding the first error I have a list of posts in the listView and want to add the like button to each post so how should I fix it? Thank you On Wednesday, May 13, 2020 at 6:08:31 AM UTC-4, Andréas Kühne wrote: > > Hi, > > There are a couple of errors in your code: > > 1. You are using a ListView and then trying to get an individual post? > That is really strange > 2. In your get_context_data method - you first get the context data, > update it and then you set it to a new dict, so everything is reset in the > dict. > 3. you are trying to get the absolut url for your post, but aren't showing > any post detail view. > > Regards, > > Andréas > > > Den ons 13 maj 2020 kl 06:46 skrev Ahmed Khairy >: > >> I am currently trying to create a like button for my posts in Django >> >> I have reached to the part where I can add a like but I am facing >> difficulty writing the code related to the view which linking the >> PostListView if there is user who liked it or not. I am getting an error: >> page Error 404 although everything is correct >> >> >> this the views: >> >> >> class PostListView(ListView): >> model = Post >> template_name = "score.html" >> ordering = ['-date_posted'] >> context_object_name = 'posts' >> queryset = Post.objects.filter(admin_approved=True) >> paginate_by = 5 >> >> def get_context_data(self, **kwargs): >> post = get_object_or_404(Post, id=self.request.POST.get('post_id' >> )) >> context = super(PostListView, self).get_context_data(**kwargs) >> context['posts'][0].likes.filter(id=self.request.user.id).exists >> () >> is_liked = False >> if post.likes.filter(id=self.request.user.id).exists(): >> is_liked = True >> context = {'post': post, >>'is_like': is_liked, >>} >> return context >> >> >> >> def like_post(request): >> post = get_object_or_404(Post, id=request.POST.get('post_id')) >> is_liked = False >> if post.likes.filter(id=request.user.id).exists(): >> posts.likes.remove(request.user) >> is_liked = False >> >> else: >> post.likes.add(request.user) >> is_liked = True >> >> return HttpResponseRedirect(post.get_absolute_url()) >> >> >> This is the model >> >> >> class Post(models.Model): >> designer = models.ForeignKey(User, on_delete=models.CASCADE) >> title = models.CharField(max_length=100) >> date_posted = models.DateTimeField(default=timezone.now) >> likes = models.ManyToManyField(User, blank=True, related_name='likes') >> >> def __str__(self): >> return self.title >> >> Here is the >> >> path('like/', like_post, name='like_post'), >> >> here is the template: >> >> {% extends "base.html"%} {% block content %} {% for post in posts %} >> {{post.title}} >> >> {% csrf_token %} {% if is_like %} >> >> Unlike >> {% else %} >> Like >> {% endif %}Likes >> >> {% endfor %} {% endblock content %} >> >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/583492d8-5252-4f86-8e8f-7593b582d404%40googlegroups.com >> >> <https://groups.google.com/d/msgid/django-users/583492d8-5252-4f86-8e8f-7593b582d404%40googlegroups.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aee352a1-2938-42a6-98cb-5d602abba567%40googlegroups.com.
Re: How to over ride the get context data method in view
Hi There, I have rewritten the get_context_data method to be like this but I am getting name 'user' is not defined: class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 5 def get_context_data(self, **kwargs): context_data = super(PostListView, self).get_context_data(**kwargs) for post in context_data['posts']: post.is_liked = post.likes.filter(user=user).exists() <- name 'user' is not defined return context I am also using this template just for testing till fix the issue Thank you Andreas with me On Wednesday, May 13, 2020 at 12:31:15 PM UTC-4, Andréas Kühne wrote: > > Hi again, > > Bare with me - this is just written in this email - so: > > 1. Your listview is paginated by 5, so it will only show 5 posts - that's > good for this exercise and how I would solve it. > 2. Rewrite your get_context_data method to iterate over the posts: > def get_context_data(self, **kwargs): > context_data = super(PostListView, self).get_context_data(**kwargs) > for post in context_data['posts']: > post.is_liked = post.likes.filter(user=user).exists() > return context > > So now your page should show. In the page template: > > % extends "base.html"%} {% block content %} {% for post in posts %} > {{post.title}} > > {% csrf_token %} > {% if is_like %}type="submit">Unlike > > {% else %} > Like > {% endif %}{% endfor %} {% endblock content %} > > Something like this should give you the functionality you want - however > it's still a bit cumbersome. > > Regards, > > Andréas > > > Den ons 13 maj 2020 kl 15:24 skrev Ahmed Khairy >: > >> Hi Andréas Kühne, >> >> Regarding the first error >> >> I have a list of posts in the listView and want to add the like button to >> each post so how should I fix it? >> >> Thank you >> >> On Wednesday, May 13, 2020 at 6:08:31 AM UTC-4, Andréas Kühne wrote: >>> >>> Hi, >>> >>> There are a couple of errors in your code: >>> >>> 1. You are using a ListView and then trying to get an individual post? >>> That is really strange >>> 2. In your get_context_data method - you first get the context data, >>> update it and then you set it to a new dict, so everything is reset in the >>> dict. >>> 3. you are trying to get the absolut url for your post, but aren't >>> showing any post detail view. >>> >>> Regards, >>> >>> Andréas >>> >>> >>> Den ons 13 maj 2020 kl 06:46 skrev Ahmed Khairy : >>> >>>> I am currently trying to create a like button for my posts in Django >>>> >>>> I have reached to the part where I can add a like but I am facing >>>> difficulty writing the code related to the view which linking the >>>> PostListView if there is user who liked it or not. I am getting an error: >>>> page Error 404 although everything is correct >>>> >>>> >>>> this the views: >>>> >>>> >>>> class PostListView(ListView): >>>> model = Post >>>> template_name = "score.html" >>>> ordering = ['-date_posted'] >>>> context_object_name = 'posts' >>>> queryset = Post.objects.filter(admin_approved=True) >>>> paginate_by = 5 >>>> >>>> def get_context_data(self, **kwargs): >>>> post = get_object_or_404(Post, id=self.request.POST.get( >>>> 'post_id')) >>>> context = super(PostListView, self).get_context_data(**kwargs) >>>> context['posts'][0].likes.filter(id=self.request.user.id). >>>> exists() >>>> is_liked = False >>>> if post.likes.filter(id=self.request.user.id).exists(): >>>> is_liked = True >>>> context = {'post': post, >>>>'is_like': is_liked, >>>>} >>>> return context >>>> >>>> >>>> >>>> def like_post(request): >>>> post = get_object_or_404(Post, id=request.POST.get('post_id')) >>>> is_liked = False >>>> if post.likes.filter(id=request.user.id).exist
Re: How to over ride the get context data method in view
still showing the same error On Wednesday, May 13, 2020 at 2:34:03 PM UTC-4, Yamen Gamal Eldin wrote: > > I haven't seen any definition for user within ur function, so > Change this > post.is_liked = post.likes.filter(user=user).exists() > > To this > > post.is_liked = post.likes.filter(user=request.user).exists() > > > Le mer. 13 mai 2020 à 19:22, Ahmed Khairy > a écrit : > >> Hi There, >> >> I have rewritten the get_context_data method to be like this but I am >> getting name 'user' is not defined: >> >> >> class PostListView(ListView): >> model = Post >> template_name = "score.html" >> ordering = ['-date_posted'] >> context_object_name = 'posts' >> paginate_by = 5 >> >> def get_context_data(self, **kwargs): >> context_data = super(PostListView, self).get_context_data(** >> kwargs) >> for post in context_data['posts']: >> post.is_liked = post.likes.filter(user=user).exists() <- >> name 'user' is not defined >> return context >> >> I am also using this template just for testing till fix the issue >> >> Thank you Andreas with me >> >> >> On Wednesday, May 13, 2020 at 12:31:15 PM UTC-4, Andréas Kühne wrote: >>> >>> Hi again, >>> >>> Bare with me - this is just written in this email - so: >>> >>> 1. Your listview is paginated by 5, so it will only show 5 posts - >>> that's good for this exercise and how I would solve it. >>> 2. Rewrite your get_context_data method to iterate over the posts: >>> def get_context_data(self, **kwargs): >>> context_data = super(PostListView, >>> self).get_context_data(**kwargs) >>> for post in context_data['posts']: >>> post.is_liked = post.likes.filter(user=user).exists() >>> return context >>> >>> So now your page should show. In the page template: >>> >>> % extends "base.html"%} {% block content %} {% for post in posts %} >>> {{post.title}} >>> >>> {% csrf_token >>> %} {% if is_like %} >> type="submit">Unlike >>> >>> {% else %} >>> Like >>> {% endif %}{% endfor %} {% endblock content %} >>> >>> Something like this should give you the functionality you want - however >>> it's still a bit cumbersome. >>> >>> Regards, >>> >>> Andréas >>> >>> >>> Den ons 13 maj 2020 kl 15:24 skrev Ahmed Khairy : >>> >>>> Hi Andréas Kühne, >>>> >>>> Regarding the first error >>>> >>>> I have a list of posts in the listView and want to add the like button >>>> to each post so how should I fix it? >>>> >>>> Thank you >>>> >>>> On Wednesday, May 13, 2020 at 6:08:31 AM UTC-4, Andréas Kühne wrote: >>>>> >>>>> Hi, >>>>> >>>>> There are a couple of errors in your code: >>>>> >>>>> 1. You are using a ListView and then trying to get an individual post? >>>>> That is really strange >>>>> 2. In your get_context_data method - you first get the context data, >>>>> update it and then you set it to a new dict, so everything is reset in >>>>> the >>>>> dict. >>>>> 3. you are trying to get the absolut url for your post, but aren't >>>>> showing any post detail view. >>>>> >>>>> Regards, >>>>> >>>>> Andréas >>>>> >>>>> >>>>> Den ons 13 maj 2020 kl 06:46 skrev Ahmed Khairy >>>> >: >>>>> >>>>>> I am currently trying to create a like button for my posts in Django >>>>>> >>>>>> I have reached to the part where I can add a like but I am facing >>>>>> difficulty writing the code related to the view which linking the >>>>>> PostListView if there is user who liked it or not. I am getting an >>>>>> error: >>>>>> page Error 404 although everything is correct >>>>>> >>>>>> >>>>>> this the views: >>>>>> >>>>>> >>>>>> class PostListView(ListView): >
How to write a Get_Context_method
Hi, I have the following context and I am trying to write it correctly in a function This is context data : def post_view(request): qs= Post.objects.all() user= request.user context= { 'qs':qs, 'user':user, } I am trying to define it in a class PostListView(ListView): I need help writing it correctly -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e81a0fc9-f0ab-4f3b-b61d-827a67db0466%40googlegroups.com.
Exception Value: Related Field got invalid lookup: value
Hi all I am adding a like/unlike button for Posts in a Listview, I am getting an error: Exception Value: Related Field got invalid lookup: value here is the Model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) likes = models.ManyToManyField(User, through="Like", related_name='liked') def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={'pk': self.pk}) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) def toggle_value(self): if self.value == "Like": self.value = "Unlike" else: self.value = "Like" def __str__(self): return str(self.post.pk) the view: def like_post(request): user = request.user if request.method == 'Post': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: like.toggle_value() like.save() return redirect('score:score') class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 5 def get_queryset(self, **kwargs): queryset = super(PostListView, self).get_queryset(**kwargs): return queryset.annotate( total_liked=Count( 'likes', filter=Q(likes__value="Like") ).annotate( user_liked=Case( When(Q(likes__user=self.request.user) & Q(likes__value="Like"), then=Value(True)), default=Value(False), output_field = BooleanField() ) ) Here is the template {% for post in posts %} {{post.title}} {% csrf_token %} {% if post.user_liked %} Like {% else %} Unlike {% endif %} {{post.total_liked}} Likes {% endfor %} Here is the URL path('', PostListView.as_view(), name='score'), path('like/', like_post, name='like_post'), Thank you -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ea1852c9-2b9c-40c7-b6e7-67be69bbc1f7%40googlegroups.com.
Re: Exception Value: Related Field got invalid lookup: value
In the views file in the class PostListView(ListView): 1. def get_queryset(self, **kwargs): 2. queryset = super(PostListView, self).get_queryset(**kwargs) 1. return queryset.annotate( … 1. total_liked=Count( 2. 'likes', 3. filter=Q(likes__value="Like") 4. )).annotate( 5. user_liked=Case( 6. When(Q(likes__user=self.request.user) & Q( On Thursday, May 14, 2020 at 10:07:25 PM UTC-4, Motaz Hejaze wrote: > > Where does this exception happen ? > In which file , which line ? > > On Fri, 15 May 2020, 12:51 am Ahmed Khairy, > wrote: > >> Hi all >> >> I am adding a like/unlike button for Posts in a Listview, I am getting an >> error: >> >> Exception Value: Related Field got invalid lookup: value >> >> here is the Model: >> >> class Post(models.Model): >> designer = models.ForeignKey(User, on_delete=models.CASCADE) >> title = models.CharField(max_length=100) >> likes = models.ManyToManyField(User, through="Like", >> related_name='liked') >> >> def __str__(self): >> return self.title >> >> def get_absolute_url(self): >> return reverse("score:post-detail", kwargs={'pk': self.pk}) >> >> class Like(models.Model): >> user = models.ForeignKey(User, on_delete=models.CASCADE) >> post = models.ForeignKey(Post, on_delete=models.CASCADE) >> value = models.CharField(choices=LIKE_CHOICES, >> default='Like', max_length=10) >> >>def toggle_value(self): >>if self.value == "Like": >>self.value = "Unlike" >>else: >>self.value = "Like" >> >> def __str__(self): >> return str(self.post.pk) >> >> the view: >> >> def like_post(request): >> user = request.user >> if request.method == 'Post': >> post_id = request.POST.get('post_id') >> post_obj = Post.objects.get(id=post_id) >> like, created = Like.objects.get_or_create(user=user, >> post_id=post_id) >> >> if not created: >> like.toggle_value() >> like.save() >> return redirect('score:score') >> >> class PostListView(ListView): >> model = Post >> template_name = "score.html" >> ordering = ['-date_posted'] >> context_object_name = 'posts' >> queryset = Post.objects.filter(admin_approved=True) >> paginate_by = 5 >> >> def get_queryset(self, **kwargs): >>queryset = super(PostListView, self).get_queryset(**kwargs): >>return queryset.annotate( >>total_liked=Count( >> 'likes', >> filter=Q(likes__value="Like") >>).annotate( >> user_liked=Case( >> When(Q(likes__user=self.request.user) & >> Q(likes__value="Like"), then=Value(True)), >> default=Value(False), >> output_field = BooleanField() >>) >>) >> >> Here is the template >> >> {% for post in posts %} >> {{post.title}} >> >> >>{% csrf_token %} >>> style="font-style: inherit; font-variant: inherit; font-weight: inh >> >> -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c0c11a1e-69c1-4b90-a608-d7691bd7d76c%40googlegroups.com.
Re: pip not working
Did you try pip install -r requirements.txt? On Friday, May 15, 2020 at 10:16:52 AM UTC-4, Akorede Habeebullah wrote: > > Hi guys, I need help with my pip. It was working fine until I upgraded it. > now its not working fine anymore. I tried running all pip commands that I > know its still not working. > I detected this while trying to install requirements.txt for a cloned > project , I've tried using python -m pip install and pip install --user > but its not working too. > > I need help pls. > Thanks. > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/25e85052-4267-4372-ab08-d1adadbcdc1a%40googlegroups.com.
how to write Ajax for a Like button in Django
Hi all, I need some help writing the ajax for a like button instead of refreshing every time a like is posted here is the template: {% csrf_token %} {% if user.is_authenticated %} {% if liked %} Unlike {% else %} Like {% endif %} {% else %} Login to Like {{total_likes}} Likes {% endif %} Here is the urls: path('like/', LikeView, name='like_post'), here is the views: def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) like = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) like = False else: post.likes.add(request.user) like = True return redirect('score:post-detail', pk=pk) class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked return context -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/00707977-9b68-4329-a13d-adb9ab7b8813%40googlegroups.com.
Re: how to write Ajax for a Like button in Django
Hi Motaz, When I added your code it disabled the function of the button nothing happened On Sunday, May 17, 2020 at 9:30:38 PM UTC-4, Motaz Hejaze wrote: > > In your like button form in your templates , > try this : > > > > i don't think you need ajax for this , but if you still need it let us know > > > On Mon, 18 May 2020, 2:26 am Gabriel Araya Garcia, > wrote: > >> Hi Ahmed, I was looking for that during several months and I have found >> examples than not run, and therefore I`ve get one conclution: "It`s not >> posible to get that functionality in Django". No one could demostrate with >> example code. >> If you find something, please send me the code. >> >> Thanks >> >> >> Gabriel Araya Garcia >> GMI - Desarrollo de Sistemas Informáticos >> >> >> >> >> El dom., 17 may. 2020 a las 20:15, Ahmed Khairy (> >) escribió: >> >>> Hi all, >>> >>> I need some help writing the ajax for a like button instead of >>> refreshing every time a like is posted >>> >>> here is the template: >>> >>> >>> {% csrf_token %} >>> {% if user.is_authenticated %} >>> {% if liked %} >>> >> class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike >> > >>> {% else %} >>> >> class= "btn btn-primary btn-sm" value="{{post.id}}"> Like >> > >>> {% endif %} >>> {% else %} >>> Login>> > to Like >>> {{total_likes}} Likes >>> {% endif %} >>> >>> >>> Here is the urls: >>> path('like/', LikeView, name='like_post'), >>> >>> here is the views: >>> def LikeView(request, pk): >>> post = get_object_or_404(Post, id=request.POST.get('post_id')) >>> like = False >>> if post.likes.filter(id=request.user.id).exists(): >>> post.likes.remove(request.user) >>> like = False >>> >>> else: >>> post.likes.add(request.user) >>> like = True >>> return redirect('score:post-detail', pk=pk) >>> >>> class PostDetailView(DetailView): >>> model = Post >>> template_name = "post_detail.html" >>> >>> def get_context_data(self, *args, **kwargs): >>> context = super(PostDetailView, self).get_context_data() >>> >>> stuff = get_object_or_404(Post, id=self.kwargs['pk']) >>> total_likes = stuff.total_likes() >>> >>> liked = False >>> if stuff.likes.filter(id=self.request.user.id).exists(): >>> liked = True >>> >>> context["total_likes"] = total_likes >>> context["liked"] = liked >>> return context >>> >>> >>> >>> -- >>> You received this message because you are subscribed to the Google >>> Groups "Django users" group. >>> To unsubscribe from this group and stop receiving emails from it, send >>> an email to django...@googlegroups.com . >>> To view this discussion on the web visit >>> https://groups.google.com/d/msgid/django-users/00707977-9b68-4329-a13d-adb9ab7b8813%40googlegroups.com >>> >>> <https://groups.google.com/d/msgid/django-users/00707977-9b68-4329-a13d-adb9ab7b8813%40googlegroups.com?utm_medium=email&utm_source=footer> >>> . >>> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to django...@googlegroups.com . >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/django-users/CAKVvSDCuegzvsZQ_Rfms3yMA_EO914T0yJ_n929mnx7bNDodUA%40mail.gmail.com >> >> <https://groups.google.com/d/msgid/django-users/CAKVvSDCuegzvsZQ_Rfms3yMA_EO914T0yJ_n929mnx7bNDodUA%40mail.gmail.com?utm_medium=email&utm_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/76f6356b-17bc-4697-b6cf-966f01e9217f%40googlegroups.com.
Re: how to write Ajax for a Like button in Django
Hi Motaz, I tried it again now but when I press it there is no change. The likes count is the same and the like button doesnt change to dislike On Sunday, May 17, 2020 at 10:05:12 PM UTC-4, Motaz Hejaze wrote: > > The button is submitted but without page refresh > > On Mon, 18 May 2020, 3:53 am Ahmed Khairy, > wrote: > >> Hi Motaz, >> >> When I added your code it disabled the function of the button nothing >> happened >> >> On Sunday, May 17, 2020 at 9:30:38 PM UTC-4, Motaz Hejaze wrote: >>> >>> In your like button form in your templates , >>> try this : >>> >>> >>> >>> i don't think you need ajax for this , but if you still need it let us know >>> >>> >>> On Mon, 18 May 2020, 2:26 am Gabriel Araya Garcia, < >>> gabriela...@gmail.com> wrote: >>> >>>> Hi Ahmed, I was looking for that during several months and I have found >>>> examples than not run, and therefore I`ve get one conclution: "It`s not >>>> posible to get that functionality in Django". No one could demostrate with >>>> example code. >>>> If you find something, please send me the code. >>>> >>>> Thanks >>>> >>>> >>>> Gabriel Araya Garcia >>>> GMI - Desarrollo de Sistemas Informáticos >>>> >>>> >>>> >>>> >>>> El dom., 17 may. 2020 a las 20:15, Ahmed Khairy () >>>> escribió: >>>> >>>>> Hi all, >>>>> >>>>> I need some help writing the ajax for a like button instead of >>>>> refreshing every time a like is posted >>>>> >>>>> here is the template: >>>>> >>>>> >>>>> {% csrf_token %} >>>>> {% if user.is_authenticated %} >>>>> {% if liked %} >>>>> >>>> class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike >>>> > >>>>> {% else %} >>>>> >>>> class= "btn btn-primary btn-sm" value="{{post.id}}"> Like >>>> > >>>>> {% endif %} >>>>> {% else %} >>>>> Login>>>> > to Like >>>>> {{total_likes}} Likes >>>>> {% endif %} >>>>> >>>>> >>>>> Here is the urls: >>>>> path('like/', LikeView, name='like_post'), >>>>> >>>>> here is the views: >>>>> def LikeView(request, pk): >>>>> post = get_object_or_404(Post, id=request.POST.get('post_id')) >>>>> like = False >>>>> if post.likes.filter(id=request.user.id).exists(): >>>>> post.likes.remove(request.user) >>>>> like = False >>>>> >>>>> else: >>>>> post.likes.add(request.user) >>>>> like = True >>>>> return redirect('score:post-detail', pk=pk) >>>>> >>>>> class PostDetailView(DetailView): >>>>> model = Post >>>>> template_name = "post_detail.html" >>>>> >>>>> def get_context_data(self, *args, **kwargs): >>>>> context = super(PostDetailView, self).get_context_data() >>>>> >>>>> stuff = get_object_or_404(Post, id=self.kwargs['pk']) >>>>> total_likes = stuff.total_likes() >>>>> >>>>> liked = False >>>>> if stuff.likes.filter(id=self.request.user.id).exists(): >>>>> liked = True >>>>> >>>>> context["total_likes"] = total_likes >>>>> context["liked"] = liked >>>>> return context >>>>> >>>>> >>>>> >>>>> -- >>>>> You received this message because you are subscribed to the Google >>>>> Groups "Django users&q
Can't Fix the No Reverse Error in Ajax
I am trying to use Ajax to submit a like button, I believe everything is in order but I keep getting django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['score/like/(?P[0-9]+)$'] I am not sure what is the reason. Need help to identify the error. Here is the view class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request, pk): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) like = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) like = False else: post.likes.add(request.user) like = True context["total_likes"] = total_likes context["liked"] = liked if request.is_ajax: html = render_to_string('like_section.html', context, request= request) return JsonResponse({'form': html}) Here is the url.py updated urlpatterns = [ path('user/', UserPostListView.as_view(), name= 'user-posts'), path('', PostListView.as_view(), name='score'), path('who_we_Are/', who_we_are, name='who_we_are'), path('/', PostDetailView.as_view(), name='post-detail'), path('like/', LikeView, name='like_post'), path('new/', PostCreateView.as_view(), name='post-create'), path('/update/', PostUpdateView.as_view(), name='post-update'), path('/delete/', PostDeleteView.as_view(), name='post-delete') ] here is the template {% csrf_token %} Likes: {{total_likes}} {% if user.is_authenticated %} {% if liked %} Unlike {% else %} Like {% endif %} {% else %} Login to Like {% endif %} here is the ajax https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";> $(document).ready(function(event){ $(document).on.('click','#like', function(event){ event.preventDefault(); $var pk= $(this).attr('value'); $.ajax({ type:'POST', url:'{% url "score:like_post" post.pk %}', data:{'id': pk, 'csrfmiddlewaretoken':'{{csrf_token}}'}, dataType:'json', success:function(response){ $('#like-section').html(response['form']) console.log($('#like-section').html(response['form' ])); }, error:function(rs, e){ console.log(rs.responseText); }, }); }); }); -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5aaa1274-dd6b-42bc-8a5e-bce4596ace98%40googlegroups.com.
Re: Can't Fix the No Reverse Error in Ajax
Do you mean that this line should be changed? No ! Don't Print it On Tuesday, May 19, 2020 at 11:11:12 PM UTC-4, Hella Nick wrote: > > button标签中的type属性设置为button, > > Ahmed Khairy > 于2020年5月20日周三 上午1:54写道: > >> I am trying to use Ajax to submit a like button, I believe everything is >> in order but I keep getting django.urls.exceptions.NoReverseMatch: Reverse >> for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: >> ['score/like/(?P[0-9]+)$'] >> >> >> I am not sure what is the reason. Need help to identify the error. >> >> >> Here is the view >> >> >> class PostDetailView(DetailView): >> model = Post >> template_name = "post_detail.html" >> >> def get_context_data(self, *args, **kwargs): >> context = super(PostDetailView, self).get_context_data() >> stuff = get_object_or_404(Post, id=self.kwargs['pk']) >> total_likes = stuff.total_likes() >> liked = False >> if stuff.likes.filter(id=self.request.user.id).exists(): >> liked = True >> context["total_likes"] = total_likes >> context["liked"] = liked >> return context >> >> >> def LikeView(request, pk): >> # post = get_object_or_404(Post, id=request.POST.get('post_id')) >> post = get_object_or_404(Post, id=request.POST.get('id')) >> like = False >> if post.likes.filter(id=request.user.id).exists(): >> post.likes.remove(request.user) >> like = False >> else: >> post.likes.add(request.user) >> like = True >> context["total_likes"] = total_likes >> context["liked"] = liked >> >> if request.is_ajax: >> html = render_to_string('like_section.html', context, request= >> request) >> return JsonResponse({'form': html}) >> >> Here is the url.py updated >> >> urlpatterns = [ >> path('user/', UserPostListView.as_view(), name= >> 'user-posts'), >> path('', PostListView.as_view(), name='score'), >> path('who_we_Are/', who_we_are, name='who_we_are'), >> path('/', PostDetailView.as_view(), name='post-detail'), >> path('like/', LikeView, name='like_post'), >> path('new/', PostCreateView.as_view(), name='post-create'), >> path('/update/', PostUpdateView.as_view(), name='post-update' >> ), >> path('/delete/', PostDeleteView.as_view(), name='post-delete' >> ) >> ] >> >> here is the template >> >> >> {% csrf_token %} >> Likes: {{total_likes}} >> {% if user.is_authenticated %} >> {% if liked %} >> > 'post_id' class= "btn btn-danger btn-sm" >> value="{{post.id}}"> Unlike >> {% else %} >> > 'post_id' class= "btn btn-primary btn-sm" >> value="{{post.id}}"> Like >> {% endif %} >> {% else %} >> > > Login to Like >> {% endif %} >> >> >> here is the ajax >> >> https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"</a>;></ >> script> >> >> <script type="text/javascript"> >> $(document).ready(function(event){ >> $(document).on.('click','#like', function(event){ >> event.preventDefault(); >> $var pk= $(this).attr('value'); >> $.ajax({ >> type:'POST', >> url:'{% url "score:like_post" post.pk %}', >> data:{'id': pk, 'csrfmiddlewaretoken': >> '{{csrf_token}}'}, >> dataType:'json', >>
Re: Template Variations title not showing
Did you adjust your views to make the variations add to the cart ? On Thursday, May 21, 2020 at 10:04:15 PM UTC-4, oldtimer wrote: > > Hello, > > i was able to get the variant to show on the product page with using a > form. > > I cannot get the variants to display in the cart. > > Only difference is my Variation model is a ManyToManyField to the item. I > have also changed my variant options to numbers as the dict was expecting > an integer and not a string, that is why mine shows 0 not size. > > Hope this helps, maybe you can help me get the next peice. > > thanks > > {% if item.variation_set.sizes %} > > {% for item in item.variation_set.sizes %} > > Select Size > {{ item.name }} option> > {% endfor %} > > {% endif %} > > On Tuesday, May 5, 2020 at 5:12:15 PM UTC-6, Ahmed Khairy wrote: >> >> Hello all, >> >> I have made a variation to an Item class in models.py and I think i got >> the template syntax right but apparently there are something wrong which i >> can't figure it out >> >> Here is the model >> >> class Item(models.Model): >> title = models.CharField(max_length=100) >> description = models.TextField() >> price = models.FloatField() >> slug = models.SlugField(unique=True) >> image = models.ImageField(blank=False, upload_to='approved designs') >> >> >> def __str__(self): >> return self.title >> >> class Meta: >> unique_together = ('title', 'slug') >> class Variation(models.Model): >> item = models.ForeignKey(Item, on_delete=models.CASCADE) >> title = models.CharField(max_length=120) >> image = models.ImageField(null=True, blank=True) >> price = models.FloatField(null=True, blank=True) >> >> def __str__(self): >> return self.title >> >> and here is the template >> >> {% if item.variation_set.all %} >> >> {% for items in item.variation_set.all %} >> > value='{item.variation|lower}'>{{title.title|capfirst}} >> {% endfor %} >> >> {% endif %} >> >> -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4808fef2-00e0-4d61-9e67-ed540bb4d2a6%40googlegroups.com.
Changing in the Quantity of variants reflecting in the wrong item in Order Summary
Helloo, I have a problem with the variations and the quantity related to it in the order summary page. It was working perfectly and all of a sudden (this is an example to simplify): when I add to the cart 2 items: - Item X with a size small - Item X with a size medium When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first. In the order summary, there are a plus and minus in the template to change the quantity. I have identified the problem but I can't figure out why it is occurring Here is the template: Order Summary {% for order_item in object.items.all %} {{ forloop.counter }} {{ order_item.item.title }} {{ order_item.item.price }} {{ order_item.quantity }} {% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} {% endif %} ``` Here is the views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) item_var = [] # item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) order_item.variation.add(*item_var) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to cart.") return redirect("core:order-summary") @login_required def remove_from_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_qs = Order.objects.filter( user=request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item = OrderItem.objects.filter( item=item, user=request.user, ordered=False )[0] order.items.remove(order_item) order_item.delete() messages.info(request, "This item was removed from your cart") return redirect("core:order-summary") else: messages.info(request, "This item was not in your cart") return redirect("core:product", slug=slug) else: messages.info(request, "You don't have an active order") return redirect("core:product", slug=slug) @login_required def remove_single_item_from_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_qs = Order.objects.filter( user=request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item = OrderItem.objects.filter( item=item,
Re: Template Variations title not showing
Helloo, Check my views in this question link, it might be useful On Saturday, May 23, 2020 at 1:35:32 AM UTC-4, oldtimer wrote: > > I cannot get variations or I tried model forms for options as well and > cannot get either to add to the cart. I can get both to display as options > on the product page, but that is as far as I've made it. Need some help on > how to get the views.py to get the options and post to cart. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/681ca6d2-7f33-4bf1-8e0d-d998db3f7fc3%40googlegroups.com.
Re: Template Variations title not showing
here is the link https://groups.google.com/forum/#!topic/django-users/5SckOumQLQM On Sunday, May 24, 2020 at 10:38:18 PM UTC-4, Ahmed Khairy wrote: > > Helloo, > > Check my views in this question link, it might be useful > > On Saturday, May 23, 2020 at 1:35:32 AM UTC-4, oldtimer wrote: >> >> I cannot get variations or I tried model forms for options as well and >> cannot get either to add to the cart. I can get both to display as options >> on the product page, but that is as far as I've made it. Need some help on >> how to get the views.py to get the options and post to cart. >> > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/00bb7b45-22c2-4375-b48a-a7c7ef5ad7ac%40googlegroups.com.
AttributeError when returning post.title in a comment model
I was working on a comment section for post and was getting an AttributeError when I return return '{}-{}'.format(self.post.title, str(self.user.username)) in the comment model I am trying to link users and posts to the comment I am getting the same error Here is the Models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9e84bb03-ca66-4517-ab34-8d723a457b9f%40googlegroups.com.
How to create a link between Posts List View and Items List View of the same User
I am creating a project where there are Posts and Items, 2 different models in 2 different apps and each has a user who can be the same. I have created a page for each user to post all related posts called Userpost List view, and I want to add an if statement or a queryset to show a button to link the items related to the same user called Designerpost List view. I don't know how to proceed as I can fix the NoReverse Error Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template user_posts.html {% if item %} Go to items{% else %} Go to items {% endif %} here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the designerlist views.py that I am trying to link to from the user post view if it is available class DesignerPostListView(ListView): model = Item template_name = "designer_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a761e738-6704-49ac-a610-af4bf74f2dc5o%40googlegroups.com.
Need Help Fixing an Issue in my E-commerce Project
Hi all, I have been battling with this issue for quite a long time and I haven't been able to find a solution to fix it. So, I have an E-commerce Project and The issue is related to the product Variations and the quantity related to it in the order summary page. Example with the sequence for my issue: 1. From the product details I add to cart the item* White T-shirt* after choosing the variations of *Small *Size 2. After adding the first item, I return to the product details page and add another *White T-shirt* but different size *Medium* Now, this is what appears in my order summary: - *White T-shirt* with a size *Small *Quantity: 1 - *White T-shirt *with a size *Medium *Quantity:1 When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first. To be like this: - *White T-shirt* with a size *Small *Quantity:2 - *White T-shirt* with a size *Medium *Quantity:1 In the order summary, there are a plus and minus in the template to change the quantity. I have recently understood that because there's no form in the template. The code that sends a POST request with form data to the add to cart view is not there, because item_var will always be an empty list so order_item.variation.add(*item_var) does nothing. I do not know how to add a POST request to this template. in the template there is a URL to add-to-cart", but URLs are transmitted by GET, so the code after if request.method == 'POST': never hits. Furthermore, even if it would, the add_to_cart url knows nothing about variations cause it only gets item slugs. Here is my models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size',), ('color', 'color',), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=100, null=True, blank=True) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) Here are the views: class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) item_var = [] # item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user=request.user, ordered=False ) order_item.variation.add(*item_var) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.