Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create custom user model for different user types using django rest framework
I am new to django rest framework and I want to create different types of users "I think it should be 4", (students, teachers, staff and admin) And I want the staff user to register the teacher and student users. I want to use custom user model and use email to register and login, can it be done, please help, I have been looking for days for anything that can help me to understand how to do it -
Django - redirect to the page i was before
I'd like to know if there is a way to redirect the user to the page he was on before way the click a "Go back" button. Because for now i used redirect or reverse_lazy to send them to a specific view when they click the button, but i'd like them to go to the page they were on before. -
403 Forbidden while making ajax request to endpoint in Django
I have this endpoint to which I am making a post request from console using AJAX, its not a web page from which I am making this request. $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/browse/", data: {csrfmiddlewaretoken: window.CSRF_TOKEN}, success: function() { console.log("Success!"); } }) But its giving me VM29 jquery.min.js:2 POST http://127.0.0.1:8000/browse/ 403 (Forbidden) The Django views code is doing nothing but returning dummy data def Browse(request): data = [{'name': 'Peter', 'email': 'peter@example.org'}, {'name': 'Julia', 'email': 'julia@example.org'}] return JsonResponse(data, safe=False) urls.py urlpatterns = [ path('browse/', views.Browse, name = 'browse'), -
Module in django
this error comes to me when i try to makemigrations in cmd: ModuleNotFoundError: No module named 'homsapp.app' virtualenv_name: repro project_name: homspro app_name:homsapp models.py: from django.db import models class location(models.Module): location_name=models.CharField(max_length=200) location_type=models.CharField(max_length=200) class propertyview(models.Model): location = models.ForeignKey(location,on_delete=models.CASCADE) property_name = models.CharField(max_length=200) property_area=models.CharField(max_length=200) installed _apps in setting.py: INSTALLED_APPS = [ 'homsapp.app.HomsappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
How to create a database with Django?
Django wants an existing database, which you configure in settings. But how can I create a second database? I will use PostgreSQL. -
How can i have multiple or queries in one querie in django's ORM
results=Post.objects.filter(Q(Q(title__istartswith=searchqueries)) | Q(title__icontains=' '+searchqueries)) | Q(Q(content__istartswith=searchqueries)) | Q(content__icontains=' '+searchqueries))) I am Trying to have this i am getting invalid syntax error i want to have 4 or queries in one query -
Face recognition using django
So I have created a Django form but wanted to add face recognition to it such that when a button is clicked, the webcam will switch on and a photo will be clicked that will be stored with the form and when a person logs in can do it through face ID, however, I am not sure how to add that functionality to the button as I would need JS and my face recognition code is in python. -
How To Receive Real Time Latitude and Longitude In Django and DRF
I am trying to make an endpoints where by I can get the longitude and latitude of a User(Rider) in Real Time and save it to my Database. I have tried Researching about how to go about this, but I have only been able to get How to receive the current location which isn't in real-time as I want. I would be glad if anyone could directs me on how to go about this and provide some materials where i could read more about how to achieve this or a past work on this. Thanks in anticipation. -
Resolving pip error when installing django-allauth
So i tried installing the django-allauth package in a virtualenv and i keep getting this error WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))': /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))': /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))': /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))': /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))': /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz ERROR: Could not install packages due to an EnvironmentError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/ae/90/419273d26361bcdf016d8595ada9ad8a0d2fe2871783bf575df1d9911dce/django-allauth-0.13.0.tar.gz (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate is not yet valid (_ssl.c:1076)'))) Please how do i resolve this error? -
Get models in Django that have exactly all the items in ManyToMany field (no reverse lookups allowed)
I have such a model in Django: class VariantTag(models.Model): saved_variants = models.ManyToManyField('SavedVariant') I need to get all VariantTag models that have saved_variants ManyToMany field with exact ids, say (250, 251), no more, no less. By the nature of the code that I am dealing with there is no way I can do reverse lookup with _set. So, I am looking for a query (or several queries + additional python code filtering) that will get me there but in such a way: query = Q(...) tag_queryset = VariantTag.objects.filter(query) How is it possible to achieve? -
Field error in creating an edit profile page in django
I'm having trouble creating an edit profile page (where users can edit their info such as name and birth date) in django the error returned is: django.core.exceptions.FieldError: Unknown field(s) (password1, birth_date, password2) specified for User Project Name: AET App Name: AnimeX (A Placeholder for now) if you want any other information leave a comment models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() from django.core.exceptions import ObjectDoesNotExist @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance) forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = User fields = ('username', 'birth_date', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class EditProfileForm(UserChangeForm): class Meta: model = User fields = ('username', 'birth_date', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from … -
Attribute Error though attribute is assigned
from channels.generic.websockets import WebsocketDemultiplexer,WebsocketConsumer from .models import TwilioCallBinding from google.cloud import speech_v1p1beta1 as speech from google.cloud.speech_v1 import enums,types import json import base64 from .SpeechClientBridge import SpeechClientBridge class MediaStreamConsumer(WebsocketConsumer): config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.MULAW, sample_rate_hertz=8000, language_code='en-US' ) streaming_config = types.StreamingRecognitionConfig(config=config,interim_results=True) def on_transcription_response(response): if not response.results: return result = response.results[0] if not result.alternatives: return transcription = result.alternatives[0].transcript print("Transcription: " + transcription) def connect(self, message, **kwargs): self.message.reply_channel.send({"accept": True}) self.bridge = SpeechClientBridge(MediaStreamConsumer.streaming_config, MediaStreamConsumer.on_transcription_response) def raw_receive(self, message, **kwargs): data = json.loads(message['text']) if data["event"] in ("connected", "start"): print(f"Media WS: Received event '{data['event']}': {message}") if data["event"] == "media": media = data["media"] chunk = base64.b64decode(media["payload"]) self.bridge.add_request(chunk) if data["event"] == "stop": print(f"Media WS: Received event 'stop': {message}") print("Stopping...") def disconnect(self, message, **kwargs): self.bridge.terminate() I am getting same error on message receive as well as disconnect event AttributeError: 'MediaStreamConsumer' object has no attribute 'bridge' I have assigned bridge attribute in connect event def connect(self, message, **kwargs): self.message.reply_channel.send({"accept": True}) self.bridge = SpeechClientBridge(MediaStreamConsumer.streaming_config, MediaStreamConsumer.on_transcription_response) then why i am getting AttributeError P.S: Pardon me i am not good at OOP that's why if i am missing any implementation,please guide me. -
Django ecomemrce error: List index out of range
I'm getting an error with this code: views.py def cart_view(request): template_name = 'cart/carts.html' user = request.user carts = Cart.objects.filter(user=user) orders = Order.objects.filter(user=user, ordered=False) if carts.exists(): order = orders[0] return render(request, template_name, {"carts": carts, 'order': order}) else: messages.warning(request, "You do not have an active order") return redirect("products:home") How to fix this ? -
Unknown column 'site_id' in 'field list' when listing new list items
I have a cage I want to add. I have this list with information about this cage, but want to add two more items; site and company. Where I want to add "site" and "company" In when adding cages it is possible to choose company and site with ForeignKey, as you see in models.py code here: class Cage(models.Model): external_id = models.CharField(max_length=200, null=False) name = models.CharField(max_length=200, null=False) site = models.ForeignKey( Site, null=True, on_delete=models.PROTECT ) company = models.ForeignKey( Company, null=True, on_delete=models.PROTECT, ) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name My admin.py code looks like this: class CageAdmin(admin.ModelAdmin): list_display = ('id', 'external_id', 'name', 'drone_match', 'latitude', 'longitude') def drone_match(self, obj): drone_cages = DroneCage.objects.filter(cage_id=obj.id) link = '' if len(drone_cages) > 1: link = 'multiple drones' elif len(drone_cages) == 1: drone = Drone.objects.filter(id=drone_cages[0].drone_id)[0] link = format_html('<a href="{}">{}</a>'.format( reverse('admin:baleen_drone_change', args=(drone.id, )), drone.serial )) return link drone_match.short_description = 'Current Drone' and when I add site and company in list_display like this: list_display = ('id', 'external_id', 'name', 'site', 'company', 'drone_match', 'latitude', 'longitude') I get the following error: Unknown column 'site_id' in 'field list' when listing new list items. I can't figure out why site and company do not … -
Running into 404 error with URL Dispatcher
This is my path path('page_ojects', views.page_objects, name = 'page_objects') this is my form <form action="{% url 'page_objects' %}" method="post" enctype="multipart/form-data"> This is the name of my function in views def page_objects(request): I am getting 404 error saying Using the URLconf defined in WebFetcher.urls, Django tried these URL patterns, in this order: [name='home'] page_ojects [name='page_objects'] admin/ ^media/(?P.*)$ The current path, WebFetcher/page_ojects, didn't match any of these. I ready all the documentation on the URL Dispatcher and I could not find anything that looks wrong with my code. I hope it is just a syntax error. If you think more of my code will be helpful, comment and I will edit this post. -
mailchimp integration with django
i am trying to integrate mailchimp to my django site so that when users register they will receive a customized email that is already set on mailchimp. i don't know what to do please help. Thanks in advance. -
ValueError at / The 'photo' attribute has no file associated with it
THE PROBLEM : I want to upload the images of my product file onto server. But when i am passing the file URL which is <{{product.photo.url}}>in my html file it is displaying value error: photo attribute has no files associated with it. My python and html file code below: product.py file: from django.db import models from django.db.models import ImageField from .category import Category class Product(models.Model): name = models.CharField(max_length=500) description = models.CharField(max_length=200, blank=True, null=True) photo = models.ImageField(upload_to='uploads/product/', blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) manufacturer = models.CharField(max_length=300, blank=True) price = models.IntegerField(default=0) @staticmethod def get_all_products(): return Product.objects.all() In the above code for Imagefield i have passed the 'photo' variable but then too the server is displaying error. urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Index.html code: <body> <div.<div class="container-fluid"> <div class="row mx-auto"> {% for product in products %} <div class="card mx-auto mb-3 mt-3" style="width: 18rem;"> <img src="{{product.photo.url}}" class="card-img-top" alt="..."> <div class="card-body"> <p class="card-title"><b>{{product.name}}</b></p> <p class="card-text"><b>{{product.price}}</b> <a href="#" class="btn btn-light border btn-md">Add To Cart</a> </div> </div> {% endfor %} </div> </div> The confusing thing is when i am passing the code {{product.image.url}} … -
Django Geos MultiPolygon contains circle
In Django, using Geos, I want to check if a circle intersects with a Multipolygon. My PointOfInterest model contains an areas MultiPolygonField, and I have tried: poi.areas.contains(Point(longitude, latitude, srid=4326)) Works fine, but we query only a point in the area poi.areas.contains(Point(longitude, latitude, srid=4326).buffer(radius)) No matching even if the circle is in the area poi.areas.buffer(radius).contains(Point(longitude, latitude, srid=4326)) Matches with all points even if with radius, they are not on the area. Do you have any idea on how to correctly find if an area (of the poi) intersects with a circle (point with radius)? -
Django Hidden cached duplicates entries, .filter() return 2 objects when .get() return one
I'm working on a quizz system , it's dev time so threre is a lot of changes on models and database imports and I have a strange problem for some time with duplicates entries. For example I've got two answers to a question for a member except of One. .get() returns one entry but .filter() returns 2 entries, I can iterate throught it, len() and count() are not equals, so it maybe a cache problem, here are some details. class Member(models.Model): name.. class MyExam(models.Model): name... class Question(models.Model): name... class Answer(models.Model): name... question = models.ForeignKey(Question,related_name="question_answers",...) class Meta: #UniqueConstraint(fields=['member_id', 'question_id', 'my_exam_id'], name='uniqu...') # get answer = Answer.objects.get(id=1) # returns one object without errors # filter answers = Answer.objects.filter(id=1) returns 2 objects answers.count() # returns 1 len(answers) # returns 2 answers.count() # returns 2 # filter distinct answers_distinct = Answer.objects.filter(id=1).distinct() # returns 2 object # filter distinct id answers_distinct_id = Answer.objects.filter(id=1).order_by('id').distinct('id') # returns 1 object It seems that count is working but len and queries are not, like if entries are duplicates in cache only, not in database. SELECT * FROM Answer WHERE id = 10; # return 1 line; SELECT * FROM Answer WHERE id IN (10); # return 1 line; I … -
Align two elements left y right in td with xhtml2pdf
How can I align two elements within a td in xhtml2pdf? I want to separate the symbol from the amount. enter image description here I tried the following but it doesn't work. Align two spans inside a td - One left and one right -
How to re-send changed data in django?
I made a POST method to send data from form, recive it with views.py . Now i want to do some changes(ex. calculate variance) on that data and then send it again to display it on my page. I tried using JsonResponse in django and $getJson in javascript but it crashes. I would really appreciate some help. views.py def valid(request): if request.is_ajax(): request_data = request.POST.getlist("invest")[0] print(request_data) return JsonResponse(request_data, safe=False) script.js function ajaxdata(){ let invest = document.getElementById('investment').value; $.ajax({ method:'POST', url:'/valid/', data: { 'invest': invest, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data){ alert("works"); }, error: function(data){ alert("doesn't work") } }); }; -
NoReverseMatch on Heroku Live Server
So I just launched my Django web app using Heroku. On the live server, when I try to view my cart or add a product to my cart...I get this error: Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/$'] However, I am able to successfully view and add to my cart on my local host. I will post my code below for reference. cart/templates/detail.html <form action="{% url "cart:cart_add" product.id %}" method="post" style="align-self: center"> {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.override }} <input class="btn btn-elegant btn-sm" type="submit" value="Update" style="margin-top: 20px"> {% csrf_token %} </form> cart/cart.py: class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): """ Count all items in the cart. """ … -
for this function based view i want class based view
and not able to filter with ( type=categ ), so used condition urls.py path('post/<str:categ>', category_list, name='category'), views.py def category_list(request, categ): context = {} if categ == 'first' or categ == 'First': context['category'] = Article.objects.filter(type="1") elif categ == 'second' or categ == 'Second': context['category'] = Article.objects.filter(type="2") elif categ == 'third' or categ == 'Third': context['category'] = Article.objects.filter(type="3") return render(request, 'category.html', context) Choices in model field in model type = models.CharField(choices=my_choice, max_length=10, default=False) these are choices my_choice= ("1", "first"), ("2", "second"), ("3", "three"), ("4", "four"), ("5", "five"), ("6", "six"), -
Dynamic asset database design - Postgres vs MongoDB, using Django
I'm currently designing a dynamic asset management system. Users can create their own Asset using a form builder. Currently, once the form is built I create a new table called "Asset_{name}". This works quite well but the issue I see is, over time, there will be quite a lot of tables called "Asset_...". My knowledge of database design is quite short, so the question is: should I continue on this path or will switching to a NoSQL solution (such as MongoDB) be more beneficial, and if so, why? -
How do I use Django subqueries?
How do I use this subquery in Django ORM? select id, name, price from book where price > (select avg(price) from book); I tried this and got an error. Book.objects.filter(price__gt=Subquery(Book.objects.aggregate(Avg('price')))).values('id', 'name', 'price') AttributeError: 'dict' object has no attribute 'query'