Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overrding get_queryset in the model file without having to create a new model manager in django?
I have a model and I have used it at multiple places now and changing it all places is cumbersome. Could you please let me know how to do that? I already know the I can create a custom model manager but it's not feasible to change the model manager at all places. class Slot(models.Model): state = models.CharField(max_length=20, choices=SLOT_STATE, default=SLOT_STATE[0][0]) According to the docs- # First, define the Manager subclass. class DahlBookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(author='Roald Dahl') # Then hook it into the Book model explicitly. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) objects = models.Manager() # The default manager. dahl_objects = DahlBookManager() # The Dahl-specific manager. I want to retain the same default manager but I want to exclude all the NULL slot. P.S. slot can have null state. -
how to update field with django rest if post uniqueness fails?
I'm new to django rest and I've been stuck here for some time. I've a table with four fields (gtin,shop,expirydate,quantity) I also made it that the first 3 are unique with each others I've created 2 methods inside my views, the get and post but since I've the uniqueness if I tried to add the same field with different quantity I get The fields gtin, shop, expirydate must make a unique set. so I tried to work on a patch method so I can increase the current quantity with the new one, but couldn't get it to work this is my views from django.http import HttpResponse,JsonResponse from rest_framework.parsers import JSONParser from .models import Stock from .serializers import StockSerializer from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def stock_list(request): if request.method == "GET": gtin = request.GET['gtin'] shop = request.GET['shop'] queryset = Stock.objects.all().order_by('expirydate') if gtin is not None and shop is not None: queryset = queryset.filter(gtin=gtin) queryset = queryset.filter(shop=shop) queryset=queryset.first() serializer = StockSerializer(queryset) return JsonResponse(serializer.data,safe=False) elif request.method == "POST": data = JSONParser().parse(request) serializer = StockSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status = 404) elif request.method == 'PATCH': queryset = Stock.objects.all() data = JSONParser().parse(request) serializer = StockSerializer(data=data) queryset.perform_update(serializer) if serializer.is_valid(): … -
How can I successfully run django private chat2?
I installed django private chat2, as in this tutorial: https://github.com/Bearle/django_private_chat2 But, on the site it shows me like this: eror How do I view messages differently? How do I get to an html page? -
I have to find pmtlist and pmtid with service id in python
File contents: serviceid=2251:tsid=6:orignetwid=99:access=clear:pids=3:clearpids=3:scrambledpids=0:packets=2315:bitrate=1745711:bitrate204=1894282:servtype=1:pmtpid=3251:pcrpid=5251:pidlist=3251,5251,6251 Code: file = open('t5001.txt','r') file1 = file.read() file2 = file1.split(":") Input = input("Enter The student ID :- ") for i in file2: if Input in i: print(i) file.close() I have written this code but not getting answer i am doing just silly mistake not getting that one can anyone will help me -
Manytomanyfields through table data list_diplay repeating grouped data
screendata I have Django model manytomany through table: bridge_qual_id, bridge_uoc_id, sequence_id bridge_qual_id is only one record where units in the qualification are attached with sequence extra field for delivery order. I want qualification to display only once and listing all units for it. I tried format_html_join in models class method and calling in list_display but may be doing correct. At the moment admin.ModelAdmin code is just listing table column names: list_display = ['bridge_qual', 'bridge_uoc', 'uoc_sequence'] I can not do order_by on field in MySql in backend so tried following to change queryset but no effect. @admin.register(tp_uoc_sequence, site=pg_site) class tpuocAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(tpuocAdmin, self).get_queryset(request) qs.extra(where= ["""bridge_uoc_id IN ( SELECT bridge_qual_id FROM tp_uoc_sequence WHERE bridge_qual_id=1) as modified group by bridge_qual_id ORDER BY bridge_qual_id""" ]) return qs list_display = ['bridge_qual', 'bridge_uoc', 'uoc_sequence'] -
Using a Deserialized Django Object Directly
I have found a lot of documentation about serializing a queryset in django, and i found out that to serialize a single object or instance of a model you simply needed to wrap that instance in a list '[]'. But here is my Issue, I serialized an object in one view passed it into session and deserialized said object in another view and it work just fine... but what i get is a python generator, how can i get the initial object with the generator? -
Django - [Errno 2] No such file or directory after compresing image
have a blog where users can upload and edit posts. I wanted to resize any uploaded image to a max. of 500*500px. For this purpose I created an if statement before save models.py def _upload_path(instance, filename): return instance.get_upload_path(filename) class Post(models.Model, HitCountMixin): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) image = models.ImageField(blank=True, null=True, upload_to=_upload_path) def __str__(self): return self.title def get_upload_path(self, filename): return "posts/images/" + str(self.user.username) + "/" + filename def save(self, *args, **kwargs): # resize image if self.image: img = Image.open(self.image.path) # Open image using self if img.height > 500 or img.width > 500: new_img = (500, 500) img.thumbnail(new_img) img.save(self.image.path) # saving image at the same path return super(Post, self).save(*args, **kwargs) Unforunalty the image path gets not recognized and I get an error [Errno 2] No such file or directory: '/Users/vic/Desktop/django_project/media/postimage1.jpg' This path is wrong! The upload-path is defined within the get_upload_path() function and should lead to /Users/vic/Desktop/django_project/media/posts/images/username/postimage1.jpg I tried to change the open path to img = Image.open(str(settings.MEDIA_URL) + self.get_upload_path(self.image.name)) or to hardcoded URL with localhost:8000... but nothing worked. If I remove the if statement the file gets uploaded in the correct path so the error must be at img definition. -
Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions' did not migrate i'm making crm and i
I'm making this crm and i got this error i will share code with you i'm taking this video and i got this error https://www.youtube.com/watch?v=fOukA4Qh9QA&t=4925s ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. leads.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. leads.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. Setting.py Here's my settings code """ INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODELS = 'leads.User' models.py Here's my models code from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
create a multidimensional array field in Django model
I get multidimensional arrays must-have array expressions with matching dimensions error from Django when I try to insert data into my model, below is my model and the data format i have effect = ArrayField( ArrayField( models.IntegerField( blank=True, null=True ), null=True, ), null=True, default=list, size=11 ) and this is my data format: "effect": [null,[95],[20],[0],[0],[0],[0],[0],[0],[0],[0]], this is how my data looks and my current model field structure isnt working, i will like a solution to problem please. -
Having issues with Django-Graphene
i built my own content management system here: https://github.com/bastianhilton/Alternate-CMS and I have added graphql support recently with Django-Graphene and updated my models, schema.py. However as I try to run a query, i'm getting the below message. Any direction would be greatly appreciated. { "errors": [ { "message": "relation \"shop_addresscountry\" does not exist\nLINE 1: ... \"shop_addresscountry\".\"is_shipping_country\" FROM \"shop_addr...\n ^\n" } ], "data": { "allAddresscountry": null } } -
Reduce bandwidth loading Django page
Building a Django newsfeed project. The main page of the site is going to be a two timelines adjacent to each other, consisting of a twitter feed and a reddit feed respectively. Utilizing the inspect module in chrome I noticed it was taking upwards of 5.5s to load the page. I have a services script running on page refresh that makes api calls to reddit and twitter, fetches data, then creates a Post object for that particular post/tweet. The post object I modeled in models.py. I then grab all the Post objects and pass them through the view as a context variable. In my template I iterate through the Posts and embed the raw html onto the page. In what way can I change the logic/architecture of my project so the page loads quicker, based on current procedures? Any suggests on how to increase efficiency within the context of my project? Here's my code: services.py import praw import tweepy import requests import webbrowser import pprint import json import os import sys import datetime from .models import Post # twitter sys.path.insert( 0, 'C:\\Users\\Nick\\Desktop\\2021 Python\\NBA_Project\\NBAblog\\news') here = os.path.dirname(os.path.abspath(__file__)) # connect to api def tweet_connect(key, secret, access_key, access_secret): auth = tweepy.OAuthHandler(key, secret) auth.set_access_token(access_key, … -
Modify queryset model fields individually and return queryset without saving the models to db
I want to change a specific model field based on other parameters for each model of the queryset. Afterwards, I would return the queryset with adjusted field values, but without altering the database entries. I'm using django-rest-framework and I currently use bulk_update which sadly updates my db recordings of the models: class CustomModelView(viewsets.ModelViewSet): serializer_class = ModelSerializer def get_queryset(self): long = self.request.query_params.get('long') lat = self.request.query_params.get('lat') point = GEOSGeometry(f'POINT ({long} {lat})', srid=4326) city = City.objects.filter(poly__contains=point) if len(city) == 1: max = CustomModel.objects.aggregate(Max('value')) models= CustomModel.objects.filter(city__in=city) objs = [] for mod in models: mod .attractivness /= max['value__max'] objs.append(mod ) CustomModel.objects.filter(city__in=city).bulk_update(objs, ["value"]) queryset = models return queryset return CustomModel.objects.none() Here I'd want to normalise each "value" field of each model from the query set by the max value of the query set. How can I update the queryset with new field values and alter the database? -
Django Pytest image upload image unit test
I'm using Django 3.2.6, django-pytest, and factory boy to run automated tests. This is the function I use to make a test image: from django.core.files.uploadedfile import SimpleUploadedFile def test_image(name='test.jpg', size=(250,250)): img = Image.new('RGB', size) content = img.tobytes() # return Django file for testing in forms and serializers return SimpleUploadedFile(name, content=content, content_type='image/jpeg') This is the view being tested: class PhotoCreateView(LoginRequiredMixin, CreateView): model = Photo form_class = PhotoForm success_url = '/' template_name = 'photos/create.html' def form_valid(self, form): new_category = form.cleaned_data['new_category'] if new_category: category = Category.objects.create(name=new_category) form.instance.category = category return super().form_valid(form) Here is the test class: class TestPhotoCreateView: url = reverse('photos:create') def test_photo_create_view_authenticated_user_can_access(self, client, user): client.force_login(user) response = client.get(self.url) assert response.status_code == 200 def test_photo_create_view_unauthenticated_user_cannot_access(self, client): response = client.get(self.url) assert response.status_code == 302 def test_photo_create_view_form_valid_existing_category(self, client, user): client.force_login(user) for _ in range(3): CategoryFactory() category = CategoryFactory() image = test_image() form_data = { 'category': category.pk, 'new_category': '', 'description': 'hello world', 'image': image, } response = client.post(self.url, form_data) print(response.content) photo = Photo.objects.get(description=form_data['description']) assert photo.category == form_data['category'] All of the tests pass except for test_photo_create_view_form_valid_existing_category. i ran pytest --capture=tee-sys and this error was in the image field: <p id="error_1_id_image" class="invalid-feedback"><strong>Upload a valid image. The file you uploaded was either not an image or a corrupted image.</strong></p> … -
django not filter by category name
django cannot filter by category name in url The Problem The Problem MyModels Code Views Code HTML Code URL code -
Serialize data to json formate using native serializer Django
I have this dictionary which I need to pass to another view, knowing that possible ways of doing that are either through sessions or cache, now when I am trying to pass to session it is throwing me an error that data is not JSON serializable probably because I have DateTime fields inside this dictionary session_data = serializers.serialize('json',session_data) error on above statement 'str' object has no attribute '_meta' updated date is somewhat in this format {'city_name': 'Srinagar', 'description': 'few clouds', 'temp': 26.74, 'feels_like': 27.07, 'max_temp': 26.74, 'min_temp': 26.74, 'sunrise': datetime.time(6, 11, 10), 'sunset': datetime.time(18, 43, 59)} -
How to send verification email in django
views.py from django.contrib.auth import authenticate, logout as userlogout, login as userlogin def signup(request): if request.method == "POST": username=request.POST['username'] firstname=request.POST['firstname'] lastname=request.POST['lastname'] email=request.POST['email'] password=request.POST['password1'] if User.objects.filter(username=username).exists() : messages.error(request, "Username already exists.") return redirect(request.META['HTTP_REFERER']) elif User.objects.filter(email=email).exists(): messages.error(request,"An account already exists with this email.") return redirect(request.META['HTTP_REFERER']) else: myuser = User.objects.create_user(username, email, password) myuser.first_name= firstname myuser.last_name= lastname myuser.save() messages.success(request, " Your account has been successfully created.") return redirect(request.META['HTTP_REFERER']) I have to send verification email after signup. I have some methods but it didn't work because it works on forms which is created by django but i have own created form in html and get all the data and then saved it with above method. Has someone have any idea how to send verification email. -
Is there a way to create "tag" system in django?
I am trying to create a e-commerce web app that requires tags to find out the categorized items easily and efficiently in django. Until now I have tried using foreign keys but can't find my way out. Any suggestions are welcomed. -
How to find django objects in a manytomany relation (with a throught)?
I need to find services with pricing for each user. I've defined my models: class User(AbstractUser): """Default user model.""" username = None email = models.EmailField(unique=True) proposals = models.ManyToManyField( Service, through=Pricing, blank=True) class Service(models.Model): name = models.CharField(max_length=50) class Pricing(models.Model): user = models.ForeignKey('users.User', on_delete=models.PROTECT) service = models.ForeignKey(Service, on_delete=models.PROTECT) price = models.IntegerField() In my template, I can get my user with associated proposal with this for loop {% for proposal in object.proposals.all %} {{ proposal }} {% endfor %} I do not have prices but only services names. What am i missing ? -
Read after write does not include written data
I have a simple React client and Django server setup for a todo list. On creating a TODO item a POST request is sent with its data, and after the response is received a GET request is sent to retrieve any updates to the list. However the GET will usually not contain the item just written. I can have the written item added to that list from the client side, but I'm wondering if there is a way to configure the server side so that a request will contain updates of requests responded to before it. For reference here is an MVP of the Django side. The client is just using fetch. I've had the same result using Sqlite and Postgres models.py class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True from django.db import models class Todo(BaseModel): name = models.TextField() views.py import json from django.http import JsonResponse from django.views.decorators.http import require_POST, require_GET from django.views.decorators.csrf import csrf_exempt from django.forms.models import model_to_dict from .models import Todo @require_POST @csrf_exempt def todo_add(request): data = json.loads(request.body) name = data.get('name') new_todo = Todo(name=name) new_todo.save() return JsonResponse({'new_todo': model_to_dict(new_todo, fields=['id', 'name']}) @require_GET @csrf_exempt def todo_list(request): results = Todo.objects.all().values('id', 'name') return JsonResponse({'todo_list', list(results)}) -
How to collect all photos from user in 1 pages Using django
i wanna ask.Im making a website using django.but i wanna make all the photo from the user uploaded was show in 1 spesific pages. How i want to link it? -
How to customise update method for ManyToMany fields in Django Rest Framework
I have a few models with ManyToMany relationships between them and I need to override the create and update method to make the POST and PUT request work in DRF. Here's my code so far: class CreateFolderSerializer(serializers.ModelSerializer): class Meta: model = Folder fields = ("id", "title", "description", "users") def create(self, validated_data): users = validated_data.pop( 'users') if 'users' in validated_data else [] folder = Folder.objects.create(**validated_data) folder.users.set(users) return folder This create method works perfectly. I tried re-creating the same logic for the update method, but it doesn't work: class FolderSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Folder fields = '__all__' def update(self, instance, validated_data): users = validated_data.pop('users') if 'users' in validated_data else [] instance.users.set(users) instance.save() return instance When I send a PUT request, the object does not get modified at all, it gets deleted altogether. Any clue? Thanks a lot. -
How to show django logging and error log in Cloud Run's log?
I'm using Django, uwsgi and nginx in Cloud Run. A Cloud Run service can't show django logging and error log. That's why Error Report can't use ,too. Cloud Run log is like this. This is my settings. Django settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'local': { 'format': "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" }, 'verbose': { 'format': '{message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'local', }, }, 'root': { 'handlers': ['console'], 'level': 'WARNING', }, 'loggers': { 'users': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } } } uwsgi.ini [uwsgi] # this config will be loaded if nothing specific is specified # load base config from below ini = :base # %d is the dir this configuration file is in socket = %dapp.sock master = true processes = 4 [dev] ini = :base # socket (uwsgi) is not the same as http, nor http-socket socket = :8001 [local] ini = :base http = :8000 # set the virtual env … -
django display objects on all url
MyViews: MyHTMLCode: MyUrl: [The Proablem is do not filter by category name][4] -
why django is using email host user as (from email)
The problem is that (from email) is being used as default email host user. So how to solve this problem? Django version 2.2 contact html template views.py for contact settings.py in Django My contact page The email -
“” value has an invalid format. It must be in the format of YYYY MM DD HH:MM
models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class recommend(models.Model): sno = models.AutoField(primary_key=True) comment= models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) timestamp= models.DateTimeField(default=now) def __str__(self): return self.recommend[0:20] + "..." + "by" + self.user.username error importing signals Operations to perform: Apply all migrations: admin, apps, auth, blog, contenttypes, home, sessions, verify_email, videos Running migrations: Applying home.0004_alter_contactme_timestamp...Traceback (most recent call last): File "/storage/emulated/0/imaginecode/manage.py", line 22, in <module> main() File "/storage/emulated/0/imaginecode/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 140, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 608, in alter_field self._alter_field(model, old_field, new_field, old_type, …