Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-mptt: Unknown column 'goods_category.lft' in 'where clause'
After updating django-mptt from 0.11.0 to 0.13.3, I getting an error Unknown column 'goods_category.lft' in 'where clause' goods/models.py class Category(MPTTModel): ... class Product(models.Model): category = TreeForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) ... goods/views.py categories = Category.objects.add_related_count( Category.objects.filter(is_public=True), Product, 'category', 'count', cumulative=True ) goods/templates/goods/sidenav.html {% recursetree categories %} <li> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}> {{ node.name }} </a> {% if not node.is_leaf_node %} <ul class="nested vertical menu {% if node.slug not in path %}display-none{% endif %}"> <li class="hide-for-large"> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}>Show all </a> </li> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} manage.py makemigrations - No changes detected manage.py migrate - No migrations to apply -
Django Celery, App import error only on production
I have a file structure like this: myapp artist_applications tasks.py tasks celery.py # settings.py INSTALLED_APPS = [ 'myapp.artist_application', ... # celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings.production') app = Celery("tasks") app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() # tasks.py from tasks.celery import app as celery_myapp from django.apps import apps from django.conf import settings import requests @celery_esns.task(name='sample_task') def sample_task(): print('TESTING CELERY') @celery_esns.task(name='publish_artist_task') def publish_artist_task(payload, artist_id): r = requests.post(settings.PUBLISH_URL, json = payload) if r.status_code == 200: apps.get_model('artist_application', 'Artist').objects.filter(unique_id=artist_id).update(published=True) else: raise Exception("Error publishing artist with id: " + artist_id) On development all is running fine when I start Celery with: celery -A myapp.tasks worker -Q celery -l info But on production I run the command (in a virtualenv) and I get the error: django.core.exceptions.ImproperlyConfigured: Cannot import 'artist_application'. Check that 'myapp.artist_application.apps.ArtistApplication.name' is correct. Any ideas where to look? I don't get how 'runserver' is loading the apps differently then wsgi? -
category_id expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager
Looks like error is because of obj.category_id in serializer have something to do with many to many relationship. Error: TypeError: Field 'category_id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager object at 0x0000025BB1C23EE0 Here is my code: modles.py: class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) category_icon = models.CharField(max_length=500, null=True, blank=True) category_image = models.CharField(max_length=500, null=True, blank=True) category_description = models.CharField(max_length=1000, null=True, blank=True) active_status = models.BooleanField(default=True) def __str__(self): return str(self.category_id) +" -"+ str(self.category_name) class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) # parent_id = models.ForeignKey("Services", on_delete=models.CASCADE, default=0) # parent_id = models.IntegerField(default=0) service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) def __str__(self): return str(self.service_id) +" -"+ str(self.service_name) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) views.py: class ServicesList(viewsets.ViewSet): def retrieve(self, request, pk=None): queryset = Category.objects.get(category_id=pk) querysetSerializer = CategoryServiceListSerializer(queryset) return Response({"status":200,"message":"Success","data":querysetSerializer.data}) serialziers.py: class ServiceListSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class VariantServiceSerialzier(serializers.ModelSerializer): # service_id = ServiceListSerializer(many=True) # Getting all service data, #i want only data for perticular … -
Redirect to next post after form submit
I am building a Blog App and I am trying to implement a feature - In which a user can rate blogs in one page and after user click Save Rate then user will redirect to next review blog page and user will ratenext blog. But it is not redirecting to next rate blog page. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) Rating_Choice = [('1','1'), ('2','2')] class Rate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) ratings = models.CharField(max_length=1, choices=Rating_Choice) views.py def rate_blog_post(request, blog_id): obj = get_object_or_404(Blog, pk=blog_id) next_blog = Question.objects.filter(rate__ratings=None) if request.method == 'POST': form = Form(data=request.POST) if form.is_valid(): post= form.save(commit=False) post.user = request.user post.blog = data post.save() # redirect here return redirect('rate_blog_post', pk=data.id) else: form = Form() context = {'obj':obj, 'form':form} return render(request, rate_blog_post.html', context) Form is working fine, it is saving the ratings What have i tried so far ? : I have tried using a next_blog like :- return redirect('rate_blog_post', rate_blog_post=question_id) But it showed Reverse for 'rate_blog_post' with keyword arguments '{'pk': 2}' not found I have tried many times but did't worked for me. I will really appreciate your Help. Thank You So, i made a choices of reviews. And User will redirect … -
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.