Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have a problem in integration between djangp-oscar and paypal
i am trying to integrate paypal with oscar-django when i installed Django-Oscar-Paypal it gives me that error ModuleNotFoundError: No module named 'oscar.apps.communication' -
Error when adding multiple paths in django
When I add mulitple path in my code, it gives error. Code views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello Nikhil") def about(request): return HttpResponse("About Nikhil") urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index') path('about',views.about,name='about') #error:Above line is giving error ] when I run the code for 1 path,it does not give any error, but when multiple path is added it givens error -
djnoer gives TypeError: permission_denied() got an unexpected keyword argument 'code' on get request on /users/me/
Doing just a get request on auth/users/me/ results in this error which says the above. Couldn't find anything that helps. Can you help me figure out where this error is coming from and how can I fix it. The link to the tutorial I was following is below. Just had setup a new project and installed djoner with jwt. Below is a detailed error message Djoner link https://djoser.readthedocs.io/en/latest/sample_usage.html Internal Server Error: /auth/users/me/ Traceback (most recent call last): File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/prashant/project/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 415, in initial self.check_permissions(request) File "/home/prashant/project/env/lib/python3.8/site-packages/rest_framework/views.py", line 333, in check_permissions self.permission_denied( TypeError: permission_denied() got an unexpected keyword argument 'code' [28/Oct/2020 17:40:20] "GET /auth/users/me/ HTTP/1.1" 500 16964 settings.py # SECURITY WARNING: don't run with debug turned on in production! … -
I have an excel file in my django models how can i import it in my views.py so that i can perform some pandas operations
from django.db import models class File(models.Model): file = models.FileField(blank=False, null=False) def __str__(self): return self.file. this is my modesl through which I upload excel file into my admin models now how can I make query to use this excel file in my views.py class TaskView(viewsets.ModelViewSet): file_obj = File.objects.all().order_by('-id')[0] data_1 = pd.read_excel(file_obj) data_1 = data_1.dropna() I want to create a function in my views.py which get excel file from models database and I can perform pandas operation on this -
How to feed information from one webpage into a view django
So, it has been two days now of searching StackOverflow for an answer, but I can't seem to find one that fits my question. Mainly, I think this question stems from a lack of understanding of how URLs pass information to views. What I want is when a user clicks on the pdf link, the application should grab the client's name, zip code, and city and feed that information into a pdf. (pdf is kind of auxiliary, I am mainly just trying to figure out how to extract information from one page and feed it into a view). Note: I wish I could imbed a picture here, but can't without a reputation of 10. You will get a great idea of what I am trying to accomplish by the picture. click here to see my demo client page Below is my best attempt on how I can see this working, but I obviously don't know how to actually do it. #client_detail.html {% extends "base_generic.html" %} {% block content %} <h1>Client: {{ compuweatherclient.client }}</h1> <p><strong>City:</strong> {{ compuweatherclient.city }}</p> <p><strong>State:</strong> {{ compuweatherclient.state }}</p> <p><strong>Zipcode:</strong> {{ compuweatherclient.zipcode }}</p> <a href="{% url 'catalog:renderpdf' %}">PDF</a> <!--<a href="{% url 'catalog:renderpdf' var1=compuweatherclient.client %}" ><button class="btn btn-primary">pdf</button></a>--> {% … -
sendgrid-django 4.2.0 do not work with django 1.11
My env: Django: 1.11.29 Python: 2.7.18 sendgrid-django: 4.2.0 I changed settings: EMAIL_BACKEND = "sgbackend.SendGridBackend" SENDGRID_API_KEY = 'api key' And used a code sample from the example: mail = EmailMultiAlternatives( subject="Your Subject", body="This is a simple text email body.", from_email="company <noreply@company.co>", to=["myemail@gmail.com"], ) mail.template_id = '6b02f312-ad80-4d7e-815a-24be029fd05b' mail.substitutions = { '%email%': 'some email', '%location_city%': 'some city', } mail.send() There are no errors, by email is not coming. I also tried to send it without template_id, and mail is coming: mail = EmailMultiAlternatives( subject="Your Subject", body="This is a simple text email body.", from_email="company <noreply@company.co>", to=["myemail@gmail.com"], ) # mail.template_id = '6b02f312-ad80-4d7e-815a-24be029fd05b' mail.substitutions = { '%email%': 'some email', '%location_city%': 'some city', } mail.send() -
How do I get a constant column in a Django ORM?
I am studying ORM. However, there are some things I don't understand even after reading the documentation. How do I get a constant column in a Django ORM? select *, 'a' as a from book; This is the query set I tried Book.objects.annotate(a=Value('a')) -
Djang default value field is not working while inserting through pymongo
I Created a Django Model name Student in which attendance field is by default True. But when I insert the value in Student, attendance field is not created. My Django Model is: class Students(models.Model): firstName=models.CharField(max_length=100, blank=True, null=True) lastName=models.CharField(max_length=100, blank=True, null=True) attendance=models.BooleanField(default=True, db_index=True) I am using mongodb as my database, when i am inserting in Students collection. data={"firstName":"python","lastName"="django"} collection.insert_one(data) But when i am fetching the data i am not getting attendance field. I was expecting that attendance field will be automatically created with default value as True -
Django channels - missing 2 required positional arguments: 'receive' and 'send'
I just got started to Django Channels and i created a very basic consumer which does nothing for now. The problem is that i keep getting the following error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\daphne\http_protocol.py", line 163, in process self.application_queue = yield maybeDeferred( TypeError: __call__() missing 2 required positional arguments: 'receive' and 'send' Here is the consumer: import json from channels.generic.websocket import WebsocketConsumer class TestConsumer(WebsocketConsumer): def websocket_connect(self, event): self.send({ 'type': 'websocket.accept' }) print('CONNECTED') def websocket_receive(self, event): #print(event['text']) dataset = event['text'] print(dataset) #print('Received') def websocket_disconnect(self, event): print('DISCONNECTED!') And here is my route: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/main/', consumers.TestConsumer), ] What am i doing wrong? -
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.