Django and Python "Questions and answers", page 1623

11.08.2021
Django Object not Saving

I am currently trying to save a Django object. My code looks like this boxscore = BoxScore.objects.create(**defaults) print(defaults) input(boxscore) Here's the output: {'away_first': 0, 'away_second': 6, 'away_third': 7, 'away_fourth': 17, 'away_final': 30, 'home_first': 0, 'home_second': 7, 'home_third': 0, 'home_fourth': …

11.08.2021
How to refresh the tokens stored in the Django Cache which is using Database as a cache storage

I have tokens stored in the Django Database Cache. I want to periodically refresh the tokens i.e. after every 5 min. Refreshing involves checking the token validity by calling an External service API and deleting all the tokens which are …

11.08.2021
Using django-polymorphic type information in query expressions

I have a django model with a couple of subtypes which until now I've been handling explicitly. Each record is uniquely identified by three fields: class Entity: type = CharField(max_length=3) released_at = DateTimeField() number = IntegerField() I use a …

11.08.2021
How can we integrate call forwarding in our website like Indiamart?

We have a website called RentYug on which people can give or take anything on rent. For this, we are taking contact information like mobile number and some other details of renter (who is giving Something on rent). But we …

11.08.2021
Automatically get the user’s location from the user’s browser instead of hard-coding in django view to filter nearest shop

Am building a simple nearby shops application that lists the shops closest to a user’s location using django and GeoDjango. To list the shops, i want to get a user's location from their browser and then filter the nearest shop …

11.08.2021
Ezhc heatmap.build requires pandas.core.index but it is Pandas.core.index is deprecated

I use ezhc and pandas to generate data for heatmap def industry_heatmap(csv): df = pd.read_csv(csv).set_index('Industry').groupby(level=0).mean() idx, col, data = hc.build.series_heatmap(df) … return idx, col, data return json However as a result of pandas 1.3.1 deprecating pandas.core.index... C:\Users\lib\site-packages\ezhc\build.py, line 338, …

11.08.2021
Django queryset.values_list() except returning a queryset of a foreign key

Given some simple models, including one with a foreign key: class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() If I have an arbitrary queryset of the Entry objects, say my_entries_queryset Entry.objects.filter(...). How …

11.08.2021
Why my queryset changes size after I evaluate it in Django?

I have a simple model: class Expense(models.Model): ... price = models.DecimalField(decimal_places=2, max_digits=6) is_fixed = models.BooleanField(default=False) I'm trying a simple query to group_by and aggregate: >>> from expenses.models import Expense >>> from django.db.models import Sum >>> …

11.08.2021
Djongo - trying to create a list field

I'm trying to explore Django and djgono for fun. I want to create a document in the db which is similar to the following document: { "title": "Djongo - trying to create a list field", "body": "I cannot do basic …

11.08.2021
Has anyone shared a CRSF token between React and Django without running into Forbidden 403?

I've been trying to execute a simple endpoint I made available with Django from my front-end, React. It's a POST request that checks if a URL exists. It's just a demo so I can get familiar with the full stack …

11.08.2021
Uploading Image to AWS using Tinymce and Django

I am working with django an Tinymce. I have an issue with uploading image to s3 bucket from the Tinymce textarea. The same code does the uploading perfectly on my local. but when deployed, it doesnt get to upload. @csrf_exempt …

11.08.2021
Should i dockerize django app as non-root?

Should i dockerize Django app as a root user? If yes how can i set up non-root user for Django? Because in node.js app should have USER:node which is a better practice. Code example from official docker page which does …

11.08.2021
Creating a templete with xlsxwriter in django webframework

I'm new to django and still trying to figure out logic. I watched a bunch of videos and I know how to create those examples but I'm not quite there. I'll explain what I want and maybe someone can explain …

11.08.2021
My ajax jquery script does not display image src with conditions but it displays video src and audio src with conditions

I am using django rest framework. From backend everything is fine. But when i display my img src with my conditions.It does not display my image source but My video and audio src displays properly with conditions but img src …

11.08.2021
How to Solve 403 Forbidden Apache2 While Deploying a Django Application to an Ubuntu Server?

The exact error that I got is: Forbidden You don't have permission to access this resource. In /etc/apache2/sites-enabled/portfolio.conf, I copied 000-default.conf and added the following lines: Alias /static /home/kailicen/portfolio/static <Directory /home/kailicen/portfolio/static> Require all granted </Directory> <Directory /home/kailicen/portfolio/portfolio> <Files …

11.08.2021
How can I implement this in my views.py and in my urls.py file?

I am working on a network monitor Django website and want to implement tx and rx monitoring commands. wifi_tx = "apstats -a | grep -i 'Tx Data Bytes' | awk '{print $5}'" wifi_rx = "apstats -a | grep -i 'Rx …

11.08.2021
Using python/Django, is there a way draw a shape in contained in a rectangle box(specifically map of a land) with specific line length and angle

I am trying to generate land ownership certificate using python/django. It needs to include 2d map of the land and I was wondering if there was a way/tool in python to draw it. Thanks in advance

11.08.2021
What can I do to don't show csrf token in the URL line?

I have a form like <form id="..." class="...">. Inside this form, I have 2 buttons, which are tracked with JS like: function one(event) { $.ajax({ type: 'POST', url: "...", data: { 'csrfmiddlewaretoken': csrf[0].value, }, ... }) } function two(event) { …

10.08.2021
Django: Null value in column "category_id" of relation "APIs_api" violates not-null constraint

I'm trying to save data into my PostgreSQL database but I seem to get an error on the category_id column that it's null. All other data seems to be submitted correctly but I keep getting this error. Null value in …

10.08.2021
How do I edit a form with Imagefield without updating Photo?

I've tried numerous ways to fix this error and I can't seem to solve it. I have a form for a user profile, the profile automatically gets created when the user registers and they receive a default photo until they …

10.08.2021
Debugging and logging when using Celery

I've been searching through StackOverflow about this topic and haven't found anything updated so I'm asking again: What is the best practice to log when using celery? I've tried many ways and it still doesn't work. Also when I'm trying …

10.08.2021
How to add scroll bar to a CheckboxSelectMultiple for a m2m field in admin panel in django?

I have two models App and Country and there is a many to many field in App to country(the other_countries field) . class Country(models.Model): name = models.CharField(max_length=100, blank=False, null=False) numeric = models.BigIntegerField(blank= True, null= True) key = models.CharField(max_length= 5, blank= …

10.08.2021
Serialize don't show data [closed]

serializer ///////////////////////////////////////////////////////////////////////////// class CommentSerializer(serializers.ModelSerializer): response_to = CommentSerializer2(many=False, read_only=True) # like = LikeSerializer(many=False, read_only=True) like = LikeSerializer(many=False) class Meta: model = Comment fields = ['id', 'user', 'text', 'created', 'response_to', 'post', 'like'] def create(self, validated_data): comment = Comment(user=self.context["user"], **validated_data) comment.save() …

10.08.2021
How Can I Auto Add URL to User Shared Post with Django Form

I want users to be able to share posts in my web app. How can I automatically generate a unique url in the background while doing this using a django form. I tried a little myself but failed. The reason …

10.08.2021
I got a probelm when I was trying to deploy my Django project to Digital Ocean. I followed that tutorial step by step, but it doesn't work on gunicorn

A little background-- Our deployment process is now on using gunicorn, so that means specifically our .wsgi file will be used. But since we never used our .wsgi file when we ran it on our local pycharm to view the …

10.08.2021
DRF FormData. Passing arguments in querydict as list of one element

Front I request to the server with something like: { "name": "myname" } Back in request.data <QueryDict>: {"name": ["myname"]} And I had to set this for param, val in params.items(): val = …

10.08.2021
Why is the MySQL query taking 25 seconds to give the output? [closed]

I have created a MySQL Database in PythonAnywhere but the problem is that it is taking too long to show results. As shown in the image below, it is taking almost 25 seconds to show the databases which I think …

10.08.2021
Making Django model Query case-insensitive

I would like to look up users by their email without worrying about uppercase letters. How would I do this? I tried customer = Customer.objects.get(email__lower="test@gmail.com") and got this error. django.core.exceptions.FieldError: Unsupported lookup 'lower' for EmailField or join on the …

10.08.2021
Why do i keep getting locking file error install django or django packages?

When I install django or django packages every time I get this error.Pipfile.lock does't occur.Is it a serious problem?If it is, how can ı fix it? <img …

10.08.2021
Does not reflect current user in comment

Hello I am new in the community and in the world of programming so I hope you can excuse my ignorance. I'm creating an Instagram-style application with Django 3.2.5. Where users have profiles to visit and upload photos. I am …

10.08.2021
How to output the specfic content reltaed to the title

I am trying to make website which shows the judgements of various cases based on some conditions. I pushing the data from database, where i upload the title of the judgment and the contents of the judgement. In the html …

10.08.2021
Python Why Django won't let me load a new product

I'm in this page: Filling the details The link of orange image is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various …

10.08.2021
Django template tags for changing key names in a dictionary

I'm working on a kanji website with Django templates. I have a dictionaries made out of an external xml. I set xml tags as keys. Here is an example of one of those dicitionaries (which casually happens to be about …

10.08.2021
Django project with Eureka server [closed]

Can any one help me how to do django project with Eureka server end to end proper implementation

10.08.2021
Django - How do I leave some fields empty when I click "Save as new"?

I am trying to clone an existing item exactly as is, make edits, and save the new version in the admin. However, I do not want to pre-fill specific fields. I need to leave those specific fields empty in the …

10.08.2021
The view system.views.Login didn't return an HttpResponse object. It returned None instead

I'm newbie to Django. I'm stuck at one thing that, valueError at /login/. I've tried my best to search and try to solve this but i didn't find my problem solution. In Following First Code Sample From Which I Got …

10.08.2021
Django {"non_field_errors":["Unable to log in with provided credentials."]} (authtoken)

Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) # creates token when user registers def create_auth_token(sender, instance=None, created=False, **kwargs): …

10.08.2021
Xhtml2pdf: Output generated PDF as in-memory object (its bytes)

I'm working with Python 3, Django and the xhtml2pdf package. I want to create a PDF from an HTML string, but I don't want to write the PDF on disk, but rather just to get its bytes, as in using …

10.08.2021
How to pass kwargs in ajax urls in django? Reverse for '' with arguments '('',)' not found. 1 pattern tried: ['partners/analytics/(?P<id>[0-9]+)/$']

I have the following code in one of my templates: var id = &quot;{{a.id}}&quot;; $.ajax({ url :'{% url 'this:dashboard' id %}',, type : 'POST', data : { }, }); I get the following error? Reverse for '' with …

10.08.2021
Фотографии в тексте статьи Django

Как правильно сделать отображение фотографии в тексте статьи на Django так, чтобы в админке можно было вставлять 1 или несколько фото в разные места статьи?