Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add dynamic dropdown menu option in django
admin.py from django.contrib import admin from .models import ReportModel # Register your models here. @admin.register(ReportModel) class ReportAdmin(admin.ModelAdmin): list_display=('url', 'width', 'height', 'name') forms.py from django import forms from .models import ReportModel from django.db import models class ReportForm(forms.Form): width = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'})) height = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'})) url = forms.URLField(max_length=300) name = forms.CharField(max_length = 50) class Meta: model = ReportModel fields = [ "url","width","height","name"] urls.py from django.contrib import admin from django.urls import path, re_path from django.conf.urls import url from .import views app_name = 'report' urlpatterns = [ url(r'^reporttest/$', views.reporttest, name='reporttest'), url(r'^add/$', views.add, name='add'), ] view.py from .forms import ReportForm from .models import ReportModel from django.shortcuts import render, redirect def reporttest(request): form = ReportForm(request.POST) return render(request, 'report/add_report.html',{'form':form}) def add(request): report_items={} form = ReportForm(request.POST) url =request.POST['url'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] if form.is_valid(): if ReportModel.objects.filter(url=url).exists(): return render(request, 'report/add_report.html', { 'form': form, 'error_message': 'URL already exists.' }) elif ReportModel.objects.filter(name=name).exists(): return render(request, 'report/add_report.html', { 'form':form, 'error_message': 'Report name already exists.' } ) else: report_models=ReportModel(url=url,width=width,height=height,name=name) report_models.save() print(report_models.name) report_items={'url':request.POST['url'], 'width':request.POST['width'], 'height':request.POST['height'], 'name':request.POST['name']} return render(request, 'report/report_one.html', report_items) else: return render(request, 'report/add_report.html',{'form':form}) report_one.html {% block content %} <body> <iframe src = "{{url}}" width= "{{width}}" height= "{{height}}" frameborder="0" allowfullscreen allowtransparency ></iframe> </body> {% endblock %} add_report.html {% extends "student/base2.html" %} {% block content %} … -
Can I link my customer model to my user model?
I'm working an a django e-commerce website where a user has to be a customer. But when I create a new user, it assigns it to the the superuser not the new user and get this error: Exception Value: User has no customer. But i can also go to my admin panel and re-assign the customer to the user. django admin panel How can I fix this please? My customer model class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) def __str__(self): return self.name members/views.py to create new user and customer from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from shop.models import Customer from django.views.generic import CreateView from .forms import CreateCustomerForm # Create your views here. class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/signup.html' success_url = reverse_lazy('customer') class CreateCustomerView(CreateView): form_class = CreateCustomerForm template_name = 'registration/customerProfile.html' success_url = reverse_lazy('login') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) My shop view def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'shop/shop.html', context) -
Django Middleware vs Django view
I have developed a Django view which takes in certain parameters as input and Creates an issue on JIRA My manager is now asking me to implement this view as middleware. I think that this is not necessary as we should invoke this view only when needed(like when user wants to create JIRA issue) in normal way instead of including this as middleware. I am new to the middleware concept and I want to understand if there is any added advantage of calling this view via middleware vs direct view call. Please suggest. -
Error Django polls app command makemigration polls
I am facing an error each time I run this command as django beginner when creating polls up I don't know if I am missing something please refer it back to me I really need help. py manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package -
How to use ImportExportModelAdmin in django Admin page
I am trying to implement import and export in Django admin.i am getting below error. admin.site.register(ShiftChange,ShiftChangeAdmin) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 117, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model ShiftChange is already registered with 'apple.ShiftChangeAdmin'. I have referred(https://stackoverflow.com/a/13709239)but don't know how to unregister.Please find the below admin.py file. from django.contrib import admin from apple.models import ShiftChange,RMSI from import_export.admin import ImportExportModelAdmin # Register your models here. @admin.register(ShiftChange) class ShiftChangeAdmin(ImportExportModelAdmin): pass @admin.register(RMSI) class RMSIAdmin(ImportExportModelAdmin): pass class ShiftChangeAdmin(admin.ModelAdmin): list_display=['ldap_id','Vendor_Company','EmailID','Shift_timing','Reason','last_updated_time'] ###Adding this line so that we Can Search/filter user result in case of any changes or to Check last time when he updated####### search_fields = ('ldap_id', 'EmailID','Shift_timing') admin.site.register(ShiftChange,ShiftChangeAdmin) class RMSIAdmin(admin.ModelAdmin): list_display=['ldap_id','Vendor_Company','EmailID','Shift_timing','Reason','last_updated_time'] ###Adding this line so that we Can Search/filter user result in case of any changes or to Check last time when he updated####### search_fields = ('ldap_id', 'EmailID','Shift_timing') admin.site.register(RMSI,RMSIAdmin) Any help on this will be highly appreciated. -
Why did my Django not add a pk to my model?
from django.db import models class User(models.Model): username = models.CharField('Username', max_length=240) avatar_url = models.CharField(max_length=2000, null=True, blank=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def __str__(self): return self.username I made a Django app that uses this simple model and it should have auto added pk hovewer when I inspect it in my api I don't see it. (avatar url is there because I intend to use Facebook api to get the user) -
How to write urls in static format in django
I am unable to upload style="background-image:url(images/home_slider.jpg)" file in django. I have made two changes in settings .That is as follows: STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,'assets') I also tried this style=" {% static'background-image:url(images/home_slider.jpg)' %}" But unable to remove error. -
Feature-testing a REST API with unittest in Django
In our Django project, we have some API views that are defined in urls.py like this: path('api/calendar/calendar_data', calendar_api.serve_data), and our calendar_api is an instance of CalendarAPI, which is instantiated above: from main.calendar_api import CalendarAPI from caldav import DAVClient ... calendar_api = CalendarAPI(client=DAVClient(...)) In the CalendarAPI class we have a method that fetches data from a remote CalDAV calendar using the caldav library like so: class CalendarAPI(ApiEndpoint): ... def __init__(self, client): self.caldav_client = client def _get_event_list(self): return self.caldav_client.principal().calendars()[0].events() We wish to mock this method in a way such that _get_event_list returns a predefined array. Our test case looks like this: from unittest.mock import patch from django.test import SimpleTestCase class TestCalendar(SimpleTestCase): @patch('main.urls.CalendarAPI') def test_response_format(self, calendarapi_mock): calendarapi_mock._get_event_list.return_value = mocked_calendar_events response = self.client.get('/api/calendar/calendar_data', format='json') # fails test if response does not match mocked_calendar_events self._compareResponse(response, mocked_calendar_events) No matter what we try, we can't get mocking to work. If anyone knows of a better way to instantiate classes in urls.py in light of mocking, please let us know! -
Django Query Multi Table
I'm trying to do a form query on a field and the goal is to get all the kids enrolled in all the teachers classes in this drop down menu. The query I have right now is getting all the classes a teacher is enrolled in . However how do I retrieve the kids within those classes. I attached a picture to so you can visually see how I linked the tables. FORMS.PY class Select_Student_Phone_Log_Form(forms.ModelForm): class Meta: model = PhoneLog fields = ('student_ps',) labels = {'student_ps':_('Student Name') } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super (Select_Student_Phone_Log_Form,self).__init__(*args,**kwargs ) students = SectionEnrollment.objects.filter(section_id__teacher_username = self.user) self.fields['student_ps'].queryset= students MODELS.PY # Section Information Stored class Section(models.Model): sectionpsid= models.CharField(primary_key = True, default = "", max_length = 50) schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = "" ,) coursepsid = models.ForeignKey(Course,on_delete = models.CASCADE, default = "" ,) termpsid = models.ForeignKey(Term,on_delete = models.CASCADE, default = "" ,) section_number = models.CharField(default = "", max_length = 50) expression = models.CharField(default = "", max_length = 50) external_expression= models.CharField(default = "", max_length = 50) staffpsid = models.ForeignKey(Staff,on_delete = models.CASCADE, default = "" ,) gradebooktype = models.CharField(default = "", max_length = 50) teacher_username = models.ManyToManyField(User) # Creation of Classrooms and Assigned Teachers class … -
My dynamic images are removed from Heroku app in few hours
I recently added my first app to Heroku, but after few hours my dynamic media files get disappeared. I am using Django 3.1. Please help!! -
import data repeatedly into Django models using python and SQL
I researched about importing csv data into Django models and there was no mention of SQL. I just want to check if this method has any problem. I have many csv files which need to be uploaded into MySQL database every day. I wrote a python and SQL script to clean the data and then save them into MYSQL database and this works fine. I want to use the data to generate some charts to display in Django. I don't want to use two databases. So I would like to store the data in Django models. My question is if it is fine to create an app and models in Django and continue to use the python and SQL script to insert data. Can I use MYSQL workbench to create the tables of my data and do I have to use Django models.py to create the tables? -
AttributeError: module ' ' has no attribute 'ProfileView'
This is my first website on django, i keep reviewing the code and reading the documentation but not been able to find the bug. #APPS/ACCOUNTS/URLS ``` code ``` from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name="accounts" urlpatterns = [ path("accounts/profile", views.ProfileView.as_view(), name="profile"), #Django-AUTH path( "accounts/login", auth_views.LoginView.as_view(template_name="accounts/login.html"), name="login" ), path("accounts/logout", auth_views.LogoutView.as_view(), name="logout"), ] -
Django – Require at least one instance of ManyToOne model
Is it possible to require at least one ManyToOne instance to a model when it's (first) saved? The idea is, to have a product that can have a price history (hope using a separate, loosely-coupled model for this is the right approach); so in order to add a product, at least one price should be required. I read that it's smarter to put this kind of validation into clean rather than save, as ValidationErrors are not raised from the latter and it's simply "better by convention". Not 100% sure where to draw the line regarding those two methods yet though. Currently trying to get it to work with Django admin; code looks as follows # models.py class Product(models.Model): name: str = models.CharField(max_length=128) def clean(self): if self._state.adding: if not self.prices.count(): raise ValidationError({ 'prices': ('At least one product price is required'), }) class ProductPrice(models.Model): product: Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') price: float = models.FloatField() created: datetime = models.DateTimeField(auto_now_add=True) # admin.py class ProductPriceInline(admin.TabularInline): readonly_fields = ('created',) model = ProductPrice extra = 3 can_delete = False @admin.register(Product) class ProductInline(admin.ModelAdmin): model = Product verbose_name = 'Product' inlines = [ProductPriceInline,] And getting ValueError ProductForm has no field named prices. Also tried using a constraint on Product … -
Django REST framework throttling class or a middleware
I've been studying how to use the Django REST framework with API key addon for a use-case: I need to create logs of each API key that sends a request to each endpoint and base on type of account how many request is able to do it by each day. I've been between using a throlling class but that seems to work for every API key but not depending on the type. Or create middleware that controls with table on the DB how many requests a type of API key is allowed to use. Which of these approchs is better in this use-case or different a approch? -
To run a django live website on development mode
My website is up and running in Digital Ocean build on Django, python. I want to make some updates to it. I want to run the website in development mode. I have 3 different setting for development, production and testing.wsgi.py nd asgi.py re used for deployment. How to i change the setting from production to developemt? What re the files i should change. This site was not built by me. -
Graphene creates unique ids
Here in relay tutorial they say: Graphene creates globally unique IDs for all objects. You may need to copy this value from the results of the first query Those ids look like this SW5ncmVkaWVudE5vZGU6MQ==. And when quering a list of item in id field one can see that ids. How can I get normal (int) ids? Or frontend should convert int ids into string ids? -
Created Signup Page for my project and used User model but after signing in the data is not getting saved in admin
Trying to create Signup Page and store the details of user in User model but the data is not getting saved.I have imported the User model in forms.py.Below is the code of forms.py and view which is created. Views.py from .forms import SignUpForm,LoginForm,PostForm def user_signup(request): if request.method=="POST": form = SignUpForm(request.POST) if form.is_valid(): un=form.cleaned_data['username'] fn=form.cleaned_data['first_name'] ln=form.cleaned_data['last_name'] em=form.cleaned_data['email'] var=User(username=un,first_name=fn,last_name=ln,email=en) var.save() form = SignUpForm() else: form= SignUpForm() return render(request,'Blog/signup.html',{'form':form}) forms.py from django.contrib.auth.models import User class SignUpForm(UserCreationForm): password1=forms.CharField(label='Password',widget=forms.PasswordInput(attrs={'class':'form-control'})) password2=forms.CharField(label='Password Again',widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields=['username','first_name','last_name','email'] labels={ 'first_name':'First Name', 'last_name':'Last Name', 'email':'Email' } widgets={ 'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}) } -
Authentication issues - request.user and request.isauthenticated is not set
I have a Django based application. I have integrated this application with SSO (Azure AD) using the package python3-saml The application URL is redirecting to Azure AD and returning the response. If I check the “request.user” or “request.user.is_authenticated” there is no user details found. For other applications using the plain Django configuration, the same Authentication mechanism worked fine but I have used Wagtail CMS which is causing issues. If I assign “request.user” manually after successful authentication from SSO, “request.user.is_authenticated” still shows false. request.user=request.session['sso_id'] print(request.user) #Prints the Associate ID -> XY123455 print(request.user.is_authenticated) #Returns False -
How to implement a function in django viewsth thats receives vue request
In the client part I have implemented vue, I have a post request with axios as follows, formData.append("file_location", archive.files[0]); formData.append("email", this.email); formData.append("group", this.group); axios.post('http://localhost:8000/files/', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) the post request works perfectly, it saves me the document. In the Django part, in the views I have the following: class DataSerializer(serializers.ModelSerializer): name_back = serializers.SerializerMethodField() class Meta: model = Data fields=( 'file_id', 'file_location', 'zone','section','artifact', 'email', 'group', 'study','study_country','study_site', 'name_back','name','name_email', 'file_view',) print('dentro de la clase') def get_name_back(self, obj): file_name = '' file_name = obj.file_location.name print('file_name:', file_name) return file_name after executing the post request with axios in the terminal I get this: [28/Sep/2020 15:01:45] "POST /files/ HTTP/1.1" 201 366 [28/Sep/2020 15:01:48] "GET /users/profile/ HTTP/1.1" 200 256 [28/Sep/2020 15:01:48] "GET /files/ HTTP/1.1" 200 2410 [28/Sep/2020 15:01:48] "GET /files/ HTTP/1.1" 200 2410 I don't understand why those get requests are realized, I would like to filter only by post request or create a new function -
jquery load() is not loading my django view in another view
So i have got my html and i would like to add my django view in div "radio2". I am using JQuery function Load() but i have a problem because it returns error 404 with get request "http://127.0.0.1:8000/post/afafa/%7B%" and its not loading nothing in div post_detail.html <div class="post__recommendation__posts"> <div id="radio2" class="radio2"> </div> {% for post in posts|slice:":3" %} <div class="post__recommendation__post"> <div class="post__recommendation__post-image"> <img src={% static post.image.url %} alt="shakhur" /> </div> <div class="post__recommendation__post-description">{{post.short_description}}</div> </div> {% endfor %} </div> Js function $(document).ready(function (){ console.log("Loading page") $(".radio-btn").click(function(){ console.log("radio - btn") console.log($(this)[0].id) $.ajax({ url: "/radio/", type: 'POST', data:{ radio: "radio", input: $(this)[0].id }, success: update_item() }) }) }) function update_item() { $('#radio2').load( "{% url 'radio2' %}" ); } View @csrf_exempt def radio_test(request): return render(request, 'blogapp/radio2.html') radio2.html <div class="radiodiv"> This is Radio2 </div> -
ConnectionResetError: [Errno 54] Connection reset by peer Django channels
System check identified no issues (0 silenced). September 28, 2020 - 12:29:32 Django version 3.0.8, using settings 'playg.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. path AnonymousUser [28/Sep/2020 12:43:30] "GET /chat/aman/aman_indresh/ HTTP/1.1" 200 1920 path AnonymousUser Not Found: /ws/chat/aman_indresh/ [28/Sep/2020 12:43:30] "GET /ws/chat/aman_indresh/ HTTP/1.1" 404 2211 Exception happened during processing of request from ('127.0.0.1', 54816) Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in init self.handle() File "/Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/indresh/Documents/Projects/tiktok/server/env/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer Consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): # print(self.channel_layer) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] sender_name = text_data_json['sender_name'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender_name': sender_name } ) # Receive message … -
Signal disconnect not working with multiple dectorators
Here's my setup: class MyModel(models.Model): pass @receiver(post_save, sender=MyModel) @receiver(post_delete, sender=MyModel) def process_stuff(sender, instance, **kwargs): # to some magic pass When I want to disconnect the signal like this: from django.db.models import signals signals.post_save.disconnect( receiver=process_stuff, sender=MyModel, ) ... it does not work. If I comment out the second decorator with post_delete, it works. Any ideas how I could fix this? Thanks! -
How to sum forloop values within Django template?
I have a Django template foorlopp like this: {% load mathfilters %} {% with summ=0 %} {% for p10 in lines %} {{ summ | addition:p10 }} {% endfor %} {% endwith %} summ is zero at the end. How to summ all p10 values here? -
Trailing slash in the URL for robots.txt
I'm developing a website using Django, and Django really likes its trailing slashes so it's easier to give in than to go against it. I planning to also serve the robots.txt file via Django, so I'm wondering: Would it matter for search bots if robots.txt file was located at example.com/robots.txt/ and example.com/robots.txt would redirect to the URL with the trailing slash? Or does this make no difference at all? -
Add fields to Elasticsearch index
I'm using django-elasticsearch-dsl to build the elasticsearch index and I want to dynamically add fields (to the created index cars) that don't exist in MySQL schema I was based on this example and added Website to illustrate what I want to achieve Manufacturer ----< Car ----< Ad ----< Website ----<: One to many relationships In this case, I can easily add manufacturer and ads NestedField/ObjectField to cars index because they are directly linked to Car table Is there a way to add website object to the cars index, other than linking it directly to Car table? When I tried to rebuild the index (python manage.py search_index --rebuild -f) I get the following error django_elasticsearch_dsl.exceptions.VariableLookupError: Failed lookup for key [website] in <Car: Car object (1)> $ python manage.py search_index --rebuild -f Deleting index '<elasticsearch_dsl.index.Index object at 0x10baeb3a0>' Creating index '<elasticsearch_dsl.index.Index object at 0x10baeb3a0>' Indexing 1 'Car' objects Traceback (most recent call last): File "/Users/user/git/django_es_dsl/dedsl_env/lib/python3.8/site-packages/django_elasticsearch_dsl/fields.py", line 52, in get_value_from_instance instance = instance[attr] TypeError: 'Car' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/user/git/django_es_dsl/dedsl_env/lib/python3.8/site-packages/django_elasticsearch_dsl/fields.py", line 58, in get_value_from_instance instance = getattr(instance, attr) AttributeError: 'Car' object has no attribute 'website' During handling of …