Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I already have implementation of python-docx to download docx file in my django project, now i want to convert it into pdf
I already have an implementation of python-docx to download docx file in my django project, now i want to download pdf with same content and same format -
ModuleNotFoundError: No module named 'django' by Deploying on Azure
I'm trying to deploy a django web app to the Microsoft Azure and this is correctly deployed by the pipeline on DevOps Azure, but I get the error message (ModuleNotFoundError: No module named 'django) on portal Azure and cannot reach my app via the URL. The app also works properly locally Here is the whole error message: '''https://pastebin.com/mGHSS8kQ''' How can I solve this error? -
pylint_django raises import-errors when not specifying --init--hook option
my_project __init__.py app __init__.py settings.py manage.py core __init__.py common.py students __init__.py models.py views.py serializer.py teachers __init__.py models.py views.py serializer.py When I run pylint --load-plugins pylint_django students, I got these errors: E0611: No name 'common' in module 'core' (no-name-in-module) E0401: Unable to import 'teachers.serializer' (import-error) E0401: Unable to import 'teachers.models' (import-error) My students/serilizer.py: from rest_framework import serializers from students.models import Student from teachers.serializer import TeacherSerializer from teachers.models import Teacher from core.common import method class StudentSerializer(serializers.ModelSerializer): pass I don't get theses error when I import the models of the same app ! I don't get any error when I specify --init--hook option: pylint --load-plugins --init--hook "__import__('sys').path.insert(0, '.'); __import__('django').setup();" pylint_django students How can we overcome these errors without specifying the --init-hook?? -
Django ORM Query: How to get record that Not Exist in other table
How to achieve this Raw SQL query in Django ORM?: dbfiddle. So I have 2 table, Table user and payment, i need to get the user_id that not have a record in payment table (see expected result): User table: Payment table: Result Expected -
Cannot install psycopg2, django-heroku, grpcio on MacOS Catalina 10.15.7
I am trying to install requirements on a Django project but I get this error. I've tried almost everything I saw but still no luck. I have tried pip install -r requirements.txt, pip install psycopg2, pip install psycopg2-binary but none of them worked. My Python version is 3.9.0 and I've also tried it with 3.8.2 but still got the same error. Here is the stack trace: ... 1 warning generated. gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.6 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=130001 -DHAVE_LO64=1 -I/Users/burakakyalcin/Projects/hakko_api/venv/include -I/Library/Frameworks/Python.framework/Versions/3.9/include/python3.9 -I. -I/usr/local/include -I/usr/local/include/postgresql/server -c psycopg/xid_type.c -o build/temp.macosx-10.9-x86_64-3.9/psycopg/xid_type.o gcc -bundle -undefined dynamic_lookup -arch x86_64 -g build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_asis.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_binary.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_datetime.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_list.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pboolean.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pdecimal.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pfloat.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pint.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_qstring.o build/temp.macosx-10.9-x86_64-3.9/psycopg/aix_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/bytes_format.o build/temp.macosx-10.9-x86_64-3.9/psycopg/column_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/connection_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/connection_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/conninfo_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/cursor_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/cursor_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/diagnostics_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/error_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/green.o build/temp.macosx-10.9-x86_64-3.9/psycopg/libpq_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/lobject_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/lobject_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/microprotocols.o build/temp.macosx-10.9-x86_64-3.9/psycopg/microprotocols_proto.o build/temp.macosx-10.9-x86_64-3.9/psycopg/notify_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/pqpath.o build/temp.macosx-10.9-x86_64-3.9/psycopg/psycopgmodule.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_connection_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_cursor_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_message_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/solaris_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/typecast.o build/temp.macosx-10.9-x86_64-3.9/psycopg/utils.o build/temp.macosx-10.9-x86_64-3.9/psycopg/win32_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/xid_type.o -L/usr/local/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.9-x86_64-3.9/psycopg2/_psycopg.cpython-39-darwin.so ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Users/burakakyalcin/Projects/hakko_api/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/lx/1m5zgk591xj0_fyybjhw1wm00000gn/T/pip-install-tiftlw89/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/lx/1m5zgk591xj0_fyybjhw1wm00000gn/T/pip-install-tiftlw89/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', … -
media Image url not opening in django template
Image from media not opening in template in my django app. below is urls or my project from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('myroyalkennel', include('myroyalkennel.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Below is my settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' below is my views.py* def store (request): items = products.objects.all return render(request, "myroyalkennel/store.html", {"itms":items}) below is my template: <body> <table> <tr> <th>image</th> <th>SERIAL NUMBER</th> <th>SERIAL NUMBER</th> <th>PRODUCT NAME</th> <th>VARIENT</th> <th>MRP</th> <th>DISCOUNTED PRICE</th> <th>DISCOUNT PERCENT</th> <th>IN STOCK</th> </tr> {%if itms %} {% for item in itms %} <tr> <td>{{item.image.url}}</td> <td>{{item.Serial_number}}</td> <td>{{item.product_name}}</td> <td>{{item.Varient}}</td> <td>{{item.MRP}}</td> <td>{{item.Discounted_price}}</td> <td>{{item.Discount_percent}}</td> <td>{{item.In_Stock}}</td> </tr> {% endfor %} {% endif %} </table> </body> below is my model * class products(models.Model): Serial_number = models.CharField(max_length=10) product_name = models.TextField() Varient = models.CharField(max_length=15) MRP = models.IntegerField() Discounted_price = models.IntegerField() Discount_percent = models.CharField(max_length=6) In_Stock = models.CharField(max_length=15) image = models.ImageField(upload_to="asset/image",default="") def __str__(self): return self.product_name When I am calling the image in template with {{ item.image.url}} it gives path /media/asset/image/rkci_logo.jpg but image does not open. -
Use Wordpress for authenticating Django users
I have a WordPress site with multiple users configured. I also have a Django-based site. I would like to have my Django site use the Wordpress site to authenticate users. Is it possible to have Wordpress serve as an authentication server for a Django site? If so, how? Thanks! -
I want to show customer coin but its only shwoing customer id
i am trying to show account balance system in my project.Like a customer has 1000$ when that customer log inhe will be shown his balance is 1000$.But whenever I try to fetch this data it only shows its id, but I want to show his amount not his id.How can I do this ??I am really confused about this part and got stuck here Here is my Customer Model: class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) How can I only show his amount when he is logged in ?? Please help me asap -
Reverse migration id column primary key
I have a table that had an id uuid primary key column. And i want to change this column into Char primary key column. So i did a migration that removes the field and then re-add. When i migrate everything migrates successful. But if i reverse the migration i get django.db.utils.IntegrityError: column "id" contains null values when tries to execute the following sql ALTER TABLE "Test" ADD COLUMN "id" uuid NOT NULL PRIMARY KEY. Below is my migration operations: operations = [ migrations.RemoveField( model_name='employee', name='id', ), migrations.AddField( model_name='employee', name='id', field=models.CharField(default='abcd', max_length=100, primary_key=True, serialize=False), preserve_default=False, ), ] -
coverage showing 100% for settings.py file
I'm confused with coverage report which is generated with help of pytest. Here is my coverage html report. settings.py file is showing 100% covered, not sure how it is.. ? Also, the following Loginform also shown as covered so I have added another dummy form even it is showing covered. I'm facing difficulty in understanding this, though I don't have any tests added for settings or for the above forms it's showing as 100% covered, with this I'm not confident whether my code is properly tested or not. -
Django Query how to display a count of records with a distinct dates and display date and count
I'm trying to create a Django query that as output will give me a list of dates and the count of records against those dates. This is my current query which gives me a count of distinct dates as {'dates':2} stats = models.SearchResultStat.objects.values().filter(organisation=organisation.id).annotate(date=TruncDate('created')) \ .values('date') \ .distinct() \ .aggregate(dates=Count('date')) But what I need is [{'2020-11-01' : 2},{'2020-11-02' : 1}] How do I achieve this? -
Forbidden (403) - CSRF verification failed. Request aborted in django when load in Iframe
Django CSRF error in Iframe. When I'm trying to log in its raises the error. Otherwise, it's work fine Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. I'm used LoginView for login also declared {% csrf_token %} in template form. -
Incomplete response format while displaying large number of users in get request?
This is my api view class UserListViewSet(ListModelMixin,GenericViewSet): serializer_class = UserListSerializer permission_classes = [IsAuthenticated] # pagination_class = BasicPagination authentication_classes = [TokenAuthentication, ] queryset = User.objects.filter(is_approved=True) I have the huge number of users more than 7000 users. This api used to give all the users in correct format when users were around in 3-4000 but when the users list get around 6000 then the response is displaying like this. [ { "first_name": "first name", "middle_name": null, "last_name":"last name" # user list ends in this format When I test locally if the users are few then there is no problem in response. I am testing the api in postman. Why is this happening ? How can solve this ? -
JavaScript doesn't change in the Browser
I am working on project with Django, when i edit a JavaScript script the Browser does not show changes. It keeps the old version -
how to save html dropdown value to database (django)
i have a form like this: <form action="/processing/save/" method="POST"> <table class="content-table"> <thead> <tr> <th class="tweet">Tweets</th> <th class="type">Tipe Data</th> <th class="manual">Sentimen Manual</th> <th class="auto">Sentimen Otomatis</th> </thead> <tbody> {% for tr in db_training %} <tr> <td class="tweet">{{tr.tweets}}</td> <td class="type">{{tr.dtype}}</td> <td class="manual"> {{tr.manual}} &nbsp; <select id="dstrain_{{ forloop.counter }}" onchange="gettrain(this)"> <option selected disabled="true">Pilih</option> <option value="negatif">Negatif</option> <option value="netral">Netral</option> <option value="positif">Positif</option> </select> </td> <td class="auto">{{tr.auto}}</td> </tr> {% endfor %} </tbody> </table> {% csrf_token %} <div class="processing"> <input class="btn_save" type="submit" value="SIMPAN"> </form> it looks like this: what i want to do is when i click save, the value from dropdown will be inserted to my database (in column "manual"). heres the database: is it complicated? i just started learning django. -
How can I serialize a nested model m2m field to self with django-rest-framework?
I have a User model that has a m2m relation to itself called friends and I'm trying to serialize it to see and update the pk's of users that are in the relation. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('Email', max_length=254, unique=True) name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False) friends = models.ManyToManyField("User", related_name='user_friends', blank=True) serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField( write_only=True, required=False, help_text='Leave empty if no change needed', style={'input_type': 'password', 'placeholder': 'Password'} ) # for setting the password class Meta: model = User fields = ('pk', 'email', 'name', 'friends', 'password') def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) When I go to my API I see the following: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ "http://localhost:8000/user_detailAPI/2/" ], } } but I would like for the serializer to display each friend in a list in a manner like this: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ 2 ], } } Plus if you could let me know how I would be able to add an object to friends field using POST or PUT request it would be nice because I am new to django-rest-framework and I feel like this is an … -
What is the correct format for adding data in Djongo Arrayfield?
I am using mongodb as my database and I have use djongo as my connector. The database connection is working fine. I have used models.ArrayField in Movie Model. When I try to add the tag in through the admin panel it shows the error as shown below.. [![enter image description here][1]][1] Here is my code from django import forms class Tag(models.Model): tag = models.CharField(max_length=200) class Meta: abstract = True def __str__(self): return self.tag class TagForm(forms.ModelForm): class Meta: model = Tag fields = ( 'tag', ) class Movie(models.Model): movie_name = models.CharField(max_length=255) tags = models.ArrayField( model_container=Tag, model_form_class=TagForm ) objects = models.DjongoManager() def __str__(self): return self.movie_name``` [1]: https://i.stack.imgur.com/li1B7.png -
use record from same model as foreignkey in django
my model is as follows : class Profile(model.Models): name = models.CharField(max_length = 20) full_name = models.CharField(max_length = 20) husband_spouse = models.ForeignKey(Profile, on_delete=models.CASCADE) on doing python manage.py makemigrations I get the following error : NameError: name 'Profile' is not defined Question : How should I use another record of the same model as a foreignkey in my current model TIA -
AttributeError: 'list' object has no attribute 'order_by'
I was trying to combine two queryset objects by itertools chain python predefine function and filter this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'. If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance. views.py : try: qs = Conversation.objects.filter( Q(chat__from_user=user) & Q(chat__to_user=to_user)) qs_2 = Conversation.objects.filter( Q(chat__from_user=to_user) & Q(chat__to_user=user)) except: raise ValidationError({"message":"bad request"}) all_qs = list(chain(qs, qs_2)).order_by('-created_on') -
Django Redirecting to a created view (pk)
I am trying to redirect to a created post after filling up the form. I tried following Django redirect to created post after form but I encountered this error TypeError at /inquiry/ inquiry() missing 1 required positional argument: 'pk' def inquiry(request,pk): form = RescueeForm() if request.method == 'POST': form = RescueeForm(request.POST) if form.is_valid(): form.save() return redirect ('rescuee' form.pk) context = { 'form' : form } return render(request, "inquiry_page.html", context) urls.py urlpatterns = [ path('', views.index, name='index'), path('inquiry/', views.inquiry, name='inquiry'), path('rescuee/<int:pk>', views.rescueeview, name='rescuee'), ] -
Django filtering in bootstrap
I try to filter username from my all users in django and I need to have some forms in bootstrap. What I did is: <div class="form-group col-4 text-left"> <label for="exampleFormControlInput1">User Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="username" {{customer_filter.form.username}}> </div> It is working but in my page I have extra > printed on my page. I don't know how to use {{customer_filter.form.username}} in bootstrap in label tag. -
ValueError('Related model %r cannot be resolved' % self.remote_field.model)
while using AUTH_USER_MODEL django throwing error. while adding my own custom model to authenticate login.when i run command python manage.py migrate it give me an error, i actually want to create a custom user model to authenticate login to my own custom admin login my settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'g4!we933keyd4p*2z*1rz)=zl%s9qi#21^to$@*79e6rz8bj1e' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'farmingwave',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static') ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'seo.guru.tech00@gmail.com' EMAIL_HOST_PASSWORD = 'working12090' AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',] AUTH_USER_MODEL = 'farmingwave.CustomUser' my models.py from django.db import models from django.forms import ModelForm from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser, BaseUserManager from django.conf import settings class CustomUser(AbstractUser): Username = models.CharField(max_length=255, unique=True,default='root') password = models.CharField(max_length=50,) my admin.py from django.contrib import admin from .models import contactForm from .models import writerForm from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import LoginForm from .models import CustomUser class CustomUserAdmin(admin.ModelAdmin): form = LoginForm model = CustomUser admin.site.register(CustomUser,CustomUserAdmin ) class Meta: db_table = 'user_auth' class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How can i override the save() method in admin page
it maybe look like a simple question, but i been struggling for weeks now, i want to override the save method in admin page, for a model name Transaction that i created, i want to pre save each transaction by groups.. lets say for example i have created 2 groups (Test1, Test2) and i assigned users to each group, and a user from group Test1 made a transaction and saved it. i want all users from Test1 group to see the transaction and modify it, but not Test2 groups members. I override save method and queryset method, but yet it still not working. any ideas ? here is my code class TransactionAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user.groups print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__in=request.user.groups.all()) -
Adding "group" field in Django User Admin
I am trying to add a "group" field to show group permissions on the user panel in Django 3.1.2. I tried combining this and this, but always end up in either end up with The model User is already registered with 'auth.UserAdmin' or The model User is not registered (when trying to unregister first): from django.contrib import admin from django.contrib.auth.models import User # fails in "model User not registered" admin.site.unregister(User) #fails in already registered with auth.UserAdmin @admin.register(User) class UserAdmin(admin.ModelAdmin): def group(self, user): return ' '.join([g.name for g in user.groups.all()]) list_display = ['username', 'email', 'first_name', 'last_name', 'is_active', group] list_filter = ['groups', 'is_staff', 'is_superuser', 'is_active'] How would I correctly register my custom UserAdmin? -
Django adding data into model from nested json returning TypeError: 'NoneType' object is not subscriptable
I am using a third-party API to get data and add it into my database via objects.update_or_create() method. This data has many records and some of the fields in the response only exists for certain records. Below the a snippet of the JSON that is returned from the API. However this data is only present for some of the records in the JSON response. When I try to add this data into my model, I am getting the following error: 'f_name': i.get('card_faces')[0].get('name'), TypeError: 'NoneType' object is not subscriptable I am trying to have it so that if the card_faces field exists, True is added to the card_face column in the database, and then the card_faces name to the database. If card_faces doesn't exist, then False is added to the card_face column in the database, and subsequent fields are null. JSON: { "data": [ "name": "Emeria's Call // Emeria, Shattered Skyclave", "card_faces": [ { "object": "card_face", "name": "Emeria's Call" }, { "object": "card_face", "name": "Emeria, Shattered Skyclave" } ], ] } views.py: for i in card_data: Card.objects.update_or_create( id=i.get('id'), defaults={ 'name': i.get('name'), 'card_faces': i.get('card_faces'), 'f_name': i.get('card_faces')[0].get('name'), 'b_name': i.get('card_faces')[1].get('name'), } )