Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing models and extending database structure in Saleor
I recently forked Saleor 2.9 for a web app I am building for an art gallery that wants to display their products for sale as well as give their artists some publicity. I want to be able to have a bunch of cards (like "our team" components) that pull data from an Artists table on the back-end that stores information about the artists' names, emails, origins, etc, and then display it on the front-end. I am struggling to see how to modify the models/DB to create a new "Artists" table with name, email, info, and then to create a manyToMany-like relationship with the products I've populated in the DC, giving the products a "created by" attribute. There are tons of models files throughout the /dashboard directory, and even when I make changes to the core models to create an artist class, I don't know how to get it to show on the dashboard so artists can be created/modified from there. I would like to make it so that the client (non-technical) can add artists and have them show up on the artists page I will make, somewhat like products show up on their pages (but obviously I cannot create a … -
Django: Last modified by and created by user automatic saving
The age-old question: How can I automatically save last_modifed_user in django models? I found in several places this general process how to do it using thread local. I'm hesitant to simply implement it that way because I'm not entirely sure of the consequences it has and because all these posts are old. Is using thread local still the "recommended" way of doing this in django 3? Or does django3 have a better options of doing it? -
Django, new model raises error when trying to access the server
I have the following model, Which is new: from django.db import models class Point(models.Model): latitude = models.FloatField(verbose_name="Latitude", blank=False) longitude = models.FloatField(verbose_name="Longitude", blank=False) elevation = models.FloatField(verbose_name="Location's Elevation", blank=True) class Location(Point): created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='create') location_name = models.TextField(verbose_name="Location Name", blank=False, unique=True,) location_info = models.ForeignKey(Point, related_query_name='new_location', on_delete=models.CASCADE, blank=False, ) I ran makemigrations and migrate and didn't ran into any errors. when running the server I got the following error: ProgrammingError at /points/ column NewLocationModel_location.point_ptr_id does not exist LINE 1: ...location" INNER JOIN "NewLocationModel_point" ON ("NewLocati... -
Django model choice Text to Integer
I'm trying to create a django model using Text as a value for the IntegerField class User(models.Model): class UserRole(models.IntegerChoices): FULLACCESS = 0, _('full_access_user') READONLY = 1, _('read_only_user') WRITEONLY = 2, _('write_only_user') role = models.IntegerField(choices=UserRole.choices) When I try to create the user like User.objects.create(role="full_access_user") it does not map the string value to integer. Tried to define models.IntegerChoices as models.TextChoices and map those to integer but django forbids such action. What could be done to create the object like it's shown in the example ? -
Cannot find reference 'DjangoWhiteNoise' in 'django.py' in wsgi.py
Im about to deploy my django-app to heroku. I will then use whitenoise to handle the static files. The tutorial im following tells me i have to add this to my wsgi.py file: So the problem is that pycharm tells me: "Cannot find reference 'DjangoWhiteNoise' in 'django.py'" However i have installed whitenoise! and it is located in the "External libraries". I even went down into the whitenoise.django file, and there is nothing named DjangoWhiteNoise there... Thanks in advance. Havent found anythin about this concrete problem anywhere. -
How to have multiple (# is dynamic) range sliders Django form
I'm relatively new to this all so please keep that in mind ;) I currently generate multiple range sliders, the number of sliders is based on the number of field in a certain column in the model. The sliders appear on the page, and also show the correct value (taken from the model). Unfortunately sliding the sliders does not change the value of the form. I know this can be done with js, but I only know how to do this when I can explicitly reference to an ID of a slider. Since the number of sliders is dynamic (it can change depending on choices of user) I don't know how to do this. Html: <form method="post"> {{ formset.management_form }} {% for form in formset %} <div class="custom-slider-container"> <label>{{ form.name.value }}</label> {{ form.weight }} </div> {% endfor %} </form> If any other information is needed, please let me know and I'll add it! -
How to create session that will remember user in the function?
I have project where users can access to rooms with password, how to create session that will remember this user after first pass,and also i want to set expire date for this session.Maybe you know different way to implement that views.py try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: # messages.success(request, 'match') user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): # return HttpResponseRedirect(Room.get_absolute_url(room)) return join_room(request,uuid) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: return HttpResponse('this work on private room only') -
My Django3 project doesn't read static files
I built a new Django project on my docker image, and I ran a command docker run -it -p 8888:8888 simple-django-on-docker On http://localhost:8888/, I could see a Django top page, but my chrome dev console says, Refused to apply style from 'http://localhost:8888/static/admin/css/fonts.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. On http://localhost:8888/admin, the page also doesn't read css files. So I ran this command to find a exact path. python3 manage.py findstatic . and the result was this. Found '.' here: /Users/umedzuyouhei/.local/share/virtualenvs/python-docker-zWNu1ZnK/lib/python3.7/site-packages/django/contrib/admin/static Why doesn't my app load static files? Followings are my setting.py and Dockerfile. setting.py """ Django settings for password_generator project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os mimetypes.add_type("text/css", ".css", True) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8ikyfm)lf-6z(xp%@m88jwg!+laxv25bvz*c)f1(%wcvp7xckl' # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True # DEBUG can be … -
When Writing Python in Powershell it Returns Nothing
Program 'Python' failed to run: No application is associated with the specified file for this operationAt line:1 char:1 + python + ~~~~~~. At line:1 char:1 + python + ~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed I am Finding for Quick Help and Also Need to Know why My python manage.py runserver Command in Django is Not Working properly anywhere. I think the only problem is python command Not Working Please help as SOON. -
how i can delete multiple record or objects in django?
I want to delete multiple records using html checkbox but i don't get any idea how i perform this task. At this time in my project I implement the single delete record or object through generic views as you can see in below code. How i can delete multiple records using checkbox? what changes i need to do in my code? views.py class DeleteProduct(SuccessMessageMixin, DeleteView): model = Product success_url = reverse_lazy('stock:stock') success_message = "Product is deleted successfully." def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message, extra_tags='alert-danger') return super(DeleteProduct, self).delete(request, *args, **kwargs) urls.py path('<int:pk>/delete', login_required(DeleteProduct.as_view(), login_url='login'), name='deleteproduct'), template.html {% extends 'base.html' %} {% block content %} <div> <h2 class="text-center" ><i>Stock!</i></h2> {% if messages %} {%for message in messages%} <div class="alert {{ message.tags }}" role="alert"> {{ message }} </div> {% endfor %} {% endif %} <hr/> <form method="POST"> {% csrf_token %} {% for product in page_obj %} <div class="row" > <input type="checkbox" name="products" value="{{ product.id }}"> <div class="col-sm-2" > <h5>{{ product.id }}</h5> <img src="{{ product.Picture.url }}" height="120px" /> </div> <div class="col-sm-4" > <h5><u>Product Name</u>: {{ product.pro_name }}</h5> <h6><u>Company Name</u>: {{product.companyName}}</h6> <div class="row" > <div class="col-sm" > <p>Purchase Price: <b>{{product.Purchase_Price}}</b></p> </div> <div class="col-sm" > <p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p> </div> </div> <div class="row" > … -
Importing javascript from node modules in a django project
I am so sorry to ask such a simple question. I have spent hours looking for an answer but I just can't figure this out. I am trying to import a javascript library from node_modules in my django project. For whatever reason, I keep getting a 404. I'm testing with a dummy javascript file, so right now my import statement is just <script src="/node_modules/test.js"></script> (As a sanity test I've also tried ../node_modules/ and node_modules/ as well as using the django static files system) Here is a picture with the file + file structure: site/node_modules/test and site/portfolio/templates/portfolio/test.html I'm wondering if this error has something to do with how Django serves static files in development? is there something that I'm missing? -
PythonAnywhere dotenv Import error when following `How to set environment variables for your web apps` guide
I want to set up environment variables for my Django project. I have followed the PythonAnywhere guide on How to set environment variables for your web apps, including this step: from dotenv import load_dotenv This is my code in the wsgi.py file: wsgi.py I receive the following import error for dotenv when trying to run the webapp: dotenv import error log I do have the dependency installed: enter image description here I'm not sure what's going on here. It seems my project_folder path is correct, so I don't think that's the issue. I'm not sure what's going on. Thanks for the help in advance :) -
Django from django.core.wsgi import get_wsgi_application
An error POPs up that wsgi does not see django(when placing it on hosting). Although there is django in the virtual environment(I read that the path of the virtual environment can be incorrectly recognized, this is probably the problem, but it did not work out): [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] from wsgi import application [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/caparol_center_spb_decision/caparol_center_spb_decision/wsgi.py", line 12, in <module> [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] from django.core.wsgi import get_wsgi_application [Fri Apr 03 23:34:20 2020] [error] [client 5.18.99.123] ModuleNotFoundError: No module named 'django' Код django.wsgi на хостинге import os, sys virtual_env = os.path.expanduser('~/caparol_center_spb_decision/env') home='~/caparol_center_spb_decision/env' activate_this = os.path.join(virtual_env, 'bin/activate_this.py') exec(open(activate_this).read(), dict(__file__=activate_this)) sys.path.insert(0, os.path.expanduser('~/caparol_center_spb_decision/caparol_center_spb_decision')) from wsgi import application -
Django REST Framework FileParser error while making a request through postman
I have a model in Django for holding the details of the user's profile like: class UserDetails(models.Model): def getFileName(self, filename): return 'profile_pics/'+str(self.user.id)+'/'+filename user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profile_picture = models.ImageField(blank = True, upload_to=getFileName) country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) verified = models.BooleanField(default=False) def __str__(self): return self.user.username Then, I wrote a REST API that would handle POST requests to create a user profile like: from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes, parser_classes from rest_framework.parsers import FormParser, MultiPartParser, FileUploadParser from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from datetime import datetime from django.contrib import messages, auth from django.contrib.auth.models import User from userMgmt.models import UserDetails @api_view(['POST']) @parser_classes(['FormParser', 'MultiPartParser', 'FileUploadParser']) def signUp(request): if request.method == 'POST': data = request.data ## Creating a basic user user = User.objects.create_user(data['first_name'], data['email'], data['password']) user['last_name'] = data['last_name'] user.save() ## Creating a profile for the user user_details = UserDetails() user_details.user = user user_details.profile_picture = data['profile_picture'] user_details.country = data['country'] user_details.gender = data['gender'] user_details.birthday = datetime.strptime(data['birthday'], '%m/%d/%y') user_details.phone = data['phone'] user_details.verified = False user_details.save() return Response({'message': 'Profile created Successfully'}) Then, I made a request to this REST API using Postman like: After that, I got … -
my class-based view in django does not work how to fix it
Guys i am learning how to make class-based views and my code does not work. would appreciate your help. In models.py class Student(models.Model): name = models.CharField(max_length=150) class Class10(models.Model): stud_name=models.CharField(max_length=200) surname=models.CharField(max_length=500) class Meta: managed=False db_table='background' in forms.py: class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput (attrs={'placeholder':'Search'})) class Meta: model = Student fields = ['name',] def clean_name(self): name=self.cleaned_data.get("name") if not Class10.objects.filter(stud_name=name).exists(): raise forms.ValidationError ( "No such student") return name In views.py : from django.shortcuts import render from .forms import * from django.urls import reverse_lazy from .models import * from django.views.generic import CreateView,TemplateView class Searchr(CreateView): form_class = StudentForm success_url = reverse_lazy('bla') template_name = 'vasa/index.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST or None) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) name = form1.name student_info=Class10.objects.get(stud_name=name) context={'profile':student_info ,'form': SymbolForm(),} return render(request, self.success_url, context) return render(request, self.template_name, {'form': form}) in app vasa/urls.py: from django.contrib import admin from django.urls import path, include from vasa import views from django.conf.urls import url app_name = 'vasa' urlpatterns = [ path('searchr/',views.Searchr.as_view(),name='searchr')] in main urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('vasa/',include('vasa.urls',namespace='vasa')),] in index.html: <form method="POST" > {% csrf_token %} {{ form}} <button class = "button" type="submit">OK</button></form> in bla.html: <form method="POST" > {% … -
Edit the template of admin top page
I am editing the template of admins I successfully override the each model's edit page. /myapp/template/admin/modelA/change_list_results /myapp/template/admin/modelB/change_list_results However how can I override the top of admin?? After login, there is a application and table lists. I tried to override these below from /django/contrib/admin/templates/admin/ folder /myapp/template/admin/app_index /myapp/template/admin/index /myapp/template/admin/base However , still in vain. -
Hiding the one certain row of tables in admin
I want to hiding the one certain row of tables in admin. I have these tables. id name 1 main // hide this row in admin. 2 John 3 Lisa At first, I try to override template change_list_result.html and edit here, but still no success. <tr class="{% cycle 'row1' 'row2' %}"> {% for item in result %} {{ item }}{% endfor %} </tr> Is there any good way or my plan is basically ok? -
Django formset not JSON serializable
I am trying to pass a formset as JSON data but i am getting Object of type HabitFormFormSet is not JSON serializable. Why is that ? my view: def modal_view(request): HabitFormSet = modelformset_factory( Habit, extra=0, form=HabitModelForm) formset = HabitFormSet( request.POST, queryset=Habit.objects.filter(user=request.user), ) new_habit = HabitModelForm(request.POST) if formset.is_valid(): formset.save() data = {"formset": formset} return JsonResponse(data) return HttpResponseRedirect(reverse('home')) -
How to handle user authentication in django without relying on user models?
I'm working on an assignment. I'm using Django as the front end. The course is focused on databases and I cannot rely on Django's ORM features(including models). I have to write raw SQL queries for everything I do. I know that Django has a user model but I cannot rely on it for querying user info. The problem is that I still need to authenticate users. I could get away with storing user credentials on user models and add a field to store the SQL primary key for the info in there and use that for the queries but that is not a full solution. The rest of the framework seems to be coupled with the user model so I'm unsure as to whether it is even possible to do it without user models. -
Serving a django model containing objects
I have following django model: class Weather(models.Model): lat_lng = gis_models.PointField() raw_data = psql_fields.JSONField(null=True) I have following view: def weather(request): data = WeatherModel.objects.all() js_data = serializers.serialize('json', data) return HttpResponse(js_data, content_type='application/json') It throws error saying 'Point object is not json serializable.' I want this function to return json. Please help. -
How to integrate django with react and webpack to create a multipage webapp?
I have a django project, now I want to integrate react with it in such a way that routes or urls should be handled by django and other stuff inside the body should be handled by react and its components. For example: /profile/ is route which is served by django and after it has loaded everything all the crud operation could be done by react. One more thing I want all the static files should be generated by webpack, which will served by django -
Generate different checkboxes inside a loop html
Right now i'm working in my first python - django project's front end, and i'm having some trouble with the table i'm using to show data from my db. The thing is that i wanted to put a checkbox at the first column of the table at every row, but since i don't know how many registers will there be, i created a checkbox on the first column inside the loop that i'm using to show the registers. And every checkbox of the table that i click makes reference to the checkbox thats on the first register of the table. (If i click the 3rd's row checkbox, it would check the first row's one, and if i click the 5th's row table, it would uncheck the first row's one.) here is my code. HTML: {% for dominios in dominios %} <tr style="height: -2px;"> <td style="text-align:center;"> <div class name="checkboxWrapper"> <input type="checkbox" id="check" hidden="true" style="margin-top: 10px;"/> <label for="check" class="checkmark" ></label> </div> </td> <td style="color:#A9A9A9;">{{dominios.id_dom}}</td> <td style="color:#A9A9A9;">{{dominios.nombre_activo}}</td> <td style="color:#A9A9A9;">{{dominios.desc_act}}</td> <td style="color:#A9A9A9;">{{dominios.dat_cont_arch}}</td> <td style="color:#A9A9A9;">{{dominios.resp_dom}}</td> <td style="color:#A9A9A9;">{{dominios.estado}}</td> {% endfor %} So what i want to do is every checkbox unique, so i can select the register with the checkbox. I hope someone can help me … -
How do I read all the images with a specific prefix in django?
I am building a Face Recognition system. All the detected faces are stored in a directory. (Its stores both known and unknown) I want to create a log of all the unknown faces. The unknown faces are stored with a prefix unknown_2203.png My Question how do I fetch the unknown.pngs from that directory and show them on a django template? Any help would be great! -
How to replace python 2.7.16 to python 3?
MacBook-Pro:~ bsr$ pip install django DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in ./Library/Python/2.7/lib/python/site-packages (1.11.29) Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from django) (2013.7) Due this error unable to install the djengo. pip install django -
Django keeps on putting quotes around table name in mysql query and the query wont work
Table name in MySql is usercreds and the query that django generates works without the quotes around the table name. The model is created using inspectdb command from django, Im trying to django admin panel as a db manager. models.py: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Usercreds(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, blank=True, null=True) password = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'usercreds' settings.py: """ Django settings for admindb project. Generated by 'django-admin startproject' using Django 2.2.11. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) …