Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error:Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I am having a problem with the password reset . Its works perfectly if i delete the namespace app_name = 'crm' . But when i include app_name = 'crm' i get the error, Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. But I want it to work without removing the namespace. My urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'crm' urlpatterns = [ path('', views.home, name='dashboard'), path('login/', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('logout/', views.logoutUser, name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), ] -
Render celery task staus in Django
I am currently using Django for my Project. In which I am saving DB backups. Db Backups are large in size so I am handling this activity with Celery as an async mechanism with Redis broker. Task works perfectly. Now I want to get the status of my task which was with celery for operation. I am currently looking to render the progress bar on the Html page so that the user can see the status of the task initiated in the celery. -
Django: TypeError at / context must be a dict rather than tuple
I keep getting an error message when executing this views settings: from django.shortcuts import render # Create your views here. def home_screen_view(request): print(request.headers) return render(request, 'base.html', ()) so I need your help -
int() argument must be string, a bytes-like object, not 'ObjectId'
I am following this tutorial for using MongoDB and Django with djongo. I am having an error creating the items of this model, but I am following the tutorial closely and I don´t really know what´s the problem. I show here the code from the models, the views and the serializer: class Piso(models.Model): nombre = models.CharField(max_length=30,blank=False,default=''); habitantes = models.CharField(max_length=202,blank=False,default=''); class PisoSerializer(serializers.ModelSerializer): class Meta: model = Piso fields = ('id','nombre','habitantes') And the view method: @api_view(['POST','GET']) def piso_list(request): # GET list of tutorials, POST a new tutorial, DELETE all tutorials if request.method == 'POST': piso_serializer = PisoSerializer(data=request.data) if piso_serializer.is_valid(): piso_serializer.save();#This is the object I fill return JsonResponse(piso_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(piso_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'GET': pisos = Piso.objects.all() name = request.GET.get('name', None) if name is not None: pisos = pisos.filter(nombre__icontains=name) pisos_serializer = PisoSerializer(pisos, many=True) return JsonResponse(pisos_serializer.data[0], safe=False) # 'safe=False' for objects serialization The problem is that the object does not save the id column of my object in the database, which is created automatically. This is the object the MongoDB saves: { "_id": { "$oid": "5edd1014b9ca43bdef186d38" }, "nombre": "iddyo", "habitantes": "yeto" } It´s probably a stupid error but I can´t get my head around it. Thanks a lot! -
Django: save an empty parent object via formset (using inlineformset_factory)
I thought I've got how forms and formsets work, but finally stuck. - How to save empty object as placeholder parent for a child object? - Do I correctly use inline formsets with form passing all of them to template? - Isn't it easier to just use forms? I have chain of models: - Theme (with title field), which can have - Description (with optional text field), which can have - Url (with name and URL fields) # models.py class Theme(models.Model): title = models.CharField(max_length=256) class Description(models.Model): description = models.TextField( blank=True ) theme = models.OneToOneField( Theme, null = True, blank = True, on_delete = models.CASCADE, ) class Url(models.Model): name = models.CharField(max_length=32) url = models.URLField() description = models.ForeignKey( Description, null = True, blank = True, on_delete = models.CASCADE, ) (My goal is that) Description can be empty, but have a URL (later several Url objects). (1) I use inline formsets via inlineformset_factory (and not sure if I do it any correctly): # forms.py class ThemeForm(forms.ModelForm): class Meta: model = Theme fields = ['title'] class DescriptionForm(forms.ModelForm): class Meta: model = Description fields = ['description'] class UrlForm(forms.ModelForm): class Meta: model = Url fields = ['name', 'url'] DescriptionFormSet = forms.inlineformset_factory( Theme, Description, form=DescriptionForm, exclude=[], can_delete=False … -
Code from Celery in __init__.py breaks Django
I was following this guide: First steps with django and it tells you to add this to your __init__.py: __init__.py from consumer.celery import app as celery_app __all__ = ['celery_app'] however, when I do that my django app wont start anymore stating: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. searching for this I dound the following answer on stackoverflow. In the accepted answer the OP states that they had some code in their __init__.py and that moving it fixed their problem. It also does for me. I find this really odd since it is a guide is from the official celery documentation and I also dicovered this only fails if I try to import a django model in my tasks.py file: tasks.py from celery import shared_task from .models import myModel # this import breaks my app @shared_task def filter_task(message): result = myModel.objects.filter(id=message['id']) print(result.length) # I haven't been able to test this line yet due to the error Note that with the code in __init__.py both pyhton manage.py runserver and celery -A myworker worker -l info fail. But when I make __init__.py emty, only the latter fails with the following error message: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either … -
UpdateView not saving changes
my UpdateView is not saving the new changes and showing no errors models.py class Service(models.Model): type_ch = [('credit','credit'),('game','game')] currency_ch = [('€','€'),('$','$'),('DZD','DZD'),('Unit','Unit')] distributor = models.ForeignKey(Distributor,on_delete=models.SET_NULL,null=True,blank=False) model = models.CharField(choices=type_ch,max_length=20,null=True,blank=False) name = models.CharField(max_length=200,null=True,blank=False) price = models.FloatField(default=0.00) currency = models.CharField(choices=currency_ch,max_length=20,null=True,blank=False) available = models.FloatField(null=True,blank=False) note = models.TextField(null=True,blank=True) image = models.ImageField(default='defser.png') def __str__(self): return self.name forms.py class ServiceForm(forms.ModelForm): class Meta(): model = Service fields = ['distributor','model','name','price','currency','available','note','image'] def __init__(self, *args, **kwargs): super(ServiceForm, self).__init__(*args, **kwargs) self.fields['model'].widget.attrs['class'] = 'form-control-account' self.fields['name'].widget.attrs['class'] = 'form-control-account' self.fields['distributor'].widget.attrs['class'] = 'form-control-account' self.fields['price'].widget.attrs['class'] = 'form-control-account' self.fields['currency'].widget.attrs['class'] = 'form-control-account' self.fields['available'].widget.attrs['class'] = 'form-control-account' self.fields['note'].widget.attrs['class'] = 'form-control-account' views.py class ServiceUpdateView(UpdateView): model = Service template = "app/service_form" form_class = ServiceForm service_form.html <form class="needs-validation" action="." method="POST" enctype='multipart/form-data'> {% csrf_token %} <div class="form-group"> <label>Distributor: <small class="text-muted"> (select your own distributor accountt)</small></label> {{ form.distributor}} </div> <div class="form-group"> <label>Type:</label> {{form.model}} </div> <div class="form-group"> <label>Service Name:</label> {{form.name}} </div> <div class="form-group"> <label>Service Currency:</label> {{form.currency}} </div> <div class="form-group"> <label>Amount Available:</label> {{form.available}} </div> <div class="form-group"> <label>Price For Unit: DZD</label> {{form.price}} </div> <div class="form-group"> <label>Note:</label> {{form.note}} </div> <div class="form-group"> <label for="exampleFormControlFile1">Service Image</label> {{form.image}} </div> <hr> <button type="submit" class="btn btn-primary">Submit</button> </form> i'm trying to allow the user to be able to change all the values of the saved service but when i press the submit button it redirects me back … -
Can't find django-html in “Select Language Mode” in VS Code
I have tried to set django-html as the language for my django template files by adding this to settings.json: "files.associations": { ".html": "html", "/templates//.html": "django-html" but instead, the language sets as a plain text. -
Is it good to keep cart items in local or cookie storage before confirming the order by user?
I'm building the E-commerce website using Django. When a user select items with quantity, the list is formed and total price is calculated on every addition of item. Objective: to keep the order (cart items) details saved even if the user leaves the browser window before confirmation and checkout process. Now for this purpose, there are two options (that i know): to save all the cart items in database even before user confirms it, (but this would be unnecessary records in database because he doesn't confirms the order) to use localStorage / webStorage / Cookie storage. (but there would be a risk that someone changes the cookie , or local storage variables which contains item ids, quantities etc) you can tell me the best methods you know for this purpose. Thanks in advance. -
command 'gcc' failed with exit status 1 when building wheel for pdftotext
ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vu13x6kn/pdftotext/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-quoxq88r remote: cwd: /tmp/pip-install-vu13x6kn/pdftotext/ remote: Complete output (14 lines): remote: /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' remote: warnings.warn(msg) remote: running bdist_wheel remote: running build remote: running build_ext remote: building 'pdftotext' extension remote: creating build remote: creating build/temp.linux-x86_64-3.6 remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPOPPLER_CPP_AT_LEAST_0_30_0=0 -I/app/.heroku/python/include/python3.6m -c pdftotext.cpp -o build/temp.linux-x86_64-3.6/pdftotext.o -Wall remote: pdftotext.cpp:3:10: fatal error: poppler/cpp/poppler-document.h: No such file or directory remote: #include <poppler/cpp/poppler-document.h> remote: ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: ---------------------------------------- remote: ERROR: Failed building wheel for pdftotext I am using Python 3.7.0, Django 3.0.4, and trying to host in Heroku. Every time I tried to push into the master of Heroku, it occurs the following error. Could anyone please help me out? -
Django - How to shape and group data to send into serializer (DRF)
I am working on data visualisation, and hence my data has to be shaped in a specific format, but for now, I am using for loops and assigning to dictionaries and lists before passing the final data into a serializer (which is extremely messy) and I was wondering if there is any better way to do it using Django. Here is my models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.ForeignKey('SalesDepartment', related_name='users', blank=True) class SalesDepartment(models.Model): department_id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=100) class CustomerInformation(models.Model): status = ( ('lead', 'Lead'), ('client', 'Client'), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=status, default='lead') creator = models.ForeignKey('UserProfile', related_name='customers', on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateField(default=timezone.localdate) Basically I want my data to look something like this { department: DepartmentA, department_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 20, client_count: 12 }, { date: 010520, formatted_date: 'May 2020', lead_count: 34, client_count: 19 } ], users: [ { user: UserA, user_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 5, client_count: 2 }, { date: 010520, formatted_date: 'May 2020', lead_count: 8, client_count: 3 } ] }, { user: UserB, user_data: [ { date: 010620, formatted_date: 'June 2020', lead_count: 10, client_count: 2 }, { date: … -
importing django-tables2 issue
I download 'django-tables2' inside venv, and i when I add django_tables2 to my INSTALLED_APPS INSTALLED_APPS = [ ...... #'search_listview', #'django_filters', 'django_tables2', #'sweetify' ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ .... 'django.template.context_processors.request', ], }, }, ] i receive this and i tried also 'django-tables2', i still receive this error -
TypeError at /addreview Field 'id' expected a number but got <built-in function id>
Recently I'm working to make an e-commerce website using django, my problem is the views are stuck on an error says that the rproduct_id requires id, but whenever i assign id to that field, it shows me this type of error.I am stucked at this point for hours. Here is my code, models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings from django import forms class Category(models.Model): Categories = [ ("Pens & Stationary", "Pens & Stationary"), ("Arts & Crafts", "Arts & Crafts"), ("Notebooks & Fullscapes", "Notebooks & Fullscapes"), ("Files & Folders", "Files & Folders"), ("Others", "Others") ] cname = models.CharField(max_length=50, choices=Categories) cicon = models.CharField(max_length=50,default="fa fa-lg") cslug = models.SlugField(max_length=200, db_index=True, unique=True) def __str__(self): return self.cname def get_absolute_url(self): return reverse('store:product_list_by_category',args = [self.cslug]) # Create your models here.""" class Product(models.Model): pimg = models.ImageField(upload_to='pics',null = True, blank=True) pname = models.CharField(max_length=100) pslug = models.SlugField(max_length=50, db_index=True, unique=False) pprice = models.DecimalField(max_digits=10, decimal_places=2) pstock = models.BooleanField(default=True) pcats = models.ForeignKey(Category, on_delete=models.CASCADE) pdesc = models.TextField() def __str__(self): return self.pname def get_absolute_url(self): return reverse('store:product_details',args = [self.id,self.pslug]) class ExploreItems(models.Model): eitname = models.CharField(max_length=50) eitimg = models.ImageField(upload_to='pics') eitdesc = models.CharField(max_length=200) def __str__(self): return self.eitname class Review(models.Model): rsummary = models.CharField(max_length=500) mreview = models.TextField() rproduct = models.ForeignKey(Product,on_delete=models.CASCADE) ruser … -
Python virtual environment doesn't work the second time
Yesterday I started to study Django. I created a virtual environment and it worked. Today I ran the activate script, the env name appears on terminal, but when I try to execute "django-admin --version" I got this: Fatal error in launcher: Unable to create process using '"d:\documentos\dev\python\ecommerce-example\django-tutorial\venv\scripts\python.exe" "D:\Documentos\dev\python\django-tutorial\venv\Scripts\django-admin.exe"> --version' I've already search, but I didn't found anything about activate venv for the second time. Can someone help me? -
Showing python console on webpage with django
I am have a function like this: def myfunc(x): # Loop over the imagePaths for i in range(N): # do somthing print("[INFO] processing {}/{}".format(i + 1, N)) print(name) print(total, " things I have done.") the user will fill a form on my webpage and then I will run this function. Running it would take a bit of time, so I want to show the progress (the prints in the myfunc). I saw some answers in How do I redirect my Python console's output to a web page in Django? and How can you display the results of a script in real-time for a Django 1.4 website?. But honestly I'm not that good at Django nor JavaScript to know what I should do with the information above. I also understand that many version of this question has been asked but I couldn't figure out how to use their answer. -
Django migrations not persisting
My django app is containerized along side postgresql. The problem is that migrations do not seem to be persisting in the directory. Whenever I run docker exec -it <container_id> python manage.py makemigrations forum, the same migrations are detected. If I spin down the stack and spin it back up the and run makemigrations again, I see the same migrations detected. Changes to the fields, adding models, deleting models, none ever get detected. These migrations that do appear seem to be getting written to the database, as when I try to migrate, I get an error that there are existing fields already. But if I look at my migrations folder, only the init.py folder is present. All the migrate commands add no changes to the migrations folder. I also tried unregistered the post model from the admin and spinning up the stack, yet I still see it present in the admin. Same things with changes to the templates. No change I make sticks from inside docker seems to stick. *Note this problem started after I switched to wsl 2 and enabled it in docker desktop (windows) -
order list is not displayed on order_list.html?
order history is not displayed on orders_list.html file. order_list.html {% if order_details %} <table class="table table-striped"> <thead> <tr> <th>Order Number</th> <th>Order Date</th> <th>Total Amount</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for order in order_details %} <tr> <td>{{ order.id }}</td> <td>{{ order.created|date:"d M Y" }}</td> <td>{{ order.total }}</td> <td><i class="fas fa-check"></i></td> <td><a href="">View Order</a></td> </tr> {% endfor %} </tbody> </table> {% else %} <p> You have not placed any orders yet. <br><br> <a href="{% url 'home' %}" class="btn btn-secondary">Continue shopping</a> </p> {% endif %} views.py file def orderHistory(request): global order_details if request.user.is_authenticated: email = str(request.user.email) order_details = Order.objects.filter(emailAddress=email) return render(request, 'orders_list.html', {'order_details': order_details}) the result to above is ORDER HISTORY You have not placed any orders yet. Continue shopping this shows that the if statement always returns false while there are rows of orders in order table. i expect the result to be the list of orders placed from the account. -
Sending emails via gmail is too slow - Django
I'm using the below to connect to gmail server to send emails. EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' The email is working perfectly fine, but it takes around 20 - 30 secs for the process to complete. I know many are facing this issue, but I didn't find a proper answer for this. -
Django Json Response - Problems at showing count fields
I'm having problems to show my fields correctly to a JSON. This is the view function query = "SELECT sede.id, sede.Nombre as nombre, count(distinct(mesa.id)) as 'mesas' , count(distinct(plan.id)) as planes, count(distinct(diagnostico.id)) as diagnosticos FROM ubicacion_sede sede join ubicacion_subregion subregion on subregion.Sede_id = sede.id join ubicacion_region region on region.id = subregion.Region_id join ubicacion_pais pais on pais.id = region.Pais_id join comunidades_comunidad comunidad on comunidad.Subregion_id = subregion.id join comunidades_mesa mesa on mesa.Comunidad_id = comunidad.id and mesa.Estado = 'Activo' left join comunidades_planesdeaccion plan on plan.Mesa_id = mesa.id left join comunidades_diagnostico diagnostico on diagnostico.Mesa_id = mesa.id group by sede.id, sede.Nombre" respuesta = Sede.objects.raw(query) respuesta_serialized = serializers.serialize('json', respuesta, fields=('nombre', 'mesas', 'planes', 'diagnosticos')) content = JsonResponse(respuesta_serialized, safe=False) and this is the JSON I get from this "[{\"model\": \"ubicacion.sede\", \"pk\": 1, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 2, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 6, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 12, \"fields\": {}}, {\"model\": \"ubicacion.sede\", \"pk\": 22, \"fields\": {}}]" Here I have two problems Why i'm not getting the files i want Why I get the JSON formatted like \" and not " Thanks in advance for your answer, I've been turning SOF upside down but couldn't get the solution -
Django - Unable to remain in the view assigned to LOGIN_REDIRECT_URL after redirecting to back page. I'm using custom AUTH_USER_MODEL
I'm trying to get a custom user model named (UserAccount) working for logging in and logging out My custom user account inherits these two classes UserAccount(AbstractBaseUser, PermissionsMixin) Used django.contrib.auth.views - LoginView and LogoutView in accounts app's urls.py file: from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name="accounts/logout.html"), name='logout'), path('signup/', views.signup, name='signup'), ] When I login, as per the setting LOGIN_REDIRECT_URL, I'm able to get redirected to the landing_page. AUTH_USER_MODEL = 'accounts.UserAccount' LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'landing_page' LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [ 'login', 'logout', 'signup', ] I've used the django-login-required-middleware and also included these two in my settings file: INSTALLED_APPS = [ 'login_required', # along with others ] MIDDLEWARE = [ 'login_required.middleware.LoginRequiredMiddleware', # along with others ] But whenever I hit back button on the browser, it is again taking me back to login page, even after logging in. Can someone please help resolve this authentication issue? -
How to update Chart JS without refreshing using ajax in Django
I wanna update variable for display in chart js without refreshing using ajax. The both variable will sent from view.py graph.html <html> <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> setInterval(function() { $.ajax({ type: "GET", url: "{% url 'updateData' %}" }) .done(function(response) { // how to coding for update variable in chart // update {{top5StockC|safe}} (response.top5StockC) and {{top5Quan|safe}} (response.top5Quan) }); }, 5000) </script> <script> // top5 of product best seller var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockC|safe}}, // need to update variable datasets: [{ label: 'quantity of products', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5Quan|safe}} // need to update variable }] }, .... </script> <html> Thank for your answering -
How to auto-fill and display data in Django from fields of User model to another model from a different app?
I'm new in Django and right now I'm working to a payment application project for registered users and for non-registered users. My User model has some required fields from the paper invoice like below: #users/models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=100, blank=False, null=False) phone = models.CharField(max_length=11, blank=False, null=False) clientid = models.IntegerField(blank=True, null=False, unique=True) Notice that the authentication process is based on e-mail address and the required field from the invoice payment is "clientid, phone, name". The other app called payments has 1 model class for non-registered users and for authenticated users like below: #payments/models.py class Payment(models.Model): invoiceid = models.IntegerField(blank=False, null=False) name = models.CharField(max_length=50, blank=False, null=False) amount = models.DecimalField(decimal_places=2, max_digits=20) email = models.EmailField(max_length=255, blank=False, null=False) phone = models.CharField(max_length=11, blank=False, null=False) clientid = models.IntegerField(blank=True, null=False, unique=False) For both models I'm using crispy forms, for non-registered users is quite easy to make the payment if they fill all the fields. (different templates are used for this actions). What I want to achieve is when the user is registered and wants to make a payment, the fields like "name, phone and clientid should be filled automatically and displayed to the user in read mode only based on the registration user table. … -
admin site list vs tuple django
when customizing admin site we can use list or tuple like @admin.register(Model_name) class Model_nameAdmin(admin.ModelAdmin): list_display = ['a', 'b', 'c'] # using list # lets say a, b, c are fields of model(Model_name) or list_display = ('a', 'b', 'c') # using tuple I'm curious Is there any difference using a list over tuple or vice-versa like performance while retrieving the admin site or something like that. I know tuples are better than lists for performance but we aren't looping here. I've looked at whats-the-difference-between-lists-and-tuples, why-does-django-use-tuples-for-settings-and-not-lists, why-djangos-modeladmin-uses-lists-over-tuples-and-vice-versa, but didn't get my answer. Is it better to use tuple all the time? I'm asking specifically for the admin site. -
comment system in class based view in django showing error
the basic source files are here and i am trying to do it in class based view for further upgrade. My main project is written in class based view and it will be easy to integrate for me. views.py codes are give below: from .models import Post,Comment from .forms import CommentForm from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView,DetailView from django.shortcuts import redirect,render, get_object_or_404 from django.http import HttpResponseRedirect class PostList(ListView): model=Post template_name='home.html' context_object_name='post_list' queryset=Post.objects.all() class PostDetail(DetailView): model=Post def get_queryset(self): queryset = super(PostDetail, self).get_queryset() post=Post.objects.all() comments=Comment.objects.filter(post=post) return queryset def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) if request.method == "POST": comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment=comment_form.save(commit=False) comment.post=post comment.save() else: comment_form = CommentForm() context['post']=post.objects.all() context['comments']=comments.objects.all() context['comment_form']=comment_form() template_name='Post_detail.html' return render(request, template_name, context) when i execute the runserver it shows NameError at /post/1/ name 'request' is not defined the models.py is: from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') content = models.TextField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) body = models.TextField() reply=models.ForeignKey('Comment',on_delete=models.CASCADE,null=True) def __str__(self): return self.name the function base view was: def PostDetail(request,pk): post = get_object_or_404(Post, pk=pk) comments=Comment.objects.filter(post=post) if request.method == "POST": comment_form = CommentForm(request.POST … -
Reset many to many fields from model
I want to reset all upvotes from all my Posts with django-orm, don`t know how to write query for that and apply it to the view. Also, maybe it would be better to make separate upvote model than just a field in the Post. class Post(models.Model): author = models.ForeignKey( User, related_name='posts', on_delete=models.SET_NULL, null=True ) title = models.CharField(max_length=100) creation_date = models.DateTimeField(auto_now_add=True) link = models.URLField() upvotes = models.ManyToManyField(User, related_name='upvotes', blank=True)