Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In my blogging website i want to delete a user and all its associated blogs and comments
I deletes a user then all the associated blogs were also deleted but the associated comments are not deleted why comments model is indirectly related to User model using foreign key. Can anyone give me the answer models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class blogpost(models.Model): created_by=models.ForeignKey(User,on_delete=models.CASCADE) topic=models.CharField(max_length=122,null=True,blank=False) title=models.CharField(max_length=250,blank=False) post=models.TextField() likes=models.ManyToManyField(User, related_name='blog_posts') date=models.DateTimeField(auto_now_add=True ) def __str__(self): return ' (' +str(self.created_by)+') Title- '+self.title class Meta: ordering=['-date'] class CommentModel(models.Model): post = models.ForeignKey(blogpost ,related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length = 100) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.title, self.name) class Meta: ordering=['-date_added'] views.py def comment_view(request, pk): if request.method=='POST' and 'comment_button' in request.POST: body=request.POST.get('comment_text') post=blogpost.objects.get(pk=pk) obj=CommentModel(body=body) obj.name=request.user obj.post=post obj.save() return HttpResponseRedirect(reverse('detaildata',args=[str(pk)])) -
Django user registration through mobile number
I am recently started to learn django and REST API development. Currently I am trying to create a user signup system where user's mobile number will be unique and user will login further using registered mobile number and an OTP. can anybody please guide through the process -
Django channels "Temporary failure in name resolution", and I'm not sure what to do about it
I'm loosely following a tutorial on YouTube, trying to get a basic understanding of implementing channels, and I am having difficulty figuring out this error: django | WebSocket HANDSHAKING /ws/events/ [172.19.0.1:49272] django | INFO 2021-07-10 12:57:11,000 runserver 11 140153597114112 WebSocket HANDSHAKING /ws/events/ [172.19.0.1:49272] django | ERROR 2021-07-10 12:57:12,139 server 11 140153597114112 Exception inside application: [Errno -3] Temporary failure in name resolution django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ django | return await self.application(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ django | return await application(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ django | return await self.inner(dict(scope, cookies=cookies), receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 254, in __call__ django | return await self.inner(wrapper.scope, receive, wrapper.send) django | File "/usr/local/lib/python3.9/site-packages/channels/auth.py", line 181, in __call__ django | return await super().__call__(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ django | return await self.inner(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__ django | return await application( django | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app django | return await consumer(scope, receive, send) django | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__ django | await await_many_dispatch( django … -
Django-atom or Atom-django autocomplete not working after installation
I also had the same problem while trying to use the django-atom autocomplete snippet and after reading different articles on it here is how I go about it. Go to the directory of the installed autocomplete package, in this case here: C:\Users\user.atom\packages\django-atom Go to the snippet folder and you'll find a .cson file, right click and open it with an editor in this case here is the directory: C:\Users\user.atom\packages\django-atom\snippets Copy everything inside the file and go back to the snippets.cson file in .atom parent directory, in this case here: C:\Users\user.atom Right click and open the snippets file with an editor, scroll down and paste everything you copied earlier into the file then save. Bro, now you can enjoy your beautiful snippets. -
Looping through two queryset in django template
I have 3 models, class Candidate(models.Model): full_name = models.CharField(max_length=255) class CandidateProjects(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="projects") project_name = models.CharField(max_length=255) class CandidateTools(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="tools") tool_name = models.CharField(max_length=255) In template, i have the object of Candidate. I want to show Tools and Projects data in a tabular format, like: Can anyone suggest how can i access both models in template only. Thanks.. -
Collect data such as IP and browser agent in Django, HTML form and jQuery
This is how I have defined my Contact form of my website (ignore php-email-form class please): <form action="" id="contactForm" method="post" role="form" class="php-email-form"> {% csrf_token %} <div class="row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required> </div> <div class="col-md-6 form-group mt-3 mt-md-0"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required> </div> </div> <div class="form-group mt-3"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required> </div> <div class="form-group mt-3"> <textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea> </div> <div class="my-3"> <div id="loading" class="loading">Please wait...</div> <div class="error-message"></div> <div id="sent-message" class="sent-message">Your message has been sent. Thank you!</div> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> And this is how I'm intercepting the form: $('#contactForm').submit(function(e){ e.preventDefault() $('#loading').css("display", "block") $.ajax({ type : "POST", url : "/contact/", data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : csrftoken, datatype : "json", }, success: function(){ $('#loading').css("display", "none"), $('#sent-message').css("display", "block"), $('#contactForm')[0].reset() }, }); }); And this is now I'm processing the form: def contact(request): if request.is_ajax(): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_text = request.POST.get('message_text') email_subject = f'Contact Form: {message_subject}' email_from = f'{sender_name} <{sender_email}>' email_to = ['me@gmail.com', ] html_message = f'Name: {sender_name}<br>Email: {sender_email}<p>{message_text}' send_mail(email_subject, '', email_from, email_to, html_message=html_message) response = {} return … -
got an unexpected keyword argument error eventhough it has been described
This might be an silly error but have tried a lot of was but it was not able to be solved. Hope someone can help. Traceback: TypeError at /profile_page/pro UserProfileView() got an unexpected keyword argument 'pro' views.py: class UserProfileView(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') website_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) pinterest_utl = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) def get_absolute_url(self): return reverse('name-of-some-view', kwargs={'pk': self.pk}) def __str__(self): return str(self.user) urls.py: path('profile_page/<str:pro>', UserProfileView, name='profile_page'), -
HTTP_REFERER not in request.META, how to set it?
I am trying to fix csrf protection for my Django views. The CsrfViewMiddleware checks if there is the referer as follows: referer = request.META.get('HTTP_REFERER') if referer is None: return self._reject(request, REASON_NO_REFERER) I am trying to set the 'HTTP_REFERER' in the headers as such: const config = { headers : { "Referer": "https://example.com/", "HTTP_REFERER": "https://example.com/", "Referrer-Policy": "strict-origin-when-cross-origin" } } const fetcherGraphql = (query) => request(serverURl + "/graphql", query, config); Django fails with REASON_NO_REFERER because there is no HTTP_REFERER in the request.META How do I get it in there? Or am I missing something else? -
Server Error (500) in deployment of django project to heroku
Server error 500 on Django when deployed on Heroku when debug is set to False I am using django 3.1.6 -
Printing hello world on the django server using vscode
I am a newbie in django I have been trying to print hello world on the django server and its not responding. I have set the url.py on both the app and project file Set the views.py Still not gotten hello world on the django server. I will appreciate any help -
Recieving Server Error (500) when deploying Django app to Heroku
I've been struggling for days just trying to deploy my site to Heroku. I've referenced many other Stack Overflow questions about this topic, such as: Django Heroku Server Error (500) when I set Debug - False on True it is working fine Heroku/Django deploy: why am I getting an error 500 with successful deploy and static collection? For reference, I was following Heroku's guide on the deployment of Django apps when doing this. Below is the relevant code to this dilemma of mine. base_settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = thekey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['dazzling-kobuk-valley-23546.herokuapp.com','localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', 'basket.apps.BasketConfig', 'account.apps.AccountConfig', 'orders.apps.OrdersConfig', 'checkout.apps.CheckoutConfig', 'mptt', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'hifive.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Static files … -
How to override get_queryset() of ModelAdmin?
I want to override a ModelAdmin to limit some users. The superadmins have all the rights but the others have restricted rights. They can't see/add/modify/delete all objects but only some. Also, the objects they can modify contain a many_to_many field and I want to limit the choices in the list. For this, I overloaded several methods, but I have a problem when I overload get_queryset(). Indeed, it reduces the list of objects, which is perfect in my case but when I click on an object to modify it, I have the following error: MultipleObjectsReturned at /fr/admin/commission/article/26/change/ get() returned more than one Article -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/fr/admin/commission/article/26/change/?_changelist_filters=q%3D Django Version: 2.2.24 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Article -- it returned 2! Exception Location: /home/aurelien/dev/extranet_thourotte/venv/lib/python3.9/site-packages/django/db/models/query.py in get, line 410 Python Executable: /home/aurelien/dev/extranet_thourotte/venv/bin/python3 Python Version: 3.9.5 my ModelAdmin: @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): """ ArticleAdmin to save automaticaly the author """ list_display = ('titre', 'auteur', 'date', 'date_update') list_filter = ('rubriques', 'auteur',) search_fields = ('titre',) exclude = ('auteur',) def get_queryset(self, request): queryset = super().get_queryset(request) if not request.user.is_superuser: rubriques = Rubrique.objects.filter(admins=request.user) queryset = queryset.filter(rubriques__in=rubriques) return queryset def formfield_for_manytomany(self, db_field, request, **kwargs): if not request.user.is_superuser and db_field.name == … -
Save method not working in Django as expected
Purpose: I am trying to setup a small local network monitor with basic UI that pings all the devices enlisted in the db and updates the status. Problem: save() method is not updating the DB. My Model: class Device(models.Model): dev_name = models.CharField(max_length=100) dev_ip = models.CharField(max_length=16) def __str__(self): return self.dev_name def get_absolute_url(self): return reverse('device-detail', kwargs={'pk': self.pk}) Function I wrote to ping the device and update DB: import platform import subprocess from netmon.models import Device from background_task import background @background(schedule=60) def start_monitor(): devices = Device.objects.all() print(">>>>>>>>>>> In Start_monitor <<<<<<<<<<<") for device in devices: if (ping(device.dev_ip)): device.status = "Alive" else: device.status = "Dead" device.save(update_fields=["dev_status"]) I am a Django beginner, please let me know if you need any more details. All answers are appreciated. Thank you -
How to run a web scraping script in Django? The server is not starting
I have a web scraping script written in BeautifulSoup4. The script is supposed to retrieve information after 600 seconds. Now, my app is not starting. I am calling the script from urls.py from django.urls import path from details.task import scrape urlpatterns = [ ... ] scrape() task.py import time from details.scrape import ScrapeFunction def scrape(): ScrapeFunction() time.sleep(600) scrape() The script must be called as soon as the app started. -
How to get user data - django
I have an edit profile page where the user can change the email, because in order to display the error messages correctly, I need to be able to compare the email of this user when entering a new email. In short, I need to get a user email which for some reason I can not do and I need your help. I have been trying to do it for 3 days. There are my codes. views.py @login_required def edit_profile(request, id): # context['DATA_UPLOAD_MAX_MEMORY_SIZE'] = settings.DATA_UPLOAD_MAX_MEMORY_SIZE user = Account.objects.get(id=id) form = UserChangeForm(instance=user) if request.method == "POST": form = UserChangeForm(request.POST, files=request.FILES, instance=user) if form.is_valid(): post_email = form.cleaned_data.get('email') # Extracting the email value from the form if Account.objects.filter(email=post_email).exists(): if Account.objects.filter(email__isnull = False).count(): data = form.save(commit=False) data.is_active = True data.save() messages.warning(request, "Personal data has updated") return redirect('account:editprofile', id) else: messages.warning(request, "Email is already busy") return redirect('account:editprofile', id) else: data = form.save(commit=False) data.is_active = True data.save() messages.warning(request, "Personal data has updated") return redirect('account:editprofile', id) models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) fname = models.CharField(max_length=128) lname = models.CharField(max_length=128) phone = PhoneNumberField(blank=True, null=True, unique=True) bday = models.CharField(max_length=128, blank=True, null=True) country = CountryField(blank_label="Select the country/region you're from", blank=True, null=True) GENDER_CHOICES = ( ("man", "Man"), ("female", "Female"), ("non_binary", "Non-binary"), ("prefer_not_to_say", … -
Django template if tag based on current Url value with username
I'm building a chat room app by following a tutorial. When I enter a room, the url looks like this 'http://127.0.0.1:8000/chatroomname/?username=username'. I want to add a different video for every chatroom, I want to do it with and {% if %} tag in the room.html template: {% if request.get_full_path == "/roomname/" %} <iframe width="560" height="315" src="https://www.youtube.com/watch?v=uilkmUoXoLU" frameborder="0" allowfullscreen></iframe> {% endif %} But this only works if the url looks like this 'http://127.0.0.1:8000/chatroomname/', how do I add the username part in the if tag. If I add an example username and access the room with that username the video doesn't appear. {% if request.get_full_path == "/roomname/?username=exampleusername" %} <iframe width="560" height="315" src="https://www.youtube.com/watch?v=uilkmUoXoLU" frameborder="0" allowfullscreen></iframe> {% endif %} This is the code of the other files: #views.py from django.shortcuts import render from .models import Message def index(request): return render(request, 'chat/index.html') def room(request, room_name): username = request.GET.get('username', 'Anonymous') messages = Message.objects.filter(room=room_name)[0:25] return render(request, 'chat/room.html', {'room_name': room_name, 'username': username, 'messages': messages}) #urls.py from django.urls import path from .models import Message from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] #models.py from django.db import models class Message(models.Model): username = models.CharField(max_length=255) room = models.CharField(max_length=255) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: … -
Return outside function error eventhough it has been indented properly
Hi I know this error is kind of silly but I am new to django. I also have indented the return function properly but it keeps on saying return outside function. I hope someone can help. Trace back: File "C:\simpleblog\ablog\myblog\models.py", line 26 return render(request, 'profile_page.html', {'pro':pro}) ^ SyntaxError: 'return' outside function models.py: class UserProfileView(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null=True, blank=True, upload_to='images/profile/') website_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) pinterest_utl = models.CharField(max_length=255, null=True, blank=True) instagram_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) return render(request, 'profile_page.html', {'pro':pro}) def __str__(self): return str(self.user) -
Django - Using sqlite3 extensions in migrations
I am implementing a text-search in sqlite using FTS5 for a Web Application in which Django is my backend. For those purposes, I would like execute SQL code in a migration that makes use of an sqlite extension called "extension-functions.so", which (uncompiled) can be found on sqlite's own webpage here (An example for such a migration is at the bottom). You can load extensions easily while using the default python sqlite3 library (here an example). However, that is not the type of connection django uses for the migrations in migrations.RunSQL, it uses connections from django.db.connections... I think. And those do not have the load_extension() function of sqlite3.connections ! What I thus want to do is have these extension files loaded into django.db.connections by default, so that the SQL in migration.RunSQL has access to these extension functionalities. Is that possible? How would I do that? Is the only solution to use migrations.RunPython instead to use sqlite3.connections that way? class Migration(migrations.Migration): atomic = False #Necessary to be able to apply trigger migrations dependencies = [ ] operations = [ migrations.RunSQL(sql = """ CREATE TRIGGER some_trigger_name AFTER UPDATE ON some_table BEGIN UPDATE some_table SET col2 = reverse(new.col1) END; """, reverse_sql = """ DROP … -
Minimum requirement for web application software
What requirement user need to access web application related to student performance analysis system languages are python(django) and reactjs. -
How does Djoser JWT login flow works
So I've been trying to use Djoser JWT and I don't know how to login in it. As far as I know you create a request with your login credentials to this url /jwt/create/ and get the access and refresh token and maybe get the user object from /users/me/. This is where I got stuck, where do I go from here? -
How to Sign my HTML document digitally in Django application
In my Django application I have a html file and it should get signed digitally. When a client clicks on a link my html document should open in that tab and highlighting the signing area, then the client click on that portion a popup with text box to enter signature name and select font style or else he can upload his sign image. Can any one please suggest me a better approach to achieve this, I was integrated DocuSign API with my Django application and this DocuSign accepting only pdf documents but I need to get sign on HTML document. -
ModuleNotFoundError: No module named 'router' in django
from django.urls import path,include from myapi.views import NoName from rest_framework import routers router=routers.DefaultRouter() router.register('thes',NoName) urlpatterns = [ path('',include('router.urls')), ] -
Django Ajax: Call a specific python script within a directory of multiple python script
Here's the code in the urls.py: from djangotest.ajax.ajax_test import ajaxTest from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', handlerView), path('ajax/', ajaxTest)] Here's the code in the python script named ajax_test under the ajax folder: from django.shortcuts import HttpResponse def ajaxTest(request): return HttpResponse("Hello World") And here's the javascript: $.ajax({ url: 'ajax/', type: 'get', success: function(data) { alert(data); }, failure: function(data) { alert('Encountered an error'); } }); When I run the server, the site alerts "Hello World" which means the code is correct. Now, my question here is this: Let's say I'll add another python script in the ajax folder named greetings(.py) with the function Greet that returns "Good day!". How do I specify which python script should the ajax call (for example, the greetings.py)? -
Is there a way to filter fields when value of the first field chosen changes?
~ Hope you all are doing great. I was wondering if it is possible to make a multi-level filtering using jquery, json and django forms. Basically I want it so that lets say I chose "Customer" first then "Site" should get filtered based on it, at the same time if I choose Site first then Customer should be filtered based on it instead, and all fields reset when no value is chosen. I could get it to work only if it filters based on one, but when I am choosing Site first I can't get it to work well...I am planning to add more fields in the future too when I get the concept better! Here is my code. views.py def get_cascading(request): cus_id = request.GET.get('cus_id',None) site_id = request.GET.get('site_id',None) if cus_id: customer = Customer.objects.get(id=cus_id) site = Site.objects.filter(customer=customer) print(str(site)) else: site = Site.objects.all() if site_id: site_cus = Site.objects.get(id=site_id) cus_change = Customer.objects.filter(id=site_cus.customer.id) else: cus_change = Customer.objects.all() context = { 'site':site, 'cus_change':cus_change } return render(request, 'ticket/cascading/index.html', context) cascading html {% if cus_id != 0 %} <label for="id_site" class="">Site</label> <select name="site" class="select form-control" id="id_site"> {% for obj in site %} <option value="{{obj.id}}">{{obj.name}}</option> {% endfor %} </select> {% elif site_id != 0 %} <label for="id_customer" class="">Customer</label> … -
Django class AccessMixin permission based in groups
I have many users belongs to groups. so I want to make permission of the classes based on the user’s group. example I have many groups like (‘Student’,‘Doctors’,‘Geology’,‘Civil engineer’) and I have this class class Div_EP(LoginRequiredMixin, PermissionRequiredMixin, ListView): permission_required = ('Doctors','Civil engineer') model = Botomeqpts template_name = 'Home/Div_EP.html' so the users allowed to visit this page are , Doctors and Civil engineer only. How I correct this in this class?