Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change HTTP to HTTPS in sitemaps.xml of django website?
Its show only http not https. But my sites is secured https. sitemaps doesnot shows https. Links are indexed in google console but not submitted in sitemap. Help me -
Django doesn't see urls.py
I'm new to Django and I'm following this tutorial: https://www.django-rest-framework.org/tutorial/1-serialization/ When I run the server with python manage.py runserver, it seems to work fine showing me no errors. However when I visit http://127.0.0.1:8000/snippets/ it gives me the following error: Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: admin/ The current path, snippets/, didn’t match any of these. Here's my urls.py located in the tutorial folder: from django.urls import path, include urlpatterns = [ path('', include('snippets.urls')), ] I don't understand what's going on, how come it only checks admin/ if I'm wiring the root urlconf to snippets.urls? On a related note, when I modify urls.py and add gibberish the server won't give me an error, however if I were to modify models.py then it'll start complaining, that's why I'm getting the feeling it doesn't even check my urls.py and maybe instead some default one... Any tips are very appreciated! -
Can I compare two datetime.datetime fields in Django?
I am having two-time fields - one from the database and one is the current time. I want to check if the current time is greater than the database time field or lesser. How to do that? if expiration_date < datetime.now() item_info['expired'] = True The above does not work. Syntax error. -
reading uploaded file before saving them to database in django
I want to validate the uploaded files before saving them to database. My validator is something like this def validate(size, file_name): valid_types = ["ffd8ff"] valid = 0 infile = open(f"{file_name}", 'rb') # here header = infile.read(24) header = str(binascii.hexlify(header))[2:-1] if header[0:6] in valid_types: valid = 1 else: valid = 0 return valid Im able to pass the size and file_name as arguments but how do I read the file without saving it. If the validator returns 1 then the my views.py saves the file else no. Thank you! -
How to fix nginx: [emerg] "proxy_cache" zone "django_cache" is unknown in /etc/nginx/nginx.conf:63
when I try to use error-check command in nginx using the command: sudo nginx –t this error has been raised: nginx: [emerg] "proxy_cache" zone "django_cache" is unknown in /etc/nginx/nginx.conf:63 I want to use nginx for my django server app but I stopped here! I searched about it but no result even in google I watched videos and read blogs but no one talk about this problem anyone knows about it thank you! -
Implement similar products in the Django framework
I want when the user enters the page of a product, that page displays the products whose first name is the same as this product. In fact, I want to implement similar products. Each time a user enters a page, the products whose first name was the same as the product the user entered are identified as similar products. I do this as follows but it does not recognize any products. What is the reason for this? my model: class Product(models.Model): name = models.CharField(max_length=200) .... my view: def product_details(request, id): products = get_object_or_404(Product, id=id) related_products = Product.objects.filter(name__startswith=products.name) ... -
django DRF with Firebase needs access to request._request
I have a mobile app talking to backend server (Django+drf). Auth is handled via Firebase. On the django side, I'm using custom DRF auth and session auth. The Custom DRF(firebase) auth kicks in for the first time and subsequently, after the jwt is validated and the user is created if needed, the session auth will kick in for as long as the session is alive. In order for the Session auth to kick in, I ofcourse need to auth.login(request, user) the user. However, the Request is the wrapped DRF request and not a Django Request. Questions: Is the above described pattern (DRFCustomAuthFirebase + SessionAuth) an acceptable approach Is the only way to login the user by accessing protected _request request._request or is there another way ? Basically, how do I get DRF Custom auth to intersect Django auth (aside from doing login(request_request, user) in order to effectively use DRF Session Auth. -
Django: Custom router for read-replica raises OperationalError on save (with related models)
I'm testing out a custom database router for a Django project to support read replicas (based on the Django docs on multiple database) and when I create model instances containing references to other models, the save method tries to use the read-replica, for some reason. I've registered the following router in the DATABASE_ROUTERS settings: class PrimaryReplicaRouter: def db_for_read(self, model, **hints): return "replica" This should only route read operations to the replica, but for some reason, save operations (on models with related models) seem to trigger use of the replica: In [1]: from django.contrib.auth import User In [2]: from myapp.models import BlogPost In [3]: user = User.objects.first() In [4]: post = BlogPost(user=user) In [5]: post.save() # ... <traceback> OperationalError: (1142, "INSERT command denied to user 'readonly'@'localhost' for table 'myapp_blogpost'") Using create on the queryset (e.g. BlogPost.objects.create(user=user)), on the other hand, works fine, and so does saving objects that don't have FK references to related models. This is a simplified version of my models, but the model I'm using only has a reference to the User model and some primitive fields and there are no custom save methods on the models. Am I doing something wrong or is this behavior documented somewhere? … -
Django - Model instance with entries from another model
I need to create a website that allows the administrator to compose a catalogue of project parameters (with categories, subcategories and values). The users should then use this catalogue as a template to fill in their values. So I created a ParameterCatalogue model with a OneToOneField to the Project model. class ParameterCatalogue(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name='catalogue') An abstract Parameter class with common attributes and methods: class Parameter(models.Model): class Meta: abstract = True class Category(models.IntegerChoices): pass parameter_catalogue = models.project(Parameter, on_delete=models.CASCADE) name = str category = models.CharField(max_length=16, blank=True) subcategory = models.CharField(max_length=16, blank=True, default="") value = models.DecimalField(name="value", decimal_places=1, max_digits=6) and a few Parameter classes that inherit from it: class ParameterA(Parameter): name = 'parameter_a' class Category(models.TextChoices): CAT_1 = 1, _('CAT1') CAT_2 = 2, _('CAT2') CAT_3 = 3, _('CAT3') CAT_4 = 4, _('CAT4') category = models.CharField(max_length=4, choices=Category.choices, default=Category.CAT_1) class ParameterB(Parameter): name = 'parameter_b' class Category(models.IntegerChoices): CAT_1 = 1, _('CAT1') CAT_2 = 2, _('CAT2') CAT_3 = 3, _('CAT3') CAT_4 = 4, _('CAT4') CAT_5 = 5, _('CAT5') CAT_6 = 6, _('CAT6') CAT_7 = 7, _('CAT7') category = models.PositiveSmallIntegerField(choices=Category.choices) Now I want to create a Model that resembles ParameterCatalogue for the user values. I want the instances of this model to mirror the ParameterCatalogue instance of the … -
insert extra dynamic input fields into database
I am trying to add all the values of a dynamic input field into the database using the logic below. The model that has the dynamic field is declared like this: class MyModel(models.Model): # some_field dynamic_field = models.CharField("List of URLs", max_length=255, blank=True) # other_field The view I'm using to process the form looks like this: model_instance = MyModel.objects.get(pk_id=pk_id) model_form = MyModelForm(instance=model_instance) if request.method == 'POST': submitted_form = MyModelForm(request.POST) if submitted_form.is_valid() MyModelForm(request.POST, instance=model_instance).save() When the model is rendered in the browser, it looks like this: <input type="text" name="dynamic_field" value="url1" maxlength="255" id="id_dynamic_field"> Using JS, I am appending extra text inputs to the form, with the same name as dynamic_field When I print out request.POST in the view, I see all the values of dynamic_field in a list as (assuming url2 is the value for a dynamic input field added to the form) <QueryDict: {'csrfmiddlewaretoken': ['....'], 'dynamic_field': ['url1', 'url2'], 'some_field': [''], 'other _fields': ['']}> Only url2 is inserted into the database....essentially the last value. How can I insert both url1 and url2 into the database? -
Is it possible to add CK Editor in django admin without installing `django-ckeditor`?
I have a blogging website and when I upload it to pythonanywhere.com using free hosting it doesnot allow me to install the django-ckeditor module. Please answer if there is any solutution for that or is there any way to use it without installing django-ckeditor? -
Django UNIQUE constraint failed: players_comment.user_id
I'm trying to post comment but it's not getting posted, rather this error is appearing UNIQUE constraint failed: players_comment.user_id. I don't know why this error is occuring. Can anyone help me out of this? Thanks in advandce! My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body', 'transfernews') My models.py : class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.save() return redirect('transfernews/') return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My transfernews.html: {% for transfer in transfernews %} {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif %} <hr> <div>Comment and let us know your thoughts</div> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button> <button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button> </form> {% … -
Redis-server cache auto clearing
I was using Django with celery and redis-server. The redis server is Auto clearing all the cache data after I deployed the Wordpress site on the same AWS instance. I am not getting the root cause of the issue. Below is the Key Space notifications I got on the redis console. "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@0__:backup3","set" "pmessage","__key*__:*","__keyevent@0__:set","backup3" "pmessage","__key*__:*","__keyspace@0__:backup4","set" "pmessage","__key*__:*","__keyevent@0__:set","backup4" "pmessage","__key*__:*","__keyspace@1__:unacked_mutex","set" "pmessage","__key*__:*","__keyevent@1__:set","unacked_mutex" "pmessage","__key*__:*","__keyspace@1__:unacked_mutex","expire" "pmessage","__key*__:*","__keyevent@1__:expire","unacked_mutex" "pmessage","__key*__:*","__keyspace@1__:_kombu.binding.celery","sadd" "pmessage","__key*__:*","__keyevent@1__:sadd","_kombu.binding.celery" "pmessage","__key*__:*","__keyspace@1__:celery","lpush" "pmessage","__key*__:*","__keyevent@1__:lpush","celery" "pmessage","__key*__:*","__keyspace@1__:unacked_index","zadd" "pmessage","__key*__:*","__keyevent@1__:zadd","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked","hset" "pmessage","__key*__:*","__keyevent@1__:hset","unacked" "pmessage","__key*__:*","__keyspace@1__:unacked_index","zrem" "pmessage","__key*__:*","__keyevent@1__:zrem","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked_index","del" "pmessage","__key*__:*","__keyevent@1__:del","unacked_index" "pmessage","__key*__:*","__keyspace@1__:unacked","hdel" "pmessage","__key*__:*","__keyevent@1__:hdel","unacked" "pmessage","__key*__:*","__keyspace@1__:unacked","del" "pmessage","__key*__:*","__keyevent@1__:del","unacked" "pmessage","__key*__:*","__keyspace@1__:celery","lpush" "pmessage","__key*__:*","__keyevent@1__:lpush","celery" -
How does code splitting actually work? (and how can I code split with django?)
I'm using Django to serve HTML files, with a react application inside one of them. The application is too large and I would like to implement code splitting. This is simple enough to do with webpack, which I get allows me to break up the application into smaller files. I can load the scripts in order in the HTML template, but doesn't this just mean they'll all be loaded one at a time HTML page is served? How does webpack's code splitting actually determine which files are requested from the server, only at the points at which they're required by the user? Also, does anyone know how to correctly React code splitting in this way with Django? -
Traefik headers hostsProxyHeaders meaning
What does Traefik's Headers hostProxyHeaders configuration do? I am looking at traefik.yml settings from django-cookiecutter (link) middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: hostsProxyHeaders: ["X-CSRFToken"] I understand that it is required for CSRF header which django uses. Why is this configuration required and what happens if this configuration is not set? -
Django url namespace:app_name:url_name problem
When I look at the documentation of django, it says that I can redirect like this, but it doesn't work. urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls' , namespace='store')), path('yedek', include('store.urls' , namespace='store-yedek')), ] app_name = 'store' urlpatterns = [ path('', views.all_products, name='all_products'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ] -
cmd prompt and vscode showing different versions of django for same environment
I use command py -m django --version in cmd prompt it returns 3.2 as my django version but when i use the same command in vscode it returns 3.1.9. Can anybody explain why -
List all attributes in a model (Django)
I'm working on a blog app and I'm trying to get all posts to be listed on the index/homepage. Here's my BlogPost model: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title return f"{self.text[:50]}..." My views.py: from django.shortcuts import render from .models import BlogPost # Create your views here. def index(request): posts = BlogPost.objects.order_by('-date_added') body = BlogPost.objects.values('text') context = {'posts': posts, 'body':body} return render(request, 'blogs/index.html', context) and my index.html: <p> Blog </p> <p> Here's some articles I've written: </p> {% for post in posts %} <h1> {{post}} </h1> <p> {{body}} </p> {%empty%} <li> Sacrebleu! Where is me posts? </li> {%endfor%} The issue is how it's being displayed: Blog Here's some articles I've written: Favorite things: <QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]> This is a test: <QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]> Instead, I'd like for it to display as: Blog Here's some articles I've written: Favorite things: blah blah blah This is a test: lorem ipsum I feel like it has something to do with the id attribute, but I really can't point it out. -
Test a view function with a HTTP404 exception
I'm trying to test this view to ensure that it returns a HTTP404 if the RedirectUrl model class does not exist and redirect to the destination_url if it does. Also it should store the url. #Views.py def clickActivity(request: HttpRequest, pk: int, whatsappid: int) -> HttpResponse: try: redirect_url = RedirectUrl.objects.get(id=pk) except RedirectUrl.DoesNotExist: raise Http404("No RedirectUrl matches the given query.") store_url_entry = RedirectUrlsEntry(url=redirect_url) store_url_entry.save() destination_url = f"{redirect_url.symptom_check_url}" f"/?whatsappid={whatsappid}" return HttpResponseRedirect(destination_url) #models.py class RedirectUrl(models.Model): url = models.URLField( max_length=255, blank=True, null=True, default="https://hub.momconnect.za/confirmredirect", ) content = models.TextField( default="This entry has no copy", help_text="The content of the mesage that this link was sent in", ) symptom_check_url = models.URLField( max_length=200, null=False, blank=False, default="http://symptomcheck.co.za" ) parameter = models.IntegerField(null=True, blank=True) time_stamp = models.DateTimeField(auto_now=True) def my_counter(self): total_number = RedirectUrlsEntry.objects.filter(url=self.id).count() return total_number def __str__(self): if self.url: return ( f"{self.parameter}: {self.url}/{self.id} \n" f"| Clicked {self.my_counter()} times | Content: {self.content}" ) class RedirectUrlsEntry(models.Model): url = models.ForeignKey( RedirectUrl, on_delete=models.CASCADE, blank=True, null=True ) time_stamp = models.DateTimeField(auto_now=True) def __str__(self): if self.url: return ( f"{self.url.url} with ID {self.url.id} \n" f"was visited at {self.time_stamp}" ) #Urls.py urlpatterns = [ path( "confirmredirect/<int:pk>/<int:whatsappid>", views.clickActivity, name="ada_hook_redirect", ), path("redirect/<int:pk>", views.default_page, name="ada_hook"), ] I was able to test that the right templates are used but I'm struggling with this test. I'm a Django … -
How to get a json response object from backend side to frontend with django?
I tried to send a json object from django views to django template but that is going as a string instead of json object. This object(json_follower) is sending from view to django template which i'm consoling as shown you the output with an image screenshot. class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request): username_to_toggle = request.POST.get("user_toggle") json_follower = None profile_, is_following,json_follower = UserProfile.objects.toggle_follow(request.user, request.user.id ,username_to_toggle,json_follower) return JsonResponse({'result': is_following, 'json_follower':json_follower}) And inside view, I'm inheriting that json_follower from model manager as you can see in the given below code. def some_view(username_to_toggle): print(username_to_toggle,"User to togle") user = User.objects.get(username__iexact=username_to_toggle) print(user,"User object") user_seri = serializers.serialize('json', [user]) user_json = json.dumps(user_seri) print(user_json,"User json") return user_json class ProfileManager(models.Manager): def toggle_follow(self, request_user,user_id, username_to_toggle,json_follower): profile_ = UserProfile.objects.get(user__username__iexact=request_user.username) is_following = False follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) json_follower = some_view(username_to_toggle) #this someview function is written on the top of this model. else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) notify.send(actor, recipient=user, verb='follow you') json_follower = some_view(username_to_toggle) #this someview function is written on the top of this model. is_following = True return profile_, is_following,json_follower -
Simple app from Github - Can't connect to localhost
https://github.com/faisalshahbaz/django-calculator Hi there. I'm a total beginner and I just need to run this app, but have no idea how to do it. Python, pip, django etc. all are installed. I cloned the app with Git. Created a virtualenv. Open the project with Vscode (Python extension installed as well), open the cmd and typed manage.py runserver but got this error: C:\Users\Hp\Desktop\django-calculator>python manage.py runserver python: can't open file 'C:\Users\Hp\Desktop\django-calculator\manage.py': [Errno 2] No such file or directory -
Connecting Django to SQL Server
I am trying to connect my Django 3.0.7 project with SQL Server 17, in docker containers. here is my settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'mysql', 'PORT': '3306', 'OPTIONS': { 'provider': 'MSOLEDBSQL', 'driver': 'ODBC Driver 17 for SQL Server', }, }, } And this is the mysql service in docker-compose.yml mysql: image: mysql/mysql-server:8.0 restart: unless-stopped environment: - MYSQL_ROOT_PASSWORD=rootpassword - MYSQL_USER=user - MYSQL_PASSWORD=password - MYSQL_DATABASE=db_name ports: - 3306:3306 volumes: - mysql:/var/lib/mysql after the docker-compose up -d and all containers are started, I get the following: ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]Protocol error in TDS stream (0) (SQLDriverConnect)') -
Extract a common field from JSON results on Django
I'm currently developing a parking place reservation app, and I have an admin-only feature where I can see how many reservations are in an interval. At the moment, my JSON is the following: "count": 8, "next": null, "previous": null, "results": [ { "city": "city_name", "interval": { "init_date": "2021-03-02T00:00:00Z", "end_date": "2021-03-17T00:00:00Z", "label": "02-03-2021" }, As you can see, I have 8 intervals with the same information, the two dates, the label, the amount of reservations, and the city. The field city is the same for all the intervals, and I want to extract that and show it only once. Is it possible to do that? My model is: class ReservationView(APIView, LimitOffsetPagination): """Basic APIView with pagination""" permission_classes = ( IsAuthenticated, IsDashboardUser, ) def get(self, request, *args, **kwargs): instance = self.paginate_queryset(self.get_interval_data(), request) serializer = ReservationSerializer( instance, context=self.get_serializer_context(), many=True, ) results = serializer.data return self.get_paginated_response(results) And my serializer is: class ReservationSerializer(serializers.Serializer, ReservationsMixin): city = serializers.SerializerMethodField("_get_city") interval = serializers.SerializerMethodField("_get_datetime") metrics = serializers.SerializerMethodField("_get_metrics") I tried to do to_representation() but it only adds the city name to the end of every interval. -
Django graphene subscriptions keep loading without sending me the data
I followed the instrections here with an existed graphen api gitHub repo. Hoever, I tried all the three options graphql-python/graphql-ws datavance/django-channels-graphql-ws jaydenwindle/graphene-subscriptions. but non of them worked with me. problem: enter image description here as you can see here it is loading forever without sending the data. goal : I need to create realtime grapheql api (subscriptions) files: Note: in the repo you will see the original repo without the subscriptions code. -
Django view is not creating records in Database
i am not able to create record in a table FinTransDetail by admin: when I trying to add records I am getting errors. Please help to solve the issues. As I could not add by admin I can not add records by my View as well. But I can add record in FinTransHeader both by admin and by me view. Model: class FinTransHeader(models.Model): """Model representing a book (but not a specific copy of a book).""" fh_type = models.CharField(max_length=200) fh_code = models.CharField(max_length=200) fh_no = models.DecimalField(max_digits = 5, decimal_places = 0,unique=True) fh_dt = models.DateField() fh_detail=models.CharField(max_length=200,blank=True,null=True) fh_cust_code = models.CharField(max_length=200,blank=True,null=True) fh_user_code =models.CharField(max_length=200,blank=True,null=True) fh_ref=models.CharField(max_length=200,default='nil',blank=True,null=True) fh_status=models.CharField(max_length=1,default=0) fh_post_status = models.BooleanField(default=False) th_prt_status=models.BooleanField(default=False) def __str__(self): """String for representing the Model object.""" return str(self.fh_code) # return self.fh_no class FinTransDetail(models.Model): fd_no = models.ForeignKey( FinTransHeader,on_delete=models.CASCADE) fd_acct = models.ForeignKey(AccountMaster, to_field='AcctCode',on_delete=models.CASCADE) fd_debit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_credit = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_detail=models.CharField(max_length=200, null=True, blank=True ) fd_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True) fd_posting=models.BooleanField(default=False, blank=True, null=True) def __str__(self): """String for representing the Model object.""" # return self.ToString(AcctCode)+"-"+self.AcctName return str(self.fd_no) when I am trying to add records in FinTransDetail i am getting Html error as below: TypeError at /admin/waccounts/fintransdetail/add/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/admin/waccounts/fintransdetail/add/ Django Version: 3.1.1 Exception Type: …