Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dj-rest-auth: get access_token/code for facebook social media authentication
I was trying to implement Social Media Authentication with Facebook using dj-rest-auth. I am following the instructions in the docs Where could I get the access_token/code that's mentioned in the docs when calling the API endpoint /dj-rest-auth/facebook/ (POST) Thank you -
Edit Validation Errors in Django
I have a registration form on my website. Im having trouble editing the errors when the registration form is filled out incorrectly. I have done this code in my forms.py but it also displays djangos regular validation error. class lageBruker(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] def clean_brukernavn(self): brukernavn = self.cleaned_data.get('username') bruker_qs = User.objects.filter(username = brukernavn) if bruker_qs.exists(): raise forms.ValidationError('Brukernavn allerede i bruk') return brukernavn def clean(self, *args, **kwargs): passord1 = self.cleaned_data.get('password1') passord2 = self.cleaned_data.get('password2') if passord1 != passord2: raise forms.ValidationError('Passordene må være like') return super(lageBruker, self).clean(*args, **kwargs) I there any way i can edit the validation error that django is throwing? -
ManyToMany Django show field in my template
I have a make in my model a manytomany relationships like this: from django.conf import settings from django.db import models class Company(models.Model): user = models.ManyToManyField( settings.AUTH_USER_MODEL, ) name = models.CharField(max_length=200) siret = models.CharField(max_length=200, blank=True) ape = models.CharField(max_length=200, blank=True) adresse = models.TextField(blank=True) cp = models.CharField(max_length=200, blank=True) ville = models.CharField(max_length=200, blank=True) code_cfast = models.CharField(max_length=200, blank=True) code_dolibarr = models.CharField(max_length=200, blank=True) marque_blanche = models.BooleanField(default=False) marque_blanche_couleur = models.CharField(max_length=200, blank=True) created_at = models.DateTimeField('date published') All is working fine on my Company View and template, i can access to the users of my company like this: {% render_field form.user type="select" class="selectpicker form-control show-tick" data-live-search="true" %} But i have create a User View and on my template i can retrieve the value in input like this: {% render_field form.groups type="select" class="form-control" %} But i want to have on my edit view of my user the same select when i have on my company edit. I have try: {% render_field form.company type="select" class="form-control" %} With no success. I use the default user model. An idea ? Sorry for my english i'm french. Thx. -
Django Import-export: Import CSV files errors
I`ve spent a few hours trying to debug this issue. I am trying to import a catalog of product into my app. I am using Django Import-export to import a csv file. I have tried to import it via the admin site and via a simple upload file. In both case, I am encountering some errors. Would you have an idea how to resolve them? 1st Method: Import the csv file via the admin site Error encountered: Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 13365: character maps to It looks like this method cannot accept some character(""). How can I change my code to accept any character? I`ve already removed the following characters: £, - and try to encode it in UTF-8. I have also done a search to remove every non ASCII characters(128-255) 2eme Method: Import the csv file via the website Error encountered: 'MultiValueDict' object is not callable views.py def simple_upload(request): if request.method == 'POST': file_format = request.POST.get('file-format') product_resource = ProductResource() dataset = Dataset() new_products = request.FILES['Price_List'] if file_format == 'CSV': imported_data = dataset.load(new_products.read().decode('utf-8'),format='csv') result = product_resource.import_data(dataset, dry_run=True) elif file_format == 'JSON': imported_data = dataset.load(new_products.read().decode('utf-8'),format='json') # Testing data import result = … -
Django OpenCV Exception Value: libSM.so.6: cannot open shared object file: No such file or directory
I am trying to deploy my simple OpenCV based app to Heroku. The app capture live stream only from webcam. My App worked well in the local environment while it gives the following error on Heroku platform. Exception Value: libSM.so.6: cannot open shared object file: No such file or directory How can I resolve it? -
How to check a condition in a DRF Serializer and then skip that iteration and go to the next
I have a serializer as follows: class CustomerSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() def get_product(self, obj): obj.product = Customer.check_is_product(obj.product_id) return obj.product.name class Meta: model = Customer fields = ['name', 'product'] and I have a models.py as follows: class Product(models.Model): name = models.IntegerField() class Meta: db_table = 'items' class Customer(models.Model): name = models.CharField(max_length=255) product_id = models.IntegerField() class Meta: db_table = 'items' @staticmethod def check_is_product(id) try: product_obj = Products.objects.get(id=id) except: <if product with that id isn't there, then i wanna skip that iteration in serializer> return product_obj Now imagine I have three customers in my Database, out of that, one customer doesn't have any product, then I wanna skip that entire customer's detail in my API response. So my final API response would have a list with only 2 items. Does anyone know how to skip an iteration of the serializer on any condition check? -
Using Django tenants on the same domain, rather than subdomains or multiple domains
If I am using django-tenant-schemas (or django-tenants fork), the way they appear to be set up is that you would access the tenants on a separate subdomain or separate domain. This means accessing tenant1 using tenant1.mysite.com or tenant1.com. However, I would like to access tenants using mysite.com/tenant1/, mysite.com/tenant2/. This is because I am using DRF, and so I just want their information stored separately. And I want to access them via the API in the same way. So, for instance I can make calls to mysite.com/tenant1/api/token/. How would I set this up? -
Circumventing F expression problem of django-simple-history by overriding save
Django-simple-history is inserting new record on each save of target model. In docs the problem with F expressions is described. I try to circumvent this with overriden save method. def save(self, *args, **kwargs): super().save(*args, **kwargs) # some other actions self.refresh_from_db() But it seems, that this is not working. Is the post_save signal of base model called directly after super().save() call? If so, is there a way to solve this problem keeping the F expression in target model update? -
Django - testing model with ManyToMany field
I'm just starting out writing tests (yes, I know!!!) for a django app I've been writing (A library). I've got a Title model which has authors as a ManyToMany field (as a book can have more than one author). This works fine in the app - I create a new title, save it, and then I can set the authors using title.authors.set([author]) - a pattern which I have used in several places and works OK (I appreciate you can't set a many to many relationship until the item in question has an id, so it's saved before and after this line. I'm trying to set this up in a test (this is my first hour or so of trying to do testing with django, so please bear this in mind if I'm doing anything stupid) - and I've got the following to set up the title and author, but I can't find any way of adding the author to the test title: class TitleModelTests(TestCase): def setUp(self): Author.objects.create(first_name="Darren", last_name="Jones") title_author = Author.objects.get(id=1) t1 = Title(title="Book One") t1.save() t1.authors.set([title_author]) t1.save() def tearDown(self): pass def test_for_title_creation(self): title = Title.objects.get(id=1) self.assertEqual(title.media, "pbk") def test_for_title_author(self): title = Title.objects.get(id=1) title_author = Author.objects.get(id=1) self.assertEqual(title.authors, title_author) I can't … -
Image won't load from admin django
I can't seem to load the image from the admin to my view page. Can anyone help me? Models.py template urls.py(app url) views.jpg main urls.py -
Uncaught RangeError: Maximum call stack size exceeded at buildParams
I can't find where is mistake. please help When I submit form I get below error in console Uncaught RangeError: Maximum call stack size exceeded at buildParams I saw different answers but they didn't help me to find error Jquery <script type="text/javascript"> var frm = $('#message-form'); frm.on('submit',function(e){ e.preventDefault(); $.ajax({ type: frm.attr("method"), url: "message/message_form/", dataType: 'json', data: { csrfmiddlewaretoken: "{{ csrf_token }}", frm:frm}, }) .done(function(response){ console.log(response.message) }); }); </script> HTML <div class="fixed-bottom"> <form id="message-form" user_id="{{u.id}}" method="POST"> <input type="hidden" id="user_id" name="user_id" value="{{u.id}}"> {% csrf_token %} <div class="container"> <div class="row"> <div id="text" class="col-10"> {{ msgform.text }} </div> <div class="col-1"> <button id="submit" class="btn" type="submit"><img height="30px" src="/static/img/send-button.png" alt="send"></button> </div> </div> </div><br> </form> </div> Thanx in advanced -
Postman making JWT token request fails
I have a DRF API I'm trying to test it using postman. But I keep failing at accessing the view. I'm generating a token. But I can't figure out how the request with the token should look like. This request returns this Django error: -
How to subtract two annotated field from different table in django?
I am just trying to subtract two fields from different tables but no success till now My model py class partdetail(models.Model): partnumber = models.CharField("Part Number",max_length=10) partweight =models.FloatField("Weight") partprice =models.FloatField("Price") partfdy =models.CharField("Foundry",max_length=10,choices = foundry_choices) def __str__(self): return self.partnumber class incomingdetail(models.Model): partnumber = models.ForeignKey(partdetail,on_delete=models.PROTECT) indate =models. DateField("Date") inqty=models.IntegerField("Quantity") class outgoingdetail(models.Model): partnumber = models.ForeignKey(partdetail,on_delete=models.PROTECT) outdate =models. DateField("Date") dcnumber= models.IntegerField("DC number") outqty=models.IntegerField("Quantity") and here is my views py def home(request): a=incomingdetail.objects.values('partnumber__partnumber').annotate(Sum("inqty")) # for incoming table data b=outgoingdetail.objects.values('partnumber__partnumber').annotate(Sum("outqty")) # for outgoing table data tests =list(chain(a,b)) # used to join both the queries return render(request,"portalone/Home.html",{'totalincome':tests}) I want to subtract inqty from incomingdetail and outqty from outgoingdetail to be subtracted according to the partnumber and group by partnumber for now i have achieved to show two queries in single table by joining them but cant able to subtract the values from two values -
django page not found - The current path, users/login/, didn't match any of these
New to Django, doing a tutorial from the Python crashcourse book. I run into an error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/users/login/?next=/topics/ Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='index'] topics/ [name='topics'] topics/<int:topic_id>/ [name='topic'] new_topic/ [name='new_topic'] new_entry/<int:topic_id>/ [name='new_entry'] edit_entry/<int:entry_id>/ [name='edit_entry'] login/ [name='login'] logout/ [name='logout'] register/ [name='register'] login/ The current path, users/login/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I have tried the solutions to the similar questions. Without any success. Thanks in advance for having a look at it:) Basically what happens: I add the code @login_required to the topics function in the views file for the learning_logs app. Which should redirect to a login page when user is not logged in. However I get the above mentioned error. My users\urls file """Defines URL patterns for users""" from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns = [ # Login page. path('login/',auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), # Logout page path('logout/', auth_views.LogoutView.as_view(), name='logout'), # Registration page. path('register/', views.register, … -
Google map directions from csv - Javascript
I'm a newbie in python and I have zero knowledge in javascript, but I'm trying to plot a map using google maps API from a local csv. Let's say the csv looks like this (sorry, I only know how to reproduce in python): import pandas as pd df = pd.DataFrame({'lat':[52.35500,52.40242,52.55827,52.55139,52.56262], 'long':[-8.68400,-8.51132,-8.27802,-8.24667,-8.26170], 'name':['name1','name2','name3','name4','name5',]}) I am using directions to map routes with waypoints as suggested in this answer, but in my case: {% load static %} <!-- sources: https://speckyboy.com/slide-out-sidebars/ --> <!DOCTYPE HTML> <html lang="en"> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <title>CALCULATED ROUTE</title> <link rel="stylesheet" href="{% static 'css/map2_style.css' %}"> <script> function initMap() { var service = new google.maps.DirectionsService; var map = new google.maps.Map(document.getElementById('map')); // list of points var stations = [ { lat: 52.35500, lng: -8.68400, name: 'Station 1' }, { lat: 52.40242, lng: -8.51132, name: 'Station 2' }, { lat: 52.55827, lng: -8.27802, name: 'Station 3' }, { lat: 52.55139, lng: -8.24667, name: 'Station 4' }, { lat: 52.56262, lng: -8.26170, name: 'Station 5' }, // ... as many other stations as you need ]; // rest of the script omitted for brevity (please see the referenced source if relevant) // source: https://stackoverflow.com/questions/22038388/google-map-direction-services-waypoints-more-than-50 My question is: how can I load my csv … -
get email from User model
i am beginner in django and i am facing a problem that is "i want to that user can not be signup again with same email id and also username" views.py def register(request): if request.method == 'POST': user=request.POST['username'] email=request.POST['email'] password1=request.POST['password1'] password2=request.POST['password2'] if password1==password2: try: User.objects.get(username=user) User.objects.get(email=email) return render(request,"register.html",{'msg':'Please Signup with other Credentials'}) except User.DoesNotExist: user=User.objects.create_user(username=user,password=password1,email=email) auth.login(request,user) return redirect('/') else: return render(request,"register.html",{'msg':'Password doesn\'t matched'}) else: return render(request,"register.html") -
Why do I get a page not found 404 error when I ran my code with a app? It worked fine without an app
When I made my django project using Django(version 1.9.1) and Python (version 3.6.3), a 404 error came. Code follows. Error Message : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, music, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Main URL file : from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] App urls file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] "Views" file for the app : from django.http import HttpResponse def index(request): return HttpResponse("<h1> This is the Music Section of the page </h1>") -
Django Dynamically serving static files.(Chunk Load error )
I have a Django + React project running at localHost:8000. VIEWS.PY def index(request): return render(request, 'frontend/index.html') INDEX.HTML {% load static %} <script src="{% static "frontend/main.js" %}"></script> When user click a button in main.js file, it request for 0.bundle.js to server, but server fails to serve it. I can't do loading manually (<script src="{% static "frontend/0.main.js" %}"></script> This scripts load the 0.bundle.js but I want dynamic import). As you can see in attached image, the frontend JS file requesting file at rootLocalhost. Any ideas or directions will be appreciated . -
When I run python manage.py makemigration following error
[django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)") windows10 mysql django python 3.8 ]1 -
Override Django Return
I need to override several views in a third party django app to add functionality. The only way I could find to do this is the following (rather hacky) method: (django-notifications app) urls.py url('^inbox/notifications/', include(notifications.urls, namespace='notifications')), # used for overridden notification views url('^inbox/notifications/', include('notifications_extension.urls')), notifications_extension urls.py # overrides some notifications views for url in urlpatterns: if url.name == 'all': url.callback = CustomAllNotificationsList.as_view() notifications_extension views.py # overrides AllNotificationsList, marking all users notifications as read class CustomAllNotificationsList(AllNotificationsList): def get_queryset(self): qset = self.request.user.notifications.all() for notification in qset: notification.mark_as_read() return super(CustomAllNotificationsList, self).get_queryset() Whenever AllNotificationsList is called the overridden function is used, then super is called. This works fine for some things, however I now want to change the 'return redirect' of a function. The problem is that I cannot just add my functionality then call 'super', as obviously the 'return redirect' is the last thing that will be ran. The only way I can think to do this is by copy/pasting the entire function into my overridden one (not good). Any other suggestions would be greatly appreciated. Thank you. -
Any idea to create the price table which associate with date in Django(Python)
I would like to create a price table by date, I tried to google this for python and django, but still have no idea for this. I don't want to create one to one relationship object like an options. but I would like to create the database associating date and price. Sorry that it may be simple question.. Would it be solution to create a database by using PostgreSQL, and read by django? or any resource / reference can help get me in right direction to access this problem? Thanks so much -
Having Difficulty Creating A News Website With django using A Title Inside Images As Headlines and as Breaking News and slideshow category
I have created a news website and I can post news from all category with a most read. But am having a challenge Because I don't want my category to appear first. No! I want my latest News title textto appear inside my image And I want all my first 10 post to appear as headlines too automatically with a simple News title alone and I want my category to appear after the breaking News and the headline. Below is my code from my views. Py, models.py and some of my template code enter image description here -
Django-Channels AsyncConsumer not working Code 500 with correct setup
I'm new to Django & socket programming. My client is unable to connect to my Consumer, the following code works perfectly for WebsocketConsumer but as soon as I try to make it async it fails with Response Code:500. I can't seem to figure out why the following code is not working. Any help is greatly appreciated ERROR (index):18 WebSocket connection to 'ws://127.0.0.1:8000/ws/test-view/' failed: Error during WebSocket handshake: Unexpected response code: 500 Client(JavaScript) var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname + '/' console.log(endpoint) var socket = new WebSocket("ws://127.0.0.1:8000/ws/test-view/") socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("open", e) } socket.onerror = function(e){ console.log("error", e) } socket.onclose = function(e){ console.log("close", e) } Consumer import json from asgiref.sync import async_to_sync from channels.generic.websocket import AsyncWebsocketConsumer from apps.core.constants import SOCKET_KEY_PROFILE class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.room_group_name = "notif_room_"+str(self.user.id) await async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) print(self.room_group_name) await self.accept() print("#######CONNECTED############") async def disconnect(self, code): await async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) print("DISCONNECTED CODE: ", code) Routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( [ url(r'^ws/test-view', consumers.NotificationConsumer), ] ) ), }) -
Alternative render of JSON response in Django depending on request origination
I'm trying to find a way how to return JsonResponse which would be either interpreted as JSON when received by Ajax success function, or will be rendered to 404 (or any other page) if will be called directly via URL. The reason I'm looking for this is because on my website I have few places where I am using empty modal view (pop-up) which is later populated with proper HTML content by server based on Ajax request. In return JSON to my Ajax success function I have only HTML responsible for the modal content. So, when displayed as standalone (by typing GET request url directly in browser) it is JSON object. What I'd like to achieve is display some page in such case (directly typed url for GET request), which will inform user that he's in wrong place, but at the same time will be properly understood by Ajax. So far I've considered two approaches: Use POST request - this is ok, until I need to render form in modal which is then sent back, also as a POST request, to server to be somehow processed. It requires some ugly workarounds to figure out if request is to render form … -
Run Colab script from python file
For a project, I need to run a Google Colab script with a python file. It's a web project, when someone send a file on a django app, the file will be upload and use in the colab script. I can't let the script run in background.