Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manage Parent Child Category in django
Django Models I'm working on a e-commerce website where I need to assign child category to a parent category like if when add product admin will select parent category then its relevant child category should come to select in I tried doing like this but didn't able to find solution class MainCategory(models.Model): # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class SubCategory(models.Model): # perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True) # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class Items(models.Model): # main = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # name = models.CharField(max_length=255) Please Share How I can do that -
How can I solve this error [missing 1 required positional argument: 'request']?
When I tried using a session on DetailView class in the Django project, I have an error and it does not work because of the missing a request object. in that case, how should I do? Would you mind telling me how should I solve this problem? Thank you in advance. the error code TypeError at /detail/41/ check_session() missing 1 required positional argument: 'request' views.py class DetailView(LoginRequiredMixin, generic.DetailView): model = sampleDB template_name = 'detail.html' def check_session(self, request): if not 'history' in request.session: request.session['history'] = {'user': self.request.user, 'id': self.kwargs['pk']} def get_context_data(self, **kwargs): self.check_session() context = super().get_context_data(**kwargs) return context Development environment Python: 3.7.5 Django: 2.2.2 -
When creating a new user in /admin using the django rest framework, the users password is not encrypted
I built an API using the Django rest framework. When you access the /admin page and are logged in as a superuser you have the ability to create new user profiles. However, creating one from the /admin tab means that when the users profile is created the password that is used does not get encrypted like it usually would if created from the /API tab. What do I need to add to encrypt the users password even if it created in the /admin tab? If I need to upload any code or anything please let me know this is my first time using StackOverflow so I am sorry if things are not formatted the right way. -
How to Validate entering Multiple url in one URLfield In Django?
I am Working with Django URLfields. this is my model: class Settings(models.Model): facebook_url = models.URLField(verbose_name='Facebook URL') linkedin_url = models.URLField(verbose_name='Linkedin URL', blank=True,null=True) twitter_url = models.URLField(verbose_name='Twitter URL', blank=True,null=True) logo_url = models.ImageField(upload_to='logo/', blank=True) class Meta: verbose_name = strings_settings.SETTINGS_VERBOSE_NAME verbose_name_plural = strings_settings.SETTINGS_VERBOSE_NAME_PLURAL db_table = 'settings' def __str__(self): return self.facebook_url So I want that nobody will be able to add multiple url in One field. one facebook url at a time,one linkedin and one twitter. How Can I able to do it. Advanced Thanks. -
FCM-Django what happens to a notification if the app is running?
I'm still fairly new to push notifications and I haven't developed a mobile client for testing. I'm primarily using the methods provided by fcm-django. from fcm_django.models import FCMDevice devices = FCMDevice.objects.all() devices.send_message(title="Title", body="Message", data={"test": "test"}) I know if the app is not in the foreground the user will receive a notification. My question is if the app is actually running, will the user get a notification or will we be able to handle it quietly in the background? Example live updating chats in the backgorund. -
load a html file in a particular div from attribute href in a anchor tag
Div in HTML file <div class="content"> <p class="info">Please choose a category</p> </div> anchor tag with href attribute <a class="menu__link" href="{% url 'Profile' %}">Profile</a></li> My javascript function var gridWrapper = document.querySelector('.content'); function loadDummyData(ev, itemName) { ev.preventDefault(); closeMenu(); gridWrapper.innerHTML = ''; classie.add(gridWrapper, 'content--loading'); setTimeout(function() { classie.remove(gridWrapper, 'content--loading'); gridWrapper.innerHTML = $(".menu__link--current").attr("href") console.log($(".menu__link--current").attr("href")) }, 500); } Output in console is showing the path of the url /Accounts/profile If the ev.preventDefault(); is removed, and commenting the linegridWrapper.innerHTML = $(".menu__link--current").attr("href"), the html page gets loaded but not in the particular content div. The problem is i want to load that particular html page with href attribute in content div. Any Help will be much appreciated. Thank You. -
In Django, the | operator is creating duplicates when I merge two querysets together
This is a really strange thing, because I understand the | operator is supposed to create a union of two querysets without duplicating objects. I'm trying to perform a query search, and getting sets of objects to display on the page. One of these sets are for posts. Here is a snippet of my code: if query: block_list = Block.objects.filter(Q(name__icontains=query) | Q(tags__slug__icontains=query)) user_list = CustomUser.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(username__icontains=query)) post_list = Post.objects.filter(Q(tags__slug__icontains=query)) post_list_by_title = Post.objects.filter(Q(title__icontains=query)) print(post_list) print(post_list_by_title) print(post_list | post_list_by_title) Here is the outcome of the three print commands in cmd. <QuerySet []> <QuerySet [<Post: Post1>]> <QuerySet [<Post: Post1>, <Post: Post1>, <Post: Post1>]> In case you're wondering why I split the post_list by tag and post_list by title, I originally had: post_list = Post.objects.filter(Q(tags__slug__icontains=query) | Q(title__icontains=query)) But when I printed post_list, it still came out to be: <QuerySet [<Post: Post1>, <Post: Post1>, <Post: Post1>]> all the same. Do you have any idea why this could be? -
Django form problem, Repeating a form n times in one template
As title What I want to do is to add a button. After pressing the button, a duplicate form will be added to enter data. Need to add a few pieces of information, just press the button several times! How can I achieve this? -
django to display stored procedure result
I am new to Django.Below is version of Django and used database Django version: 2.1.15, django-pyodbc-azure==1.11.9.0, used sql-server 2012 django-admin startproject item Objective: To take input from user @itemnumber & give that input to EXEC ValidateBusinessrule '@itemnumber' and show result in html page setting.py connection DATABASES =\ { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ETP', 'HOST': '10.*.*.*', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } } item.urls: from django.urls import path from django.urls import path from . import views urlpatterns = [path(r'item/', views.itemnumber, name='index'), ] print("hello1") views.py: from django.db import connection print("yupp") def itemnumber(request): print("hiiiiiiiiii") cursor = connection.cursor() try: Itemnumber = "1234" cursor.execute('EXEC ValidateBusinessrule Itemnumber') result_set = cursor.fetchall() finally: cursor.close() print("hello3") I am not able to go inside def itemnumber(request) in views.py are not executing or in other words not able to print (not printing--print("hiiiiiiiiii")) Currently I am not getting any error while running above code. How to retrieve stored procedure table result to my html page form? -
django send file after a process is done
I am trying to run a function foo on an uploaded file then send the output file to the user, I have written a functions to store the uploaded file and send emails (both works),I need help in attaching the output file once the function is completed foo() which takes about 1-2 hours to complete. this is my views.py import time from django.shortcuts import render from django.core.files.storage import FileSystemStorage from django.core.mail import send_mail def My_Upload(request): if request.method=="POST": uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(name=uploaded_file.name,content=uploaded_file) context = {'Name':name} #function return render(request,'my_app/homepage.html',context=context) return render(request,'my_app/upload.html',) def send_email_to(filename=None): foo(filename) send_mail("Your file is ready", "Here is your file", 'example@gmail.com', ['1234@gmail.com'],fail_silently=False) def foo(filename): #run some math on the file #creates a f'{filename}_done.csv' time.sleep(300) pass is there a way to do this, if not what alternatives do I have for accomplishing this? -
Django url collisions
Using Django==2.2.11, djangorestframework==3.8.1 Thank you for reading! The urls I am using that have the collision: urlpatterns = [ . . . url( r'^some-path/(?P<pk>\w+)$', views.MyViewSet.as_view({'get': 'retrieve'}) ), url( r'^some-path$', views.MyViewSet.as_view({'post': 'create'}), ), ... ] I am using postman to test each path, and it seems like there is a collision between these two urls. Using this url with a GET, would work: http://my_domain.com:8000/some-path But POST with same url (and with a valid payload) would throw error: WARNING 2020-03-28 19:13:57,288 "POST /some-path HTTP/1.1" 405 41 And response: {"detail": "Method \"POST\" not allowed."} I urls are swapped in order, then the POST would work, and GET would throw a similar error. I looked at this post: 405 POST method not allowed I would gladly add the view code - but I am pretty sure the issue is with the urls, since they each work when swapped order. Will add it upon request. Thank you! -
Django DRF FCM: Live Chat passively notify mobile client
I'm using fcm-django to send push notifications. Docs: https://fcm-django.readthedocs.io/en/latest/# I usually send notifications using the send bulk message method: from fcm_django.models import FCMDevice devices = FCMDevice.objects.all() devices.send_message(title="Title", body="Message", data=data) But I need a way to discrete notify the app to update chat without having to notify the user everytime. Example when they're actually in the chat. Any known solutions for this? -
How does Django Rest Framework permission_classes work?
I don't understand why the permission_classes attribute of a GenericView is a list. Say why is it permission_classes = [IsAdminUser] and not permission_class = IsAdminUser ? Also can I put 2 or more elements in the list, if so how do I interpret this? permission_classes = [IsAdminUser, IsAuthenticated] Is the snippet above the same as permission_classes = [IsAdminUser & IsAuthenticated] ? Also how should I interpret bitwise OR on the permissions? permission_classes = [IsAdminUser | IsAuthenticated] Thank you -
Django serializers vs rest_framework serializers
What is the difference between Django serializers vs rest_framework serializers? I making a webapp, where I want the API to be part of the primary app created by the project. Not creating a separate App for the API functionality. Which serializer do I need to use for Django views and models, and at the same time will work for the API? from django.core import serializers https://docs.djangoproject.com/en/3.0/topics/serialization/ from rest_framework import serializers https://www.django-rest-framework.org/api-guide/serializers/ -
Why we shouldn't keep our code in our web server's root folder?
I started learning Django, in official website(as you can see from the image below) it says we shouldn't keep our code in server's root folder but we need to keep it somewhere outside the root folder. I didn't understand two things 1) How we will be able to run our project without keeping the code in root folder? 2) How is it safe to keep the code in /home/mycode folder than keeping it in /var/www ? -
Can "list_display" show users input on django admin page?
I need to see user's input display on django's admin page, from what i have read, I need to use list_display but there is nothing appearing on admin page. Maybe there is a problem in the views.py but everything looks good. Here is my code: Views.py def process_e(request): if request.method == 'POST': if request.POST.get('website_name') and request.POST.get('product_name') and request.POST.get('phone_number') and request.POST.get('website_details') and request.POST.get('website_content'): post=Enterprise() post.title= request.POST.get('website_name') post.content= request.POST.get('product_name') post.content= request.POST.get('phone_number') post.content= request.POST.get('website_details') post.content= request.POST.get('website_content') post.save() return render(request, 'enterprise.html') else: return render(request,'enterprise.html') Admin.py from django.contrib import admin from service.models import Enterprise class PaymentsAdmin(admin.ModelAdmin): list_display = ('website_name', 'product_name', 'phone_number', 'website_details', 'website_content') admin.site.register(Enterprise, PaymentsAdmin) Models.py from django.db import models class Enterprise(models.Model): website_name = models.CharField(max_length=50) product_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) website_details = models.CharField(max_length=200) website_content = models.CharField(max_length=200) Html <div class="form-group"> <label>Website name</label> <input type="text" name="website_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label>Product name (if there is)</label> <input type="text" name="product_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label>Phone number</label> <input type="text" claa="phone_name" class="form-control" placeholder="First name"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">What kind of content should your website upload?</label> <textarea class="form-control" name="website_content" rows="3"></textarea> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Website details</label> <textarea class="form-control" name="website_details" rows="3"></textarea> </div> -
Identifying and debugging a getJSON error with Django
I've got an error in my Django app that I can't seem to figure out for the life of me Basically the issue is that my getJSON call is failing in my template and I can't figure out why because I can access the url directly via the browsel and the development server is showing a 200 response as well. Here's my view def test(request): cases = ConfirmedCase.objects.all() cases = read_frame(cases, fieldnames=['provice_state', 'country_region', 'confirmedcases','date']) cases['date'] = pd.to_datetime(cases['date']) globaltrend = globaltrend.groupby('date')[['confirmedcases','1_day_growth']].sum().reset_index() globaltrend['date'] = globaltrend['date'].dt.date #convert back to date globaltrend= globaltrend.to_dict(orient='list') data = {} data['chart_data'] = globaltrend data = json.dumps(data, default=str) return HttpResponse(data, content_type='application/json') Here's the url from tracker import views as tracker urlpatterns = [ path('test/', tracker.test, name="test"), ] If I go to http://127.0.0.1:8000/test/ in the browser, everything works fine and I see { "chart_data": { "date": [ "2020-03-26", "2020-03-27" ], "confirmedcases": [ 66885, 69030, ], "1_day_growth": [ 3.21, 3.18, ], } } Here's my script in my template/html file <script > $(document).ready(function(){ var url = '{% url "test" %}' $.getJSON(url, function(d) { console.log("working"); alert('yay') }).done(function(d) { console.log("done"); }).fail(function(d) { console.log("error"); console.log(url); }).always(function(d) { console.log("completed regardl"); }); }); </script> This keeps throwing an error (and I dont see the alert), even … -
Django Pass Multiple Arguments Into Sitemap URL
I would like to take the tc_accept_specific_version named URL from https://github.com/cyface/django-termsandconditions/blob/master/termsandconditions/urls.py#L67-L71 and pass in the slug (site-terms) and version_number (1.0) into my sitemap.xml file so that /site-terms/1.0/ gets put onto the end of the /terms/accept/ link. How do I do this? Currently, the code below is able to only pass in one argument instead of two: class StaticViewSitemap(sitemaps.Sitemap): priority = 0.9 changefreq = 'always' def items(self, *args): return [ ('tc_view_page', {}), ('tc_accept_page', {}), ('tc_email_page', {}), ('tc_accept_specific_version_page', {'slug':'site-terms'}), ('tc_view_specific_page', {'slug':'site-terms'}), ] def location(self, obj): name, kwargs = obj return reverse(name, kwargs=kwargs) Desired Result: <url> <loc>http://www.example.com/terms/accept/site-terms/1.0/</loc> <changefreq>always</changefreq> <priority>0.9</priority> </url> -
How to perform calculations in Django class-based views?
I used Django class-based views to create a simple web application. In this app, a user submits length and width of a building, the app calculates the area and stores it in the database. After submission the user is redirected to the 'results' page where he can see his inputs and result. I'm not sure how to implement such calculation function in generic views. My Models: from django.db import models class Building(models.Model): length = models.IntegerField(default=1) width = models.IntegerField(default=1) area = models.IntegerField(default=1) def __str__(self): return self.name My Forms: from django import forms from .models import Building class BuildingForm(forms.ModelForm): class Meta: model = Building fields = ('length', 'width', 'area') My Views: from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse, reverse_lazy from .models import Building from .forms import BuildingForm from django.http import HttpResponseRedirect, HttpResponse class BuildingListView(ListView): model = Building context_object_name = 'buildings' class BuildingCreateView(CreateView): model = Building form_class = BuildingForm success_url = reverse_lazy('results') class BuildingUpdateView(UpdateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building_changelist') def calculation(request): length = request.POST.get('length', False) width = request.POST.get('width', False) area = length * width Building.objects.create(length=length, width=width, area=area,) return HttpResponseRedirect(reverse('results')) Can someone share a good example related to my question, or help me to implement this function … -
How to connect the views functions with two templates in django?
In one of my views, I have a function that brings some information of some users. Lets say that in the template (Template A) the users are displayed on a table, and each of them has a button. If you click the button, you will be redirected to another template (Template B). What I want to do is that when you click on the button and sends you to the other page, I want to display the information of that user. How do I do that? -
How to test function that checks and login temporary user - Django
Hello I'm trying to test function that takes temporary user id (if exists) from session and log the user in. def check_if_temp_user_exists_and_log_in(request): temp_user = request.session.get('temporary_user_id', None) if temp_user: u = User.objects.get(pk=temp_user) return login(request, u) Here is my uncomplete unittest. I don't know, what login() returns, so I am not able to finish the test code. import unittest from django.test import RequestFactory from django.contrib.sessions.middleware import SessionMiddleware class AnonymousOrRealTestCase(unittest.TestCase): def test_check_if_temp_user_exists_and_log_in(self): request = RequestFactory().get('/') # adding session middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.session['temporary_user_id'] = '1' result = check_if_temp_user_exists_and_log_in(request) self.assert ??? Can you help my please? Thanks a lot :) -
Filtering posts by three components logic issue
Code is working fine, but I have one little problem in filtering. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') if VideoPost.objects.filter(school=school_slug).filter(category=category_slug).filter(approve = 1).exists(): posts = VideoPost.objects.all().filter(approve = 1) if school_slug: posts = posts.filter(school=school_slug) if category_slug: posts = posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) return render(request, 'stories/no_post.html') 4th code line makes it to show the posts when it has both school and category are set only. How could I use that line to be working with one filter is applied? -
not working running python manage.py rusnerver
when runninge that command python manage.py rusnerver i get this error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? i try to pip install mysqlclient and got that Command "C:\Users\xavi6\PycharmProjects\LES\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\xavi6\\App Data\\Local\\Temp\\pip-install-8q8y5ra6\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\ n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\xavi6\AppData\Local\Temp\pip-record-zvgp3gov\inst all-record.txt --single-version-externally-managed --compile --install-headers C:\Users\xavi6\PycharmProjects\LES\venv\include\site\py thon3.7\mysqlclient" failed with error code 1 in C:\Users\xavi6\AppData\Local\Temp\pip-install-8q8y5ra6\mysqlclient\ Im using pycharm and i think i try everything, pls help me. Thanks for help Andre. -
Formset invalid but 'Save' saves parent model and closes page
I've been using Django for a while - but I'm new to formsets. I have a formset 'payment' on a parent model 'invoice'. If the user enters a payment but forget the payment date (which is required) the page still saves the invoice and then closes. I can see from form_valid that formset.is_valid() is False. I can see the error raised if I print it in console: [{}, {}, {'paymentdate': ['This field is required.']}, {}]. I can even see the validation show up on the page right before is closes. How do I keep the page from closing when there is a validation error? -
How to check username exists or not in wiew.py without forms.py?
How to check username exists or not in wiew.py without forms.py, if USERNAME_FIELD = 'email' in Django settings? in models.py I create accounts model and USERNAME_FIELD = 'email' so now when I trying check username with User.objects.filter(username=username).exists() it returns email address, so how I can check if the username already exists in the database?