Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
DRF: Update a specific field with a GET instead of a PATCH
Context For a specific use case I need to be able to update a single field of my Visitor model using a GET request instead of a PATCH request. My relevant Visitor model looks like this: # models.py class Visitor(models.Model): visitor_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customers = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_visitors') audiences = models.ManyToManyField(Audience, related_name='audience_visitors') cid = models.CharField(max_length=255, unique=True) uid = models.CharField(max_length=255) cup = JSONField(null=True) def __str__(self): return self.cid class Meta: db_table = 'visitor' I am using a straightforward serializer like this: # serializers.py class VisitorSerializer(serializers.ModelSerializer): class Meta: model = Visitor fields = ('customers', 'cid', 'uid', 'cup') I am able to update just the cup field for a specific Visitor which is looked up using the unique cid field with a PATCH like this: # views.py class VisitorViewSet(viewsets.ModelViewSet): serializer_class = VisitorSerializer queryset = Visitor.objects.all() lookup_field = 'cid' def list(self, request, *args, **kwargs): instance = self.get_object() serializer = self.serializer_class(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Problem The problem is that I am unable to update the cup field of a Visitor based on a given unique cid field using a GET request. What I tried As this answer by Uri Shalit suggested, I tried to override get_serializer() inside my VisitorViewSet and … -
APNS Private Key + Django Backend
I'm using a django backend to send push notifications to my iOS app. One method of loading in the APNS certificate is as an environment variable with the contents of the .pem file. However, I'm noticing that my certificate contains BOTH the certificate section, and the private key section. Is this correct? Or should the private key section be stripped out? -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ... -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- -
how to show the created and updated date in django admin?
Is it possible to access the created date and updated date from django admin page ? I don't have these fields specified in the model. -
Not able to load static files in django template
I am learning django through this tutorial. The tutorial is kind of old but most of the code is the same. I tried adding some CSS files to the project just like the tutorial but for some reason, it is not working for me. here is my file structure... src ├── assets │ └── css │ ├── base_styles.css │ └── index_styles.css ├── core │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ ├── views.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── test_app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── templates │ │ └── test_app │ │ └── test_app_home.html │ ├── tests.py │ ├── urls.py │ └── views.py └── templates ├── aboutpage.html ├── base.html └── homepage.html Please note that src is the root folder. core is the name … -
Python DRF serializers custom errors
I just learn python and DRF for my project. currently I'm making some API for my mobile app. This is my plan API call response format for operation success: { "status" : 1, "message" : "success", "result" : { } } and for operation failed: { "status" : 0, "message" : "failed" "errors" : [ { "code":10001, "description":"invalid email format" } ] } I'm using serializers right now for validate the data. but serializers have they own error format. for raise ValidationError, i change it with my custom validation error handler so it will give 200 status code. class custom_ValidationError(APIException): status_code = 200 And this is what I'm doing right now with my view and serializers @api_view(['POST']) def register_user(request): serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() result = {} data['status'] = 1 data['message'] = 'user registration success.' result['id'] = user.id result['username'] = user.username data['result'] = result else: data['status'] = 0 data['errors'] = serializer.errors return Response(data) class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','username','password','password2'] extra_kwargs = { 'password':{'write_only':True} } def save(self): user = User( email = self.validated_data['email'], username = self.validated_data['username'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise … -
Django. Reply for comments getting posted as comments. How to have the reply for comments?
Hey I am quite new to django, I have this function for comments and replies,the problem is I can't have the reply to comments instead it is getting posted as comments. How to have this replies under respective comments? Here is my model and functions. model class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, related_name='replies', blank=True, on_delete=models.CASCADE) content = models.TextField(max_length=1000) timestamp = models.DateTimeField(auto_now_add=True) views def comment_section(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, reply=None).order_by('-id') if request.POST: comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') #reply-section comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=post, user=request.user, content=content, reply=comment_qs) comment.save() else: comment_form = CommentForm() context = { 'post':post, 'comment_form':comment_form, 'comments': comments, } if request.is_ajax(): html = render_to_string('posts/comment_section.html', context, request=request) return JsonResponse({'form': html}) html <!-- Comment showing section --> <div class="main-comment-section"> <div class="container-fluid mt-2"> <div class="form-group row"> <!-- Comment Form --> <form class="comment-form" method="post" action="{% url 'posts:comment_section' post.slug %}"> {% csrf_token %} <div class="form-group"> <textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea> </div> <button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button> </form> <!-- Comment Form end --> </div> </div> {% if not post.comment_set.all %} <small>No comments to display</small> … -
Django ORM update with subquery
I have a model with 2 DateTime fields. I want to subtract start time and end time and update the duration column in seconds. Nearly 15000 records need to be updated at each request. I got below mentioned error operational error (1093, "You can't specify target table 'tq_trn_user_question' for update in FROM clause") class TqTrnUserQuestion(models.Model): question = models.ForeignKey(TqTrnQuestion, on_delete=models.CASCADE, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False, related_name="%(app_label)s_%(class)s_users") question_status = models.ForeignKey(TqCfgQuestionStatus, on_delete=models.CASCADE, null=False, blank=False) start_time = models.DateTimeField(null=True, blank=True) end_time = models.DateTimeField(null=True, blank=True) duration = models.IntegerField(null=False, blank=False) role = models.ForeignKey("CfgUserRole", on_delete=models.CASCADE, null=False, blank=False) pause_duration = models.IntegerField(default=0) park_duration = models.IntegerField(default=0) below is my ORM tq_user_question = cls.objects.filter(question__in=locked, end_time__isnull=True, question_status=TqCfgQuestionStatus.objects.get(question_status_id=10)) tq_user_question.update(end_time=end_time, duration=Subquery(cls.objects.filter(id=OuterRef('id')).annotate( diff_duration=TimeStampDiff(F('end_time'), F('start_time'), output_field=IntegerField()) ).values('diff_duration')[:1]), question_status = TqCfgQuestionStatus.objects.get(question_status_id=50), updated_by=user)