Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URLs file redirecting the different URLs to the wrong html files
My Django site isn't working properly. It's hard to explain but when I run my Django web server and go to http://127.0.0.1:8000/hello/ I see "Hello, World!" as expected. But when I go to http://127.0.0.1:8000/dashboard/ I see the same thing, when I should be seeing "Hello". There is to much code to put on stack overflow and it won't make sense so I made a GitHub repo https://github.com/Unidentified539/stackoverflow. -
Django models - how to track a field on an object when value of the field depends on the different users?
I want a Book object with the field is_read, but the value of the is_read depends on the user. When I first created this app I was only thinking of one user (me). class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) is_read = models.BooleanField(default=False) But if the app has multiple users then of course the is_read needs to change according to the user. new models class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) class IsRead(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) book = models.ForeignKey(Book, on_delete=CASCADE) is_read = models.BooleanField(default=False) I think adding the IsRead class will help but I need an IsRead object to automatically be created every time a new user or book is created. Not only that, but every time a new user is created, I have to iterate through all the books. Or if a new book is added, I have to iterate through all the users. This seems like a lot of db work just to keep track of who has read what books. Even if the above is the correct strategy I don't know how to I would do it. I did try to overwrite AdminModel to save the IsRead but this did not work. I did not … -
retrive data according to the dropdown list item selected, in django
I have a dropdown list that is populated with "price range" from the database. I want to show the relevant "price" according to the "Price Range" for example, in the database, I have this row Price Range Price "0-1500" 28 "1501-1750" 30 What I want when I select the range "1501-1750" the corresponding "price" value shown in an input field or paragraph tag. Below are my Model.py, views.py, and home.html files models.py from django.db import models class price_range(models.Model): name = models.CharField(max_length=100, null=False) price = models.IntegerField(null=False) views.py from django.shortcuts import render from range.models import price_range def showobj(request): displayvalues = price_range.objects.all() return render(request, 'range/home.html', {"range":displayvalues}) home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Range</title> </head> <body> <center> <select name="drop1"> <option selected disabled="true">Select the Price Range</option> {% for results in range %} <option> {{results.name}} </option> {% endfor %} </select> </center> </body> </html> -
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping
In a Python function If I write like this, I get Expected expression Pylance in vscode. document = await collection.find({'date': {$gte: {start_date}, $lte: {end_date}}}).to_list(100) Here, date is my field and sart_date, end_date are the dynamic value that specify the specific range of documents I'd like to get from database. And, then because of Pylance error, I changed code like this: query_string = {"date": f'{{date: {{$gte: {start_date}, $lte: {end_date}}}}}'} document = await collection.find(query_string["date"]).to_list(100) And also, writing print(query_string) I get {date: {$gte: '2021-07-15T16:18:46.688Z', $lte: '2021-07-18T12:18:45.258Z'}} on terminal as well that means the value of query_string variable is right. Even If I check with this query in mongodb compass gui app, it returns me the desired data from database. So why getting title's error when the function runs? Please, help me up. For your convenience, the whole function is: # routing in FastAPI @router.get('/api/{start_date}_{end_date}') async def query_date_from_person(start_date, end_date): query_string = {"date": f'{{date: {{$gte: {start_date}, $lte: {end_date}}}}}'} document = await collection.find(query_string["date"]).to_list(100) return document -
Django/react Dockerfile stages not working together
I have a multistage Dockerfile for a Django/React app that is creating the following error upon running docker-compose up --build: backend_1 | File "/code/myapp/manage.py", line 17 backend_1 | ) from exc backend_1 | ^ backend_1 | SyntaxError: invalid syntax backend_1 exited with code 1 As it stands now, only the frontend container can run with the two below files: Dockerfile: FROM python:3.7-alpine3.12 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r ./myapp/requirements.txt FROM node:10 RUN mkdir /app WORKDIR /app # Copy the package.json file into our app directory # COPY /myapp/frontend/package.json /app COPY /myapp/frontend /app # Install any needed packages specified in package.json RUN npm install EXPOSE 3000 # COPY /myapp/frontend /app # COPY /myapp/frontend/src /app CMD npm start docker-compose-yml: version: "2.0" services: backend: build: . command: python /code/myapp/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" networks: - reactdrf web: build: . depends_on: - backend restart: always ports: - "3000:3000" stdin_open: true networks: - reactdrf networks: reactdrf: Project structure (relevant parts): project (top level directory) api (the django backend) frontend public src package.json myapp manage.py docker-compose.yml Dockerfile The interesting thing is when commenting out one service of the Dockerfile or docker-compose.yml or the other, … -
Django: Save a formset with commit=False (Docs say nothing)
With a form its easy, one does something like this: obj = form.save(commit=False) obj.foo = 1234 obj.save() obj.savem_m2m() # If has a ManyToMany field Now for formset is seems much more complicated. The documentation does not shed any light: it only briefly mentions saving and deleting without explaining how. So I checked the sourcecode for a formset.save(): def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m return self.save_existing_objects(commit) + self.save_new_objects(commit) So if one has commit = False, I am guessing one needs to do the work of save_existing_objects, and save_new_objects. Looking at these two functions they are rather large: def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk … -
Python/Django 'OperationalError:no such table: main.auth_user_old' in Django Rest Forest (DRF)
I'm trying to create an RESTful API at the URL /polls/ in Django and DRF using a SQLite database. But I keep getting the error below. I'm using DRF's authentication system. What could be the problem? Thanks in advance! cursor.execute(sql, params) ..... ..... django.db.utils.OperationalError: no such table: main.auth_user__old "POST /admin/vote/poll/add/ HTTP/1.1" 500 215568 ``` The apps URL Patterns code: ``` urlpatterns = [ path("polls/", PollList.as_view(), name="polls_list"), ] ``` The models code: ``` class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) ``` -
Renaming Django model without breaking existing migrations
I want to rename a model in Django 3.2, keep my existing migrations and be able to both migrate a db with the old table name and create a db from scratch. I've started by renaming the model class and all references to it in the code. As "./manage.py makemigrations" did not automatically create a migration, I manually created a migration that renames the model: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('market_integrations', '0003_migration'), ] operations = [ migrations.RenameModel('OldModelName', 'NewModelname') ] My initial idea is that I should not update existing migrations, as I never do when creating other migrations. However, the references to the old model in the old migrations cause a LookupError when I run "./manage.py migrate". I've tried using both the model name string and apps.get_model(). Sample codes that break: operations = [ migrations.CreateModel( name="OldModelName", ... ) ] operations = [ migrations.CreateModel( name=apps.get_model("myapp", "OldModelName"), ... ) ] As keeping the old model name in old migrations didn't work, I replaced the old model name in old migrations with the new name. "./manage.py migrate" ran successfully, including the model renaming migration. However, when I try to create a new database, the model renaming migration fails because … -
How to display li tag in JavaScript or how to display p tag
I want to complete the following code with Django and JavaScript. What I want is <li><p id="optprice">{{value.extra_cost}}</p><option id="value" value="{{value.value_code}}">{{value.name} } (+{{value.extra_cost}}won)</option></li> In this part <p id="optprice">{{value.extra_cost}}</p> I want to float this. So in javascript var optprice = $("#optprice").text(); I did this, but it doesn't show up. What's the problem? Any help would be appreciated. <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <li><p id="optprice">{{value.extra_cost}}</p><option id="value" value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option></li> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> <script> $().ready(function() { $("#optionSelect").change(function(){ var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var optprice = $("#optprice").text(); if (checkValue != "no") { // 없음 선택 아닐경우 var whtml = "<hr style='width: 300px; margin-bottom: 30px;'><p style='font-size: 17px;'>"+product+"</p><p style='font-size: 16px; margin-top: -10px; margin-bottom: … -
Django how to connect user profile model with comment model for showing data from user profile?
I want to show user profile picture publicly in my blog comment section. I tried to use foreignkey in my comment model for connect user profile model then use this in my html for showing profile picture but didn't work. <img src="{{blogcomment.userprofile.profile_pic.url}}"> #didn't show any profile picture until I manually go to admin panel and set foreignkey of userprofile in my blogcomment model. here is my full code: userprofile model class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) blogcomment model: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True,related_name="blogcomment_blog") comment = models.TextField(max_length=50000) name = models.CharField(max_length=250) userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_comment',blank=True,null=True) views.py: if comment_form.is_valid(): isinstance = comment_form.save(commit=False) isinstance.user = request.user isinstance.blog = blog isinstance.save() -
django urlpattern path argument empty (' ') meaning?
I am linking a views to urls.py inside the app. Django docs show it like this from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Note: This urls.py is from app not the project, I have already directed the project(from urls.py) to this file. I want to ask what does path('') means, the first argument of path. What kind of urlpattern is this? -
Can't load CSS Django IIS
I have deployed my web app on Microsoft IIS on my company server. Web.config file is set up and app is running with all permissions. I have created Virtual Directory (to enable serving static files map a static alias to the static directory, C:/inetpub/wwwroot/PyWeb/static/). No matter what I do I can't get my 'blog/main.css'. CSS is not loaded and I get error: Refused to apply style from 'http://localhost/static/blog/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="shortcut icon" href="/media/favicon.ico"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> Part href="/media/favicon.ico" is working and my icon is loaded. I have tried to remove rel="stylesheet" but it did not help. Also, I have run collectstatic: C:\inetpub\wwwroot\PyWeb>python manage.py collectstatic Starting Scheduler... You have requested to collect static files at the destination location as specified in your settings: C:\inetpub\wwwroot\PyWeb\static This will overwrite existing files! Are … -
django forms - what is difference between form.fields and class var?
I wanted to make a dropdown-list that removes data with submit button. <form method="post"> <label for="id_title">Select:</label> <select name="title" id="id_title"> <option value="Return of the Jedi">Return of the Jedi</option> <option value="The Force Awakens">The Force Awakens</option> </select> <input type="submit" value="remove"> </form> and my views.py: def remove(request): if request.method == 'POST': form = forms.TitleDropDownForm(request.POST) if form.is_valid(): (col_name, val), = form.cleaned_data.items() psy.delete_movie_from_table( table='ex04_movies', col_name=col_name, val=val ) return redirect(request.META.get('HTTP_REFERER')) else: form = forms.TitleDropDownForm() form.reload() return render(request, 'ex04/remove.html', context={'form' : form}) forms.py: class TitleDropDownForm(forms.Form): def get_title(): try: conn = psycopg2.connect(database='djangotraining', user='djangouser', password='secret') try: cur = conn.cursor() cur.execute(""" SELECT title FROM %s; """ % ('ex04_movies', ) ) res = cur.fetchall() except Exception as e: return [] else: conn.commit() conn.close() cur.close() ret = [] for tup in res: ret.append((tup[0], tup[0])) return ret except Exception as e: return ret title = forms.ChoiceField(label='Select', choices=get_title()) def reload(self): # TitleDropDownForm.title = forms.ChoiceField(label='Select', choices=TitleDropDownForm.get_title()) self.fields['title'] = forms.ChoiceField(label='Select', choices=TitleDropDownForm.get_title()) When I tried reloading form with class var like comment, the page did not display changed DB properly. But It works after modifying Form.title to self.fields['title']. What is difference between two methods, and how does it work? -
How to queryset filter with two lists?
I have two list and I want to filter the values from table. I was using this query but this is giving me unions of two list i.e OR. I want something with AND i.e filter values this way retail_item_list = [100,120] and city_id_list = [1,2] the output should be on the basis of these combination (100,1) (120,2) val = list(KVIItem.objects.filter(Q(retail_item_id__in=retail_item_list, cms_city_id__in=city_id_list)).values("retail_item_id","cms_city_id","active","id").order_by('-id')) -
How to manage long running tasks via website
I have a django website, where I can register some event listeners and monitoring tasks on certain websites, see an info about these tasks, edit, delete, etc. These tasks are long running, so I launch them as tasks in a asyncio event loop. I want them to be independent on the django website, so I run these tasks in event loop alongside Sanic webserver, and control it with api calls from the django server. I dont know why, but I still feel that this solution is pretty scuffed, so is there a better way to do it? I was thinking about using kubernetes, but these tasks arent resource heavy and are simple, so I dont think it's worth launching new pod for each. Thanks for help. -
Import Error when i try to set AUTHENTICATION_BACKENDS
i created a module in my project directory like this: -Project Directory -Project Name -modules -emailauth.py settings.py -app name and when i add this code to Settings.py: AUTHENTICATION_BACKENDS = ('.modules.emailauth.EmailBackend') i get the error: ValueError at /login/ Empty module name and when i try: AUTHENTICATION_BACKENDS = ('modules.emailauth.EmailBackend') i get the error: ImportError at /login/ m doesn't look like a module path like it's spliting it by characters instead of '.' when i try: AUTHENTICATION_BACKENDS = ['modules.emailauth.EmailBackend'] which i think should be correct, i get an entirely new kind of error: TypeError at /login/ the 'package' argument is required to perform a relative import for '.modules.emailauth' -
`create()` must be implemented
My code: serializers.py: class AuthenticationSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) def validate(self, data): email = data.get('email') password = data.get('password') user = User.objects.get(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password was not found.'+ ' ' + email + ' ' + password ) return { 'email': user.email, 'username': user.username, } views.py: class Authentication(CreateAPIView): serializer_class = AuthenticationSerializer def authentication(request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) return user, Response(serializer.data, status=status.HTTP_200_OK) i need to create authentication and after give user JWTToken but i can't to do authentication. I am work with this libs 2days. May be it is because i am using CreateAPIView? But what can I replace CreateAPIView? -
how to use default address for saving in django
i have model name address which allow user to create multple address and also have functionality to set the default address but i unable to fetch it for saving in models any suggestion will be a big help thank you here is my address model choice are removed class Address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) default = models.BooleanField(("Default"), default=False) def __str__(self): return self.user.username my views.py for seting a address to deafult @login_required def set_default_address(request, id): Address.objects.filter(user=request.user, default=True).update(default=False) Address.objects.filter(pk=id, user=request.user).update(default=True) return redirect('accounts:home') my model in which i want to save that default address class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) address = models.ForeignKey(Address, default= True, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) size = models.CharField(max_length=20, blank=False) price = models.FloatField(blank=False) created_at = models.DateField(auto_now=True, editable=False) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = … -
Django preventing multiple user logins
I wanted to limit users to one login per account. I read numerous posts, and I've been following this post in particular: How to prevent multiple login in Django. In myapp/models.py, I have this: from django.conf import settings from django.db import models from django.contrib.sessions.models import Session ... class UserSession(models.Model): user_acc = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session_manager = models.OneToOneField(Session, on_delete=models.CASCADE) In myaurth/views.py, I import from myapp/models.py and have this: from django.contrib.auth import user_logged_in from django.dispatch.dispatcher import receiver ... @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions Session.objects.filter(usersession__user_acc=user).delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user_acc=user, session_manager=Session.objects.get(pk=request.session.session_key) ) I am not using a custom user model. When I run this code, it works properly when the user logs in the first time and creates an entry in the usersession table. After that I have problems: If I login a second user, it logs them in, but it replaces the first user's session info with the second user's in the usersession table. I never see more than one entry in the usersession table, which is the last user to successfully login. Worse, if I attempt to login the first user … -
How to set Heroku profile so it accepts "yes" in any terminal question for Heroku Deployment
Hello I am tryting to run a command while deploying my Django code to Heroku. I want to accept any question it might get in terminal I tried to add following to the procfile, but it didnt work release: python manage.py collectstatic --yes release: python manage.py collectstatic -y What is the correct way to do this? Thanks in advance -
Facing troubles on bringing the Django admin user tools like welcome, view site, log out on the custom template
I have to override the blocks like branding,site_title, and index title to a custom template. But the user tools are not displaying. How I get. How I want. -
DateField in Django Forms shows like simple text input
My Form : date = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'})) My HTML : <label class="form-label">Date</label> {{ form.date }} <div class="invalid-feedback"> Enter Date </div> Also I don't want to add type "date" in my forms. Issue picture : enter image description here -
How to configure a django url correctly in javascript
I have seen lots of questions and answers on this topic, but the solution seems to evade me. common/urls.py path('use-selected/<str:app_base>/<str:board_number>/', views.UseSelectedItem.as_view(), name='use-selected'), If I enter the the following code in my template, it works correctly <a id="use-selected" href="{% url 'use-selected' app_base='solo' board_number='4' %}"><button type="submit">Use selected</button></a> if, on the other hand, I assign the href in javascript use_selected = document.getElementById('use-selected'); use_selected.href="{% url 'use-selected' app_base='solo' board_number='4' %}" the link fails. The request url is http://127.0.0.1:8000/common/history/solo/%7B%25%20url%20'use-selected'%20app_base%3D'solo'%20board_number%3D'4'%20%25%7D I do not uderstand where the common/history/solo elements arise. common and solo are apps within my project; common/history was the url to get to this page -
Django Paginator. How to set number of pages or elements of list
I need to create a Paginator object for function based view. When I send a request to googleapi I receive json with totalItems and items keys. GoogleApi paginates request to 10 items. Let's say the totalItems is 800 so I need to somehow tell Django Paginator there are more items than I receive in the request. My first idea was to just create a list with empty items and items received from API at indexes accordingly to page number but I believe there is some good clean trick for that" VIEW def get_books(request): page = request.GET.get('page', 1) start_index = (page - 1) * 10 params = {'q': RoweryMogąUratowaćŚwiat, startIndex: start_index} result = requests.get('https://www.googleapis.com/books/v1/volumes?,params=params) total = result['totalItems'] items = result['items'] my_list = [] for i in range(total) if start_index < i < start_index + 10 my_list.append(items[i - start_index]) else: my_list.append('') paginator = Paginator(my_list, 10) -
Creating an Django API end point for data with foreign key value
first time asking question will try and make it clear what I'm trying to do. I have 2 models called Configuration and Results. class Configuration(models.Model): title = models.CharField(max_length=50, default="") houseType = models.CharField(max_length=50) numberOfHouses = models.CharField(max_length=50) maxAmpere = models.CharField(max_length=50) date = models.DateField(default=now()) status = models.BooleanField(default=False) class Results(models.Model): time = models.CharField(max_length=100) averageCurrent = models.CharField(max_length=100) config_id = models.ForeignKey(Configuration, related_name='results', on_delete=models.CASCADE) What I am struggling to do is: Create a Results object linked to the correct configuration Create an api endpoint in the views to fetch the results for a specific configuration Any help or advice would be greatly appreciated! Thanks in advance In case it helps this is the code for my serializers: class ResultsSerializer(serializers.ModelSerializer): class Meta: model = Results fields = ['time', 'averageCurrent', 'config_id'] class ConfigurationSerializer(serializers.ModelSerializer): results = serializers.StringRelatedField(many=True) class Meta: model = Configuration fields = ['results', 'title', 'houseType', 'numberOfHouses','maxAmpere', 'date', 'status']