Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changes in views.py doesnt appear in my browser unless I stop the server
When I make any changes in views.py it doesnt appear in my browser unless I restart the server. Even CTRL + F5 and SHIFT+CTRL+R doesnt work . Does this happen for a reason? -
Curl POST file upload for django FileField
I have this model which has models.FileField and I have confirmed file upload works on Django rest framework web UI (viewsets.ModelViewSet) class MyFile(models.Model): name = models.CharField(verbose_name='NAME', max_length=30) file = models.FileField(upload_to='file/%Y/%m/%d') created_at = models.DateTimeField( auto_now_add=True) class MyFileSerializer(serializers.Serializer): name = serializers.CharField() file = serializers.FileField(required=False) def create(self, validated_data): return MyFile.objects.create(**validated_data) class MyFileViewSet(viewsets.ModelViewSet): queryset = MyFile.objects.all() serializer_class = MyFileSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) then I try to upload the file from curl. curl -X POST -F upfile=temp/@image.jpg -F 'name=test' it returns like this but file is not uploaded. {"name":"test","file":null} Where am I wrong? -
Query on response value
How to write a conditional query on multiple fields? Explain: I have an index let say "case" and the fields are "title", "secondTitle(contain nested obj)", "source(contain nested obj)". Now I want to search on title and want number of document inside of secondTitle, which also contains in source field of another document. PUT /case_indx_tmp_tmp { "mappings": { "properties": { "title":{ "type": "text", "fields": { "title":{ "type":"keyword" } } }, "secondTitle":{ "type": "nested", "properties": { "second_title":{ "type":"text", "fields": { "secondtitle":{ "type":"keyword" } } } } }, "source":{ "type": "nested", "properties": { "source_title":{ "type":"text", "fields": { "sourcetitle":{ "type":"keyword" } } } } } } } } PUT /case_indx_tmp_tmp/_doc/1 { "title" : "Case 1", "secondTitle" : [ { "case_title" : "Case 2" } ], "source":[ { "source_title":"Case 3" }, { "source_title":"Case 4" } ] } PUT /case_indx_tmp_tmp/_doc/2 { "title" : "Case 2", "secondTitle" : [ { "case_title" : "Case 3" }, { "case_title" : "Case 4" }, { "case_title" : "Case 1" } ], "source":[ { "source_title":"Case 1" } ] } PUT /case_indx_tmp_tmp/_doc/3 { "title" : "Case 3", "secondTitle" : [ { "case_title" : "Case 5" }, { "case_title" : "Case 4" }, { "case_title" : "Case 1" } ], "source":[ { "source_title":"Case … -
How to hide the django AuthenticationForm built-in error_message?
I'm new to django and trying to hide the error message that has bullet on it (see screenshot below), the built-in error_message attribute when using the AuthenticationForm class on login, because I have used the form.errors in the templates and wanted to keep the error message on the top. I tried to use css to hide, but when I load the login page, it wont work. Is there a way to hide or perhaps disable it? I can only see the options to customize error_message in the docs though. Here is my code. login.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <!-- Custom Error Message --> {% if form.errors %} {% for _, error in form.errors.items %} <div class="alert alert-danger text-center"> {{ error|striptags }} </div> {% endfor %} {% endif %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log in</legend> {{ form | crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="text-muted ml-2"> <a href="{% url 'password_reset' %}">Forgot Password?</a> </small> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a href="{% url 'register' %}" class="ml-2">Sign Up</a> </small> </div> </div> {% endblock content %} forms.py class LogInAuthForm(AuthenticationForm): username = … -
How to post a foreign key using as an actual field name and not pk value
Im still new to django and im trying to post the rfid number and bus reg number and i get the following error: Error: {"status":"error","data":{"rfid":["Incorrect type. Expected pk value, received str."],"bus":["Incorrect type. Expected pk value, received str."]}} I would like to post the actual rfid number and bus reg number instead of the pk value. Is there a way of achieving this. Transaction model: class Transaction(models.Model): bus = models.ForeignKey(Bus, on_delete = models.CASCADE) rfid = models.ForeignKey(Rfid, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) Serializer: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ('rfid', 'bus') views.py: class TransactionViews(APIView): def post(self, request): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) rfid model: class Rfid(models.Model): rfid_num = models.CharField(max_length = 50, unique = True) lock = models.BooleanField(choices = BOOL_CHOICES, default = False, verbose_name = 'Lock card', blank=True) is_active = models.BooleanField(default = True) user = models.OneToOneField(User, on_delete = models.CASCADE) balance = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) bus model: class Bus(models.Model): reg_num = models.CharField(max_length = 20, unique = True) destination = models.ForeignKey(Destination, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) company = models.ForeignKey(Company, … -
how to search a string with space in django search method?
when I search the first_name and last_name field together it won't display the result eg: serch_text = "harry potter " it does not include the space? views.py def get(self, request, *args, **kwargs): if request.is_ajax(): search_text = request.GET.get('search') if search_text is not None and search_text != u"": search_text = request.GET.get('search') print(search_text) wallets = Wallet.objects.filter(Q(user__customer__first_name__icontains=search_text) | Q(user__customer__last_name__icontains=search_text) | Q(user__customer__email__icontains=search_text) | Q(user__customer__phone__icontains=search_text)) else: wallets = Wallet.objects.all() html = render_to_string('customer/wallet-filter.html', {'wallets': wallets}, request) return JsonResponse({'html': html}) wallets = Wallet.objects.all().order_by('-id') return render(request, 'customer/wallets.html', {'wallets': wallets}) -
Python - order python list by datetime object
I have a list of datetime objects that's being appended into an array from my database with an additional library called Django Recurrence. I append it as follows inside a for loop: events = Events.objects.filter(...some conditions) timeslots = [] for event in events: for occurence in event.recurrences.between(context['today'], context['end']): occurence_date = datetime.combine(occurence.date(), time(0, 0)) timeslots.append({ 'start_date': occurence_date + timedelta(hours=event.start_time.hour, minutes=event.start_time.minute), 'end_date': occurence_date + timedelta(hours=event.end_time.hour, minutes=event.end_time.minute), }) It would then output it as [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, {'start_date': datetime.datetime(2022, 3, 8, 14, 0), ... }] which is great. A side effect from the events loop, is that it would add a the other events, after all the occurrences, eg 1 march, 5 march, 10 march, 2 march, 4 march, etc etc etc. I'd like to order them by the starting date, so I can render them out in the correct order in my template. Thanks -
How to edit a Djano app in production mode in a remote linux server
I have to make changes to a Django application already in production on a linux. Can anyone guide me as to how I can make changes to this application through ssh? I was able to ssh and access the code of the application but I don't know how to commit a change to the application as I don't have access to the runserver terminal like the one I have access to when developing on windows. Also would be helpful if someone could explain how to access the particular python env it's running on. Help on this would be appreciated. -
Using for django loop inside of a JavaScript variable
I want to loop through a django query in JavaScript, example: musics = Music.query.all(). I did something like this: const songs = [ {% for music in musics %} { id: "{{music.id }}", songName: "{{ music.title }}", poster: "{{ music.cover_image.url }}", } {% endfor %} ] Array.from(document.getElementsByClassName("songItem")).forEach((element, I) =>{ element.getElementsByTagName('img').src = songs[I].poster; }) I get Uncaught TypeError: Cannot read properties of undefined (reading 'poster'), but if I use console log console.log(element.getElementsByTagName('img').src = songs[I].poster); ``` it works in the console. -
Can't open link containing special characters
I have Django app which I test on my local PC and then when I add something new, I upload changes to my company virtual server. I have a problem with links to files. Below is the code for links to attached files (both my local and server have the same code): <p class="article-content mt-2 mb-1"><strong>Attachment: </strong><a href="{{post.file_close.url}}">{{post.file_close.name}}</a></p> If I upload file cars.png everything works fine in both versions. This works no matter the extension, pdf, excel, image, etc. Problem is, if I upload file carsčč.png it fails only on server side, on my PC it works great. I get the following error on my Django/debugg: Page not found (404) “C:\inetpub\files\PyWeb\media\PN_files\2022\03\06\cars” does not exist Like the link is not complete, it stoped as soon as it runs into a special character. But, shown link still containes all the letters, it's PN_files/2022/03/06/carsčč.png Tried: I looked at regional settings, it's the same on both PCs. Is there something else I could check or change? Maybe include something in the link? Also, when I manually search for the file, the name is not currupted, it's saved localy as carsčč.png. So I guess it's only the link, tring to get the file. I figured … -
Does Django automatically manages the media while loading the application?
So what i want to achieve here is to load my web-application faster. In my web-application there will be lots of media file like audio, video, images. Locally i guess network time is faster but on server side it is starting to slow down. What I want to know here is, if there is any way to manage this media file specifically in Django or in general. Need solution for django not django-rest-framwork -
Django rest framework custom search
I have a drf viewset like this class EntryViewSets(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Entries.objects.all() serializer_class = EntrySerializer authentication_classes = (SessionAuthentication, BasicAuthentication) search_fields= ('desc',) filter_backends = (CustomSearchFilter,) Here I want to search the desc field which is of type models.TextField. The search works, but I want to add some condition to the searches. I want to match the search with the query but only if the match does not contain a #. For example, lets say I have two entries with desc, test new and test #new. Now if I do this query ?search=test it returns both and ?search=new also returns both. But I want the second query to only return the first entry i.e. test new, not test #new as it starts with # it should be discarded. How do I do this? -
Can't connect to GCP with external IP
Trying to connect to my django website that's stored on the GCP virtual machine. Everything works fine if I'm accessing it internally using internal IP or localhost. However, I can't access website with external IP. I have http, https traffic enabled on instance. Firewall rule to allow port 80: Here is Test-Net results. Searched the web for answers but nothing looks wrong in my settings.. Any ideas would be appreciated. -
Why does accessing Django cache during unit tests (manage.py test) produces datetime.datetime objects instead of expected values?
I have a Django app, and I'm trying to create unit tests for functions/methods that work with the cache. My tests are run using python manage.py test. The functions/methods I'm testing contain lines that are similar to the following: from django.core.cache import cache ... def some_function(): ... cache.set('test', ('hello', 'world')) retrieved = cache.get('test') ... I expect retrieved to be the value that I retrieved from the cache (in this case, ('hello', 'world')); however, retrieved is somehow always a datetime.datetime object. This happens for various different cache backends, including django.core.cache.backends.locmem.LocMemCache and django_redis.cache.RedisCache. How can I correct this cache behavior for tests? -
I am having trouble getting an ajax request data to show up in each dynamically created form in Django
My Django project has an app that registers sales which needs to have multiple forms saved all at once using Django formsets, I have managed to get the dynamic forms working but it needs improvement so that with a product selected in each form, the product price may appear on the price field dynamically and the total price (product_price * quantity) may also appear in the its respective field. My code only shows the first form's price but when i add new forms (dynamically) they all appear with the the price of the first form and not the price of the product selected in in each form. Please really I need help fixing that. My sale models... class Product(models.Model): slug = models.SlugField(editable=False, unique=True, verbose_name=_("product id")) is_active = models.BooleanField(default=True, verbose_name=_("is active")) product_name = models.CharField(max_length=50, verbose_name=_("product name")) cost_price = models.DecimalField(max_digits=19, decimal_places=2, verbose_name=_("cost price")) retail_price = models.DecimalField(max_digits=19, decimal_places=2, verbose_name=_("retail price")) class ProductSale(models.Model): slug = models.SlugField(editable=False, unique=True, verbose_name=_("product sale id")) product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name=_("product")) retail_price = models.DecimalField(max_digits=19, decimal_places=2, blank=True, null=True, verbose_name=_("retail price")) quantity = models.SmallIntegerField(verbose_name=_("quantity")) total = models.DecimalField(max_digits=19, decimal_places=2, blank=True, null=True, verbose_name=_("total")) The form... ProductSaleFormset = modelformset_factory( ProductSale, fields=("product", "quantity"), extra=1, localized_fields="__all__", widgets={ "product": forms.Select( attrs={ "id": "id_product", "class": "form-control", "style": "width:350px", } … -
URL not correctly configured in Django
I am creating a Blog post application and I have added a new feature to mark a post favourite. Now I have also used django authentication system to authenticate users. I have written the following login in add to favourite function in views.py file def favourite_post(request,pk): if request.user.is_authenticated: post = get_object_or_404(Post, pk=pk) if(post.favourites.filter(id=request.user.id).exists()): post.favourites.remove(request.user) else: post.favourites.add(request.user) else: return redirect('members/login_me_in') return redirect(request.META['HTTP_REFERER']) Now when a non authenticated user clicks on the favourite button in template the URL formed is -> http://127.0.0.1:8000/favourite-post/members/login_me_in But It should have been -> http://127.0.0.1:8000/members/login_me_in This is the URL that will be used when clicking the Add to favourites button -> path('favourite-post/<int:pk>',views.favourite_post,name='favourite_post'), Can anyone help me out to change the URL that is being sent. -
How to decrease the slider speed in Django?
Please help to decrease speed, it's too fast. Searched a lot in google and everywhere there is Bootstrap solution. I even tried Bootstrap, that was too slow and different icons which didn't look good. Also Bootstrap version center it's PREV and NEXT icons for each image, which is also not looking good as I have different image height. Is there any way to change speed in my current carousel? Please help. my CSS looks like /* PRODUCT DETAIL SLIDER START */ .product_detail-slider{ position: relative; } .product_detail-slider .owl-stage-outer{ overflow-x: hidden; } .product_detail-slider .owl-stage{ display: flex; } .product_detail-slider .owl-nav .owl-prev{ position: absolute; top: calc(50% - 80px);; left: 0; border: none; background-color: transparent; } .product_detail-slider .owl-nav .owl-prev span{ color: rgba(0, 0, 0, 0.30); font-size: 80px; transition: all 2s; } .product_detail-slider .owl-nav .owl-prev span:hover{ color: #000000; } .product_detail-slider .owl-nav .owl-next{ position: absolute; top: calc(50% - 80px); right: 0; border: none; background-color: transparent; } .product_detail-slider .owl-nav .owl-next span{ color: rgba(0, 0, 0, 0.30); font-size: 80px; transition: all 2s; } .product_detail-slider .owl-nav .owl-next span:hover{ color: #000000; } .owl-dots{ display: none; } /* PRODUCT DETAIL SLIDER END */ my HTML <div class="product_detail-slider"> <div class="product_detail-slider_block"> <img src="{{ product.image_url }}" alt="" style="width:100%; padding-bottom: 20px;"> </div> {% if product.image_2_url %} … -
How access session variable from Django Simple Tag
I want access session variable from Django Custom simple type tag. but I don't know how can I do it. please anyone helps me if anybody knows. @register.simple_tag def get_blancecalculate(amonut): return amonut @register.inclusion_tag('Admin UI/Reports/leadger-blance.html',takes_context=True) def get_blance(context,Blance): request = context['request'] LedgerBlance = request.session['LedgerBlance'] + float(Blance) request.session['LedgerBlance'] = LedgerBlance return {'CurrentBlance':LedgerBlance} -
Django how to update a template without refreshing/redirecting?
I'm trying to make a simple commenting system where someone can add their comment to a post and it'll show up without having to redirect them or refresh the page. This is what my code basically looks like: def post_details(request): details = {} if request.method == "POST": request.POST # Function here for creating a new comment details['new_comment'] = new_comment details['post_details'] = post_details else: details['post_details'] = post return render(request, 'post_details.html', details) The post_details.html shows a post with comments below it along with a form that adds their comment. I tried to add a new block of code in the template file for new_comment and the issue is that when I add a new comment, it will update that part but adding another one won't show up. I should also note that I have CSV files that store the post and comment details. In my models.py file, I have my classes and methods to read in the CSV files so the function I left out does update the file with the comments. I'm trying to do this without Javascript but I'm open to trying anything, just really want to solidify my understanding of requests. I hope this wasn't confusing. -
Django: Not able to get bio field from table to be displayed on page
I developed a small test app with a profile page with user info and bio. Everything is showing except the bio field, this is silly and driving loopy. I tried so many combinations to no avail. Please see my code below: Someone please help. views.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class TeacherProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() def __str_from__(self): return self.user models.py def teacher_profile(request,pk): teacher_profile = TeacherProfile.objects.all() return render(request, 'registration/teacher_profile.html', { 'teacher_profile':teacher_profile }) html <div class="container"> <div class="row"> <div class="col-lg-12"> <h1 class="page_heading">Teacher profile</h1> <strong>Welcome back:</strong> {{user.username}} | {{user.first_name}} {{user.last_name}} | {{user.email}} | <strong></strong>| <a href="{% url 'edit_teacher_profile_view_url' user.pk %}">edit profile</a><br> | <a href="{% url 'logout' %}">logout</a><br> <strong>About me:</strong> {{user.bio}} <hr> </div> </div> -
Python Flask Postgres error - Can't generate DDL for NullType(); did you forget to specify a type on this Column?
Seemingly out of the blue I started getting this error whenever I try to run my flask app. Can't generate DDL for NullType(); did you forget to specify a type on this Column? I've changed nothing with the code or database. It runs fine from another server so I'm thinking it has to be something with the computer I'm running the script on but I'm out of ideas. I restarted my computer, restarted the database. Here is the code from flask import Flask, jsonify from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@ngdeva-2/flaskapp2' db = SQLAlchemy(app) class Project(db.Model): id = db.Column(db.Integer, primary_key=True) wmx_jobid = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return f"{self.id} - {self.wmx_jobid}" db.create_all() @app.route('/', methods=['GET']) def home(): message = 'Flask is UP and RUNNING!' return jsonify(message) if __name__ == "__main__": from waitress import serve serve(app, host="0.0.0.0", port=8080) -
Django POST Request 500 Error: AttributeError: 'QuerySet' object has no attribute '_meta'
I am trying to create a POST request to add a user to a database, but I am getting a 500 error with this message: AttributeError: 'QuerySet' object has no attribute '_meta'. Here is my code: @api_view(['POST']) def register(request): data = request.data if data['password'] != data['password_confirm']: raise exceptions.APIException('Passwords do not match') serializer = UserSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) UserSerializer: from rest_framework import serializers from users.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User.objects.all() fields = ['id', 'first_name', 'last_name', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} User: from django.db import models # Create your models here. class User(models.Model): first_name = models.CharField(max_length=63) last_name = models.CharField(max_length=63) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) This is the stack trace: Internal Server Error: /api/register Traceback (most recent call last): File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/amicharski/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/amicharski/.local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File … -
Calling function with variable from view template, django
in template {{object.get_resource}} in views.py(DetailView) def get_resource(self): return "my resource" It works. Now, I want to pass the variable to object. Is it possible to do like this below? {{object.get_resource(1)}} def get_resource(self,num): return "my resource:{0}".format(num) -
REST Django - Can't find context of request from within my validator
Please be gentle. I'm a Django newb and I find the level of abstraction just plain overwhelming. My ultimate goal is to modify an image file on its way into the model. That part may or may not be relevant, but assistance came my way in this post which advised me that I should be making changes inside a validator: REST Django - How to Modify a Serialized File Before it is Put Into Model Anyway, at the moment I am simply trying to get the context of the request so I can be sure to do the things to the thing only when the request is a POST. However, inside my validator, the self.context is just an empty dictionary. Based on what I have found out there, there should be a value for self.context['request']. Here is what I have: Serializer with validator method: class MediaSerializer(serializers.ModelSerializer): class Meta: model = Media fields = '__all__' def validate_media(self, data): print(self.context) #todo: why is self.context empty? #if self.context['request'].method == 'POST': # print('do a thing here') return data def to_representation(self, instance): data = super(MediaSerializer, self).to_representation(instance) return data The view along with the post method class MediaView(APIView): queryset = Media.objects.all() parser_classes = (MultiPartParser, FormParser) permission_classes … -
User select Model from dropdown in Django form
Wondering if there is a way allow a user to select the Django model to input data into from a drop-down menu. I have a bunch of small items that each have their own model but would prefer if a user could add data to a desired model all from the same form page. So ideally a user goes to one "add data" page and from there they can choose the desired model to add data to from a drop down. Then the form will update with the required fields needed. Is this possible or do I need a separate view for each model & form? Tried searching and found this relevant post but that's 8 years old and it seems most of that has been depreciated so not sure where to continue or if its even possible.