Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unexpected behaviour using a shell script to run a command in python shell
I'm attempting to write a script for the initial setup of superuser in django. I have a docker container running django. docker exec -it "mydockername" bash -c echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('root3', 'admin3@myproject.com', 'root3')" | python manage.py shell This script is throwing an error File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax But if I execute the command echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('root3', 'admin3@myproject.com', 'root3')" | python manage.py shell inside of the docker container I don't have any problems and the superuser is created. -
how to create autocomplete using function-based view
I am trying to create autocomplete. I have an input field (class Coordinate) where code is required to input. Also i have static file (class Profiles). the idea is that when i type code it goes to class Profile and matches with geocode and hence can find country name based on code. I want to create autocomplete for input field so when i type code it brings suggestions based on country. For example: code input 011 equals to United Kingdom in class Profiles and etc. In models.py i have: class Coordinate(models.Model): code = models.CharField(max_length=150) class Profiles(models.Model): geocode=models.CharField(max_length=200) country=models.CharField(max_length=500) class Meta: managed=False db_table='profiles_country' def __str__(self): return '{}'.format(self.geocode) class Year19(models.Model): geocode=models.CharField(max_length=200) longitute=models.CharField(max_length=500) latitude=models.CharField(max_length=500) class Meta: managed=False db_table='year19' in forms.py: from dal import autocomplete class CoordinateForm(forms.ModelForm): code= forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Coordinate fields = ('__all__') widgets = { 'country': autocomplete.ModelSelect2(url='coordinate-autocomplete', attrs={ 'theme': 'bootstrap'})} def clean_code(self): code=self.cleaned_data.get("code") if not Profiles.objects.filter(geocode=code).exists(): raise forms.ValidationError ( "Not true") return code in views.py: from dal import autocomplete def geoview(request): form = CoordinateForm(request.POST or None) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) code = form1.code dataview=Profiles.objects.get(geocode=code) year19=Companies_data_2019.objects.get(geocode=code) context={'geodata':dataview ,} return render(request, 'cgeo/result.html', context) return render(request, 'cgeo/search.html', context={'form':form}) functon based view for autocomplete : def … -
Django - 'AnonymousUser' object is not iterable
Getting an error for AnonymousUser. What I code here is only for the authenticated user. But an unauthenticated user cannot add a product. I want to work it like, if user comes to the website and clicks on add to cart the product should be added to the cart. Then when he tries to sign in. The products should be in the cart. cart models.py # Create your models here. class CartItem(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f"{self.quantity} of {self.item.name}" def pre_save_cart_item(sender, instance, *args, **kwargs): instance.item_total = instance.quantity * instance.item.price pre_save.connect(pre_save_cart_item, sender=CartItem) class Cart(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='cart') items = models.ManyToManyField(CartItem) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) purchased = models.BooleanField(default=False) def __str__(self): return f"User: {self.owner}, items in cart {self.number_of_items}" def m2m_save_cart(sender, action, instance, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': instance.number_of_items = instance.items.count() items = instance.items.all() instance.total = 0 for x in items: instance.total += x.item_total instance.save() m2m_changed.connect(m2m_save_cart, sender=Cart.items.through) cart views.py # Create your views here. def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) cart_item, created = … -
docker-compose resets django db when requirements.txt change
I'm using docker-compose to develop a django project with postgres db. Using VS Code, I get two dockers running after Docker Compose Up. Every time I work on the project, the db is intact The issue is when any changes are made to requirements.txt, the db image resets, even though no changes were made to that image. I have to run python manage.py migrate and createsuperuser and the db is empty. I can understand that the web docker image must be recreated when there are changes to requirements.txt, but why does the db image resets? Is there a way to avoid this? I would hate to publish the production app and not be able to install additional libs in newer versions without losing the db. docker-compose.yml: version: '3' services: db: image: postgres environment: POSTGRES_USER: 'aaa' POSTGRES_PASSWORD: 'aaa' POSTGRES_DB: 'aaa' web: build: . volumes: - .:/code ports: - "8000:8000" depends_on: - db stdin_open: true tty: true Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ -
Send data to a Django channels consumer
I have the following basic Django Channels consumer: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('Connected!') And, in parallel, i have a normal Python script which connects to a websocket and receives some data in real time: from binance.client import Client import json from binance.websockets import BinanceSocketManager client = Client('', '') # get all symbol prices prices = client.get_all_tickers() trades = client.get_recent_trades(symbol='BNBBTC') # start aggregated trade websocket for BNBBTC def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Quantity, Order) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() I would like to do the following: instead of only printing the data received, the second script should send somehow that data to the Django Channels consumer. Whenever a user opens the page, that page should receive that data. If a second user opens the page at the same time, that second user should receive the data too. Is it possible to do this? Am i supposed to use another service? -
Tasypie Django - GroupBy and Count
I am trying to do a group by and count using tastypie in django. I have spent quite some time, but I get a very weird error and I am pretty sure it comes from tastypie. In practice, I just want to return a JSON with distinct locations and count. This is my model: class Incident(models.Model): location_name = models.CharField(max_length=255) latitude = models.FloatField() longitude = models.FloatField() This is what I do for tastypie: class IncidentResource(ModelResource): class Meta: API_LIMIT_PER_PAGE = 0 queryset = Incident.objects.all() resource_name = 'covid' limit = 0 max_limit = 0 include_resource_uri = False allowed_methods = ['get', 'post'] authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() validation = Validation() def get_object_list(self, request): location_group = Incident.objects.filter(possibly_new=True).values('location_name').annotate(total_incidents=Count('possibly_new')) # return location_group here is NOT working "invalid literal for int() with base 10: ''" -
How to use django groups in order to set group permission
I want to use django groups provided in user groups. The django group permissions set in admin panel. Suppose I created two groups teachers and students. I want to set permissions at generic view level. Some views can only be can view or can edit by either student or teacher. These permission were set in django admin as following: Now I created a createview as following: class CreateQuestionView(LoginRequiredMixin,generic.CreateView): model = Question success_url= reverse_lazy('questions:list') fields = ['title','description' ] def form_valid(self,form): form.instance.user = self.request.user #self.object.save() return super().form_valid(form) Now I want this view to be accessible by only teacher groups. I cant find a proper way to implement group permission.Something like @group_required may work in this case link but cant find any related documentation. What is correct way to implement this? -
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'))