Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: Command errored out with exit status -11
I ran this command in a virtual environment with Python3.6.7: pip3 install -r requirements.txt --use-deprecated=legacy-resolver Then I got this error: ERROR: Command errored out with exit status -11: command: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' cwd: None Complete output (0 lines): ERROR: Command errored out with exit status -11: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' Check the logs for full command output. -
Django pass back some data on post
if not request.user.is_doctor and not request.user.is_staff: bookAppointment = BookAppointmentForm() bookAppointment.fields['doctors'].queryset = Profile.objects.filter(Q(is_active=True)&Q(is_doctor=True)) context['bookAppointment'] = bookAppointment I would like to add data to the page if a dropdown was selected with the above no redirects since I am using the below to pass a table back. d = get_date(request.GET.get('day', None)) print(d) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) # Figure how to pass this context['calendar'] = mark_safe(html_cal) html: <form method = "POST" action='/displayCalendar' enctype="multipart/form-data"> {% csrf_token %} {{ bookAppointment.as_p }} <button type="submit" name='bookAppointment'>Check availability</button> </form> {{calendar}} forms.py class BookAppointmentForm(forms.ModelForm): class Meta: model = Calendar fields = ('doctors',) -
Unauthorized User Error in Django Unit test
Hello! I am writing a unit test case for a website, The website has a basic function of address update, the address update requires an authentic user login, so I am using the temporary token for that purpose in query-param (as a part of website functionality) from django.test import TestCase from accounts.models import Address, User, Business, Employment from accounts.controllers import AddressController class Test_Cases_AddressController(TestCase): user= User.objects.create_user( birth_year=1996, birth_month= 8, birth_day = 15, marital_status= "married", \ reset_password_token = "xxxxy", confirmation_token = "xxxx", password_reset_at= "2022-01-12 13:12:13", \ confirmed_at= "2022-01-12 13:12:13", email= "testuser@example.com", username = "testuser123") def test_update_address(self): address1 = Address.objects.create(street_1="abc abc abc", city="lahore", state="punjab", zip="54000", type="abcdef") API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.put(API_LOGIN_URL, {"street_1": "xyz xyz xyz"}, content_type='application/json' ) self.assertEquals(response.status_code, 201) def test_get_address(self): API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.get(API_LOGIN_URL) self.assertEquals(response.status_code, 200) but I am still getting the same unauthorized error PS C:\Users\Lenovo\web> docker-compose run --rm api sh -c "python manage.py test accounts" Creating web_api_run ... done Creating test database for alias 'default'... System check identified some issues: WARNINGS: accounts.User.privacy: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. main.NonProfit.website: (fields.W340) null has no effect … -
django create object using nested serializer and model
Hi i am try to create 3 model objects in single post request from flutter to django restframework but i don't know how to use serializer to create object so I'm implemented many lines of code to done this but it's working fine. It's correct or not View.py from rest_framework.views import APIView from .models import Booking, FromAddress, Product, ToAddress from .serializers import BookingSerializer, FromAddressSerializer from rest_framework.response import Response from rest_framework import status # Create your views here. class BookingView(APIView): def get(self,req): bookings = Booking.objects.all() serializer = BookingSerializer(bookings,many=True) return Response(serializer.data) def post(self,req): user = self.request.user fromAddressData = req.data['from_address'] toAddressData = req.data['to_address'] productData = req.data['product'] from_address = FromAddress.objects.create(name=fromAddressData['name'],phone=fromAddressData['phone'],address=fromAddressData['address'],) to_address = ToAddress.objects.create(name=toAddressData['name'],phone=toAddressData['phone'],address=toAddressData['address'],pincode=toAddressData['pincode'],) product = Product.objects.create(title = productData['title'],weight = productData['weight'],nature_of_content=productData['nature_of_content'],breakable=productData['breakable'],) from_address.save() fadrs = FromAddress.objects.get(id= from_address.id) print(FromAddressSerializer(fadrs)) to_address.save() product.save() booking = Booking.objects.create(user=req.user,from_address=fadrs,to_address=to_address,product= product, price=req.data['price'], payment_id=req.data['payment_id']) booking.save() return Response('Success') Model.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class FromAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) def __str__(self): return self.name class ToAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) pincode = models.CharField(max_length=6) def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=50) weight = models.DecimalField(max_digits=5,decimal_places=2) nature_of_content = models.CharField(blank=True,null=True,max_length=100) breakable = models.BooleanField(default=False) def __str__(self): return f'{self.title} … -
displaying None instead of data in the form of table
Here, select machine name and operation number, after select and save, It is displaying none instead of data like machine name and operation number in the form of table. Please help me out to solve this. I am new in Django. urls.py: urlpatterns = [ path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine') ] views.py: def upload(request): machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machine_name', '') operation_no = request.POST.get('operation_no') choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no) machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine}) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField(null=True) def __str__(self): return self.machine_name upload.html: <form action="{% url 'save_machine' %}" method="post"> {% csrf_token %} <select> <option>Select Machine Name</option> {% for machine in machines %} <option name="machine_name">{{ machine.machine_name }}</option> {% endfor %} </select> <br> <br> <select> <option>Select Operation Number</option> {% for machine in machines %} <option name="operation_no">{{ machine.operation_no }}</option> {% endfor %} </select> <br> <br> <br> <input type="submit" value="Save"> </form> <tr> <td>{{choiced_machine.machine_name}}</td> <td>{{choiced_machine.operation_no}}</td> </tr> -
Adding criteria to Django DRF responsive map InBBoxFilter with viewsets.py, not views.py?
We've developed a responsive map using this tutorial where Django Rest Framework serves responses that populates the map. My viewsets.py: class MarkerViewSet(viewsets.ReadOnlyModelViewSet): """Marker view set.""" bbox_filter_field = "geom" filter_backends = (filters.InBBoxFilter,) queryset = Tablename.objects.all() serializer_class = MarkerSerializer pagination_class = GeoPaginator I'd like to add optional criteria to this filter if they are found in a GET value. The rest of my project uses views.py, which filters things differently. My simplified views.py which does this for something else: def EgFilterView(request): qs = Tablename.objects.all() date_min_query = request.GET.get('dmin') min_date = 1970 qs = qs.filter(date__gte=dt.datetime(int(date_min_query), 1, 1, tzinfo=pytz.UTC)) context = { 'queryset': qs, 'dmin': min_date, } return render(request, "main_page.html", context) But it looks like viewsets.py doesn't handle .get() values in this way, but instead uses .list() and .create(), which I don't understand. How can I include additional filters into my viewsets.py to further filter things with GET values? Would it be better to attempt to convert this viewsets.py / other complicated API stuff I don't understand into views.py? -
How can I restrict users to delete other's posts in django using class based views?
my views.py file: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin, ) from .models import Post # Create your views here. class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" ordering = ["-date_posted"] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin): model = Post fields = ['title', 'genere', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "blog-home" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "/" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def about(request): return render(request, 'blog/about.html') My models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) genere = models.CharField(max_length=50, default='') def __str__(self): return f'{self.title} by {self.author}' def get_absolute_url(self): return reverse('blog-home') my urls.py url: from django.urls import path from .views import PostListView, … -
JWT authentication for Django rest framework --> error ={ "detail": "Authentication credentials were not provided." }
I'm using JWT for authentication and I can't make this error go away... HTTP 401 Unauthorized Allow: GET, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } Below are all my code files... I think the error is in the simple_jwt section in the settings file but can't figure out what. I looked up a few stackoverflow answers already but nothing seem to work out in my case. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', ), } from datetime import timedelta from django.conf import settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), # 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken, Token from .models import Book class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'email', 'username', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): … -
Django: Check at model level if anything in ManyToMany field before saving
There's a lot of questions worded similarly, but every single one I've seen is somebody trying to get some kind of data through a ManyToMany relationship before saving it. I'm not trying to use the relationship at all before saving, I just want to see if the user put anything there or not. My model has a ForeignKey field pointing to a parent model, and two ManyToMany fields pointing to other models, but I only want users to be able to use one M2M field or the other, not both. This model is being edited through the admin as an inline on its parent. models.py class ProductSpecial(models.Model): # name, slug, image, etc class ProductSpecialAmount(models.Model): special = models.ForeignKey(ProductSpecial, related_name='amounts', on_delete=models.CASCADE) amount = models.IntegerField() brands = models.ManyToManyField(ProductBrand, related_name='specials', blank=True) lines = models.ManyToManyField(ProductLine, related_name='specials', blank=True) admin.py class ProductSpecialAmountInline(admin.StackedInline): model = ProductSpecialAmount # fieldsets, etc @admin.register(ProductSpecial) class ProductSpecialAdmin(admin.ModelAdmin): inlines = [ProductSpecialAmountInline] # fieldsets, etc I only want users to be able to choose from brands or lines, but not both, and I would like to validate this before save and throw a validation error if necessary. My initial attempt was to just do... class ProductSpecialAmount(models.Model): # ... def clean(self): if self.brands and self.lines: raise … -
Given models relations nested 3 layers what query will return an object I can pass to Django Rest Framework model serializers
Given models related three levels deep how can I construct a query where I can pass the response to a Django Rest Framework model serializer? The code below with one layer of relationship works. Modles class SubArea(models.Model): label = models.CharField(max_length=20) fiber_switch = models.ForeignKey( 'FiberSwitch', related_name='sub_areas') class BackboneLine(models.Model): sub_area = models.ForeignKey( SubArea, related_name='backbone_lines') source = models.ForeignKey( Enclosure, related_name='backbone_lines_out') destination = models.OneToOneField( Enclosure, related_name='backbone_line_in') @property def label(self): return f'{self.source.box_number} - {self.destination.box_number}' Serializers class BackboneLineSerializer(ModelSerializer): class Meta: model = BackboneLine fields = ['label'] class SubAreaSerializer(ModelSerializer): backbone_lines = BackboneLineSerializer(many=True) class Meta: model = SubArea fields = ['label', 'backbone_lines'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) But if I add the model BackboneLineSegments along with a serializer for it, and change the BackoneLineSerializer to handle it I get errors. Added Model class BackboneLineSegment(models.Model): location = models.LineStringField() buried = models.BooleanField(default=False) backbone_line = models.ForeignKey( BackboneLine, related_name='segments' ) New Serializer class BackboneLineSegmentSerializer(GeoFeatureModelSerializer): class Meta: model = BackboneLineSegment geo_field = 'location' fields = ['location', 'buried'] Updated BackboneLineSerializer class BackboneLineSerializer(ModelSerializer): segments = BackboneLineSegmentSerializer(many=True) class Meta: model = BackboneLine fields = ['label', 'segments'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) This throws the following error. Got AttributeError when attempting to get a value for field segments on serializer BackboneLineSerializer. The serializer … -
How to fix Session matching query does not exist?
I made a raw django website to prevent multiple sessions by a user. It worked fine locally but it started throwing errors when I uploaded it to pythonanywhere. This happened after I logged into the site. If you want to log into the site use: E-mail: career Pwd: Qazpl,@123 Here is the error, I get: Environment: Request Method: GET Request URL: https://careerabacusgallery.pythonanywhere.com/ Django Version: 4.0.1 Python Version: 3.9.5 Installed Applications: ['onlinetest.apps.OnlinetestConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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', 'onlinetest.middleware.OneSessionPerUserMiddleware'] Traceback (most recent call last): File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/careerabacusgallery/statelevel/onlinetest/middleware.py", line 19, in __call__ Session.objects.get(session_key=stored_session_key).delete() File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/careerabacusgallery/.virtualenvs/test/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at / Exception Value: Session matching query does not exist. My settings.py: """ Django settings for statelevel project. Generated by 'django-admin startproject' using Django 4.0.1. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable … -
How to show data when select and save
I am new in Django. In this project, select machine name and operation number, after select, we need to click on save button, after button click, data should display in the form of table, when button click only. Please tell me where I got wrong. Please. urls.py: urlpatterns = [ path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine'), ] views.py: def upload(request): machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machine_name', '') operation_no = request.POST.get('operation_no') choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no) machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine}) template upload.html <form action="{% url 'save_machine' %}" method="post"> {% csrf_token %} <select> <option>Select Machine Name</option> {% for machine in machines %} <option name="machine_name">{{ machine.machine_name }}</option> {% endfor %} </select> <br> <br> <select> <option>Select Operation Number</option> {% for machine in machines %} <option name="operation_no">{{ machine.operation_no }}</option> {% endfor %} </select> <br> <br> <br> <input type="submit" value="Save"> </form> <tr> <td>{{choiced_machine.machine_name}}</td> <td>{{choiced_machine.operation_no}}</td> </tr> models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name when I clicked on save button, I got this error: DoesNotExist at /save Machine matching query does not exist. Request Method: POST Request URL: http://localhost:8000/save Django Version: 4.0 Exception Type: DoesNotExist Exception Value: Machine matching query does not exist. Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 439, … -
How do you add validation to django rest framework api
I have two models, which look like this: class Item(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) sku = models.CharField(max_length=60) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) location = models.CharField(max_length=60) serial_number = models.CharField(max_length=60) def __str__(self): return self.name class Warehouse(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) def __str__(self): return self.name and they have two serializers which look like this: class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('id', 'name', 'sku', 'description', 'price', 'location', 'serial_number') #we need a validator that checks if location is in the list of warehouses #we need a validator that checks if sku is in the list of products class WarehouseSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Warehouse fields = ('id', 'name') I need a way to ensure that the location field for newly created items matches an existing name field from a warehouse. I also need the deletion of a warehouse to trigger the deletion of all items in that warehouse, or, failing that; if the warehouse has items, it cannot be deleted. I'm brand new to python and django, so any help would be massively appreciated! for reference, my views class looks like class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all().order_by('name') serializer_class = ItemSerializer class WarehouseViewSet(viewsets.ModelViewSet): queryset = Warehouse.objects.all().order_by('name') serializer_class = … -
Execute a Django view and redirect to another view like a request.POST
When I access my web page, let's say example.com, that url is associated with my index view. def index(request, pid): context = {} context['nbar'] = 'index' if request.method == 'POST': User = get_user_model() users = User.objects.all() context['users'] = users context['project_values'] = Project.objects.get(id=pid) return render(request, 'index.html', context) Inside my template (index.html) I have a button that simply changes the state of a certain project Active <-> Inactive If the user clicks the button, I want the view activate_project or deactivate_project to run in background and when the execution is finished, just reload index.html as a post.REQUEST . What I've tried: Activate - Deactivate views: def activate_project(request, pk): if request.method == 'POST': project_to_activate = ITT.objects.get(pk=pk) if project_to_activate.status == "Inactive": project_to_activate.status = "Active" project_to_activate.save() return redirect('/index/'+str(project_to_activate.id)+'/') def deactivate_project(request, pk): if request.method == 'POST': project_to_deactivate = ITT.objects.get(pk=pk) if project_to_deactivate.status == "Active": project_to_deactivate.status = "Inactive" project_to_deactivate.save() return redirect('/index/'+str(project_to_deactivate.id)+'/') The problem comes here: return redirect('/index/'+str(project_to_deactivate.id)+'/') If I use the redirect, it is treated as a GET instead of a POST. <WSGIRequest: GET '/index/5/'> In short, I need index to know that I am coming from deactivate_project or activate_project, how can I make the view index smart enough to know that? -
Django: How do I use a custom template for a specific sitemap only if I have multiple separate sitemaps?
I want to use a custom template only for a VideoSitemap when I have multiple sitemaps divided as follows: How can I use a custom template only for a specific sitemap? I want to use a custom template for VideoSitemap with a sitemap tag for Video. class VideoSitemap(Sitemap): changefreq = "weekly" def items(self): return Video.objects.published() def location(self, obj): return f"/video/{obj.pk}" def lastmod(self, obj): return obj.updated_at class PlaylistSitemap(Sitemap): ... class TagSitemap(Sitemap): ... # urls.py sitemaps = { "video": VideoSitemap, "playlist": PlaylistSitemap, "tag": TagSitemap } urlpatterns = [ path( "sitemap.xml", sitemaps_views.index, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "sitemap-<section>.xml", sitemaps_views.sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), ] -
Pass List of UUID to django endpoint url as param
I have this code #VIEWS def report_pdf(request, queryset): if request.method == "GET": trans = Transaction.objects.filter(id__in=queryset) return something #URLS path("pdf/<uuid:queryset>", views.report_pdf, name="get_pdf") Now from my frontend react iam sending a get request to this endpoint with a list of UUID values. I cant find a way to access that list in my view coming from frontend. Would appreciate any suggestions! -
Getting wsgi error after updating django==3.0.12 to django==3.1.13
I'm trying to update the django version in one of my projects, however, I run into a wsgi error if I update django==3.0.12 to django==3.1.13. I get the following error- django.core.exceptions.ImproperlyConfigured: The MEDIA_URL and STATIC_URL settings must have different values. I'm not sure whether it's because of an incorrect configuration, or If there is a bug in my code. -
Error when pushing app to Heroku (psycopg2 error)
I am trying to git push my heroku app and when I execute the following command git push heroku master I get the error below. I have tried brew install postgresql, reinstalling psycopg2, installing psycopg2-binary. I have been searching for a solution and trying various ones but none seem to working. I am not too familiar with psycopg2 to know what the exact problem is so I would appreciate any help. My code is below thank you! Enumerating objects: 107, done. Counting objects: 100% (107/107), done. Delta compression using up to 4 threads Compressing objects: 100% (104/104), done. Writing objects: 100% (107/107), 17.72 MiB | 1.82 MiB/s, done. Total 107 (delta 15), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: https://github.com/heroku/heroku-buildpack-python.git remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.9 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.9 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.4.1 remote: Downloading asgiref-3.4.1-py3-none-any.whl (25 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl … -
Django Rest Framework nested serializers AttributeError 'RelatedManager' object has no attribute
Full Error Got AttributeError when attempting to get a value for field segments on serializer BackboneLineSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'segments'. I can't figure out why I'm getting this error. I'm using what I think is the exact same code elsewhere with it working. The only thing I can think of is I may have changed the related_name on the backbone_line field of the BackboneLineSegments model from something else to 'segments'. All migrations have been applied, and I don't know why it would be causing issues. Maybe the database doesn't update the new related_name correctly? I'm using Postgres in case it matters. Models class BackboneLine(models.Model): sub_area = models.ForeignKey( SubArea, on_delete=models.SET_NULL, null=True, related_name='backbone_lines') source = models.ForeignKey( Enclosure, on_delete=models.SET_NULL, null=True, related_name='backbone_lines_out' ) destination = models.OneToOneField( Enclosure, on_delete=models.SET_NULL, null=True, related_name='backbone_line_in' ) @property def label(self): return f'{self.source.box_number} - {self.destination.box_number}' class BackboneLineSegment(models.Model): location = models.LineStringField() buried = models.BooleanField(default=False) backbone_line = models.ForeignKey( BackboneLine, on_delete=models.CASCADE, related_name='segments' ) @property def long_lat(self): return [list(coord_pair) for coord_pair in self.location] @property def lat_long(self): return [(cords[1], cords[0]) for cords in self.location.coords] Serializers class BackboneLineSegmentSerializer(GeoFeatureModelSerializer): class Meta: model = BackboneLineSegment … -
limiting fetch data in django-celery acting as a consumer from rabbitmq queue acting as a producer
I want to retrieve 10 data message in every period of django-celery periodic task from a rabbitmq queue containing 100000 data messages. everything works well. but I don't know how can I stop fetching data if 10 data messages have been retrieve in the specific period. here is my task.py @periodic_task(run_every=(crontab(minute='*/1')), name="task", ignore_result=True) def task(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') def callback(ch, method, properties, body): # do sth channel.basic_qos(prefetch_count=10, global_qos=True) channel.basic_consume(queue='name', on_message_callback=callback) channel.start_consuming() and here is my rabbitmq producer connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='name') for i in range(10000000): channel.basic_publish(exchange='', routing_key='name', body=msg) -
No reverse match error. Reverse for 'user-profile' with arguments '('',)' not found
I have created a messaging function on my website where logged in and guest users can send messages to other users. I have created an inbox for the logged in users to store these messages. When opening up a message from a guest (someone who doesn't have an account) I get an error: Reverse for 'user-profile' with arguments '('',)' not found. Based on my digging on the web I think this may be due to the fact that the guest user doesnt have a name attached? Could this be it and how would I fix it? Views.py: def createMessage(request,pk): recipient = Profile.objects.get(id=pk) form = MessageForm() try: sender = request.user.profile except: sender = None if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.sender = sender message.recipient = recipient if sender: message.name = sender.name message.email = sender.email message.save() messages.success(request, 'Your message was successfully sent!') return redirect('user-profile', pk=recipient.id) context = {'recipient': recipient, 'form': form} return render(request, 'users/message_form.html', context) Models.py: class Message(models.Model): sender = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True) recipient = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True, related_name="messages") name = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=200, null=True, blank=True) subject = models.CharField(max_length=200, null=True, blank=True) body = models.TextField() is_read = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) … -
Django How to add a User Foreignkey inside a User model?
I'm trying to insert a foreignkey of the User inside of the user model but I keep getting error. As as user I want to have two purposes, I can do i do a book to get my pets taken care of and also i can take care of other pets class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=255, default='John Doe') pet_sitter = models.ForeignKey('User',on_delete=models.CASCADE)//--->User inside User I tried get_user_model() it showed errors too// pet_appointments= models.ManyToManyField( 'User', through=Booking, through_fields=('patient', 'doctor') ) class Booking(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() owner_of_pet = models.ForeignKey(get_user_model(),related_name = "User",on_delete=models.CASCADE, blank=True,null=True) sitter = models.ForeignKey('User', on_delete=models.CASCADE) enter code here =============== error django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed -
Django Constraining Foreign Keys for multiple nested objects
Let's start with the models: class Brand(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) class ProductLine(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class Product(models.Model): id = models.UUIDField(primary_key=True name = models.CharField(max_length=255) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) product_line = models.ForeignKey(ProductLine, on_delete=models.CASCADE, blank=True, null=True) So we have brands. Brands can have 0 or more product_lines. A product always has a brand, and may also be within a product_line. My goal is to constrain the product_line of a product to also have the same brand as the product itself. For example: Brand A has 2 product_lines: Premium, Standard Brand B has 1 product_line: Platinum Suppose we have a product that belongs to brand B. I want to allow the product_line to be either null or Platinum, but not one of the product_lines that belong to Brand A (Premium or Standard) I'm not sure how to achieve this, or even if this should happen in serializers, at the model level, or somewhere else. Any help from seasoned django-ers would be much appreciated! -
Consequences of overriding __hash__ of Django models?
I have a quite complex potentially time-demanding system where Django model instances are stored and "indexed" (for the actual purpose of the system and for caching for perfomance during its execution) in sets and dicts. Thousands of CRUD operations are performed on those. Since these hashable instances are stored, this means the Django model __hashable__ method is run thousands of times: class Model(object): ... def __hash__(self): return hash(self._get_pk_val()) As efficient as this is, when called that many times, it does add up in time performance. When I use the model pk as dict keys or in sets the performance improvement is noticeable. Now, I cannot just replace all these instances with pks for practical terms, so I was thinking of overriding the method as follows in all pertinent models: def __hash__(self): return self._get_pk_val() Skipping the hash function overhead. What would be the implications and consequences of this change? Since we know the pk is unique, wouldn't this serve the same purpose in terms of indexing? Why does Django need to hash the pk? -
Add static_appname_ to file name in Django
I deploy my first app on heroku but when I download some pdf file from app their names look like static_nameapp_namefile.pdf Help me to resolve this problem