Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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': 7, 'home_final': 14} BoxScore object (190) However, nothing is showing in Django admin as being saved in the database. Why would this be and how do I fix it? -
How to refresh the tokens stored in the Django Cache which is using Databse 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 invalid and deleting them from cache. How can this be done? -
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 query expression to combine this into a single string for searching and annotating results: entity_uid_expr = Case( When( number=None, then=Value(None), ), default=Concat( 'type', ExtractYear('released_at'), 'number', output_field=CharField() ), output_field=CharField() ) This has worked well so far but the two subtypes are diverging quite drastically now and it would be easier to handle those as subclasses using the polymorphic model. What I'm trying to do is something like this: class Entity: released_at = DateTimeField() number = IntegerField() class EntityA(Entity): type = 'A' class EntityB(Entity): type = 'B' But this removes the type information from the DB and breaks the query expression. Is it possible to set a field's default based on the polymorphic class? The only other alternative I can think of is hiding it from visibility and autopopulating it with the right value on save. Would that be a viable approach or am I missing something? Thanks! -
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 don't want to show the mobile number to everyone. We want to forward the call through us like Indiamart to make this website more safe. Website is developed using React.js and Django. I need to know that so I can integrate this before launch. Website demonstration https://rentyug.netlify.app -
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 for the user instead of hard-coding it. views.py from django.views import generic from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import Distance from .models import Shop longitude = -80.191_788 latitude = 25.761_681 user_location = Point(longitude, latitude, srid=4326) class Home(generic.ListView): model = Shop context_object_name = "shops" queryset = Shop.objects.annotate( distance=Distance("location", user_location) ).order_by("distance")[0:6] template_name = "Home.html" models.py class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) -
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, in series_heatmap return series def series_heatmap(df, *args, **kwargs): idx = df.index col = df.columns assert(isinstance(idx, pd.core.indexe.Index)) … for c in col: assert(df[c].dtype.kind in 'if') dft = df.copy() dft.index = range(len(df.index)) dft.columns = range(len(df.columns)) I get an attribution error module 'pandas.core' has no attribute 'index' Any workaround or alternative for ezhc generating data for for highchart javascript??? thanks in advance -
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. How can I convert that into a queryset of the associated "blog" objects through the foreign key? If I use a value_list Entry.objects.values_list('blog', flat=True) it's just a list of blog ids, not a Blog queryset that I can do further Blog-related queryset operations on. The only way I can think of is something like this: blog_ids = Entry.objects.values_list('blog', flat=True).distinct() Blog.objects.filter(id__in=blog_ids) But I was hoping for something more straightforward or cleaner. -
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 >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) I expected that qs will have two records: >>> qs.count() 2 But when I evaluate it, it returns nine! >>> len(qs) 9 After the evaluation, count starts to return nine as well: >>> qs.count() 9 To ilustrate even more: >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) >>> qs.count() == len(qs) False >>> len(qs) == qs.count() True >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) >>> len(qs) == qs.count() True I have no idea what is causing this "anomaly". What do you think it might be? -
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 programming...epic fail!", "tags": ["django","djongo","list"] } Following is my code: from djongo import models class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField(max_length=1000) tags = models.JSONField() Clearly I am going horribly wrong somewhere. Would be happy if someone pointed me in the right direction. Thanks! -
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 process. The issue is that any attempts at trying to test this endpoint outside of React, I receive a Forbidden: CSRF token missing or incorrect error log in my Django console, meanwhile inside React I just fail to fetch. Here's what I have: Relevant Code views.py def check_url(request, url): headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"} r = requests.get(url, headers=headers) return HttpResponse(status=r.status_code) component.jsx //django crsf token for api const getCookie = (name) => { var cookieValue = null; if (document.cookie && document.cookie !== "") { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = $.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; //handles making api call with the cookie const APIcall = () => { var csrftoken = getCookie("csrftoken"); fetch("http://127.0.0.1:8000/check_url/", { credentials: "include", method: "POST", mode: "same-origin", headers: { … -
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 def upload_image(request): if request.method == "POST": file_obj = request.FILES['file'] file_name_suffix = file_obj.name.split(".")[-1] if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: return JsonResponse({"message": "Wrong file format"}) upload_time = timezone.now() path = os.path.join( settings.MEDIA_ROOT, 'tinymce', str(upload_time.year), str(upload_time.month), str(upload_time.day) ) # If there is no such path, create if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, file_obj.name) file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}' if os.path.exists(file_path): return JsonResponse({ "message": "file already exist", 'location': file_url }) with open(file_path, 'wb+') as f: for chunk in file_obj.chunks(): f.write(chunk) return JsonResponse({ 'message': 'Image uploaded successfully', 'location': file_url }) return JsonResponse({'detail': "Wrong request"}) -
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 not include non-root: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ -
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 to me a logic how to do, yes? I created an app and inside an app I connected urls, settings, html and I have working site. Now I want to input data in django website, django to pass data to xlsxwriter script to create xlsx document, and to pass that document to user to download. My logic: What I need now, is to create some kind forms (but not for registered users, it can use anyone who uses a website) to input data. Which forms are best? Than I need to pass () that data to function that are in views that will get an arguments from html page through some kind of forms, create document, and pass that to download button. -
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 does not display. I want to display image src according to ajax jquery script conditions.Without these conditions image src displays properly but i want to display image source with conditions as mentioned in the code. Here is my code: My html file: It includes my html code with django jinja template {% extends 'layout.html' %} {% block body %} <!DOCTYPE html> <html> <head> <title>Blog</title> <link rel="stylesheet" href="/static/css/blog.css"> <link rel="stylesheet" href="/static/css/create_blog.css"> <link rel="stylesheet" href="/static/css/update_blog.css"> </head> <body> <main> <h1 class="display-4">Dashboard <small> Welcome, {{request.user.username}} </small> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createModal"> Create Blog </button> </h1> {% include 'create_blog.html' %} {% include 'update_blog.html' %} <div class="card" id="card" style="width: 27rem;"> </div> </main> <script type="text/javascript" src="/static/js/blog.js"></script> </body> </html> {% endblock %} ajax jquery script code: It incudes my ajax script code with different file src // Read or Retrieve blog data (this function calls in create, update and delete success messages) read_retrieve_blogs() function read_retrieve_blogs() { var card = document.getElementById('card'); card.innerHTML = '' $.ajax({ url: "http://localhost:8000/user_blogs/", cache: … -
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 wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/kailicen/portfolio/portfolio/wsgi.py WSGIDaemonProcess django_app python-path=/home/portfolio/portfolio python-home=/home/kailicen/portfolio/venv WSGIProcessGroup django_app I also wrote the permission to my project directory: drwxrwxr-x 7 kailicen www-data 4096 Aug 10 06:48 portfolio I don't know what goes wrong. Hope you can help me out. Thanks in advance. -
How can I implement this in my views.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 Data Bytes' | awk '{print $5}'" eth_tx = "cat /proc/net/dev | grep -i eth0 | awk '{print $10}'" eth_rx = "cat /proc/net/dev | grep -i eth0 | awk '{print $2}'" -
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 -
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) { $.ajax({ type: 'POST', url: "...", data: { 'csrfmiddlewaretoken': csrf[0].value, }, ... }) } btn1.addEventListener('click', one) btn2.addEventListener('click', two) So, everything works fine. But when I press a button, it creates a post request and in my URL appears something like ?csrfmiddlewaretoken=randomDigits&symbols=&text= What can I do to don't show csrf in my URL? By the way, I don't want to add method="post" to my form. Maybe there are an obvious solution, but I'm new to Django:) -
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 column "category_id" of relation "APIs_api" violates not-null constraint DETAIL: Failing row contains (1, Twilio SMS, Twilio's Programmable SMS API helps you add robust messaging cap..., Twilio's Programmable SMS API helps you add robust messaging cap..., 1, null). The 1 in this case refers to the User ID. Referencing the category_id seems to be the problem. The category in question is SMS with an ID of 34. So the category_id should be 34, since I have 47 categories. I can't find any solution online as many tutorials have the admin input items from the admin dashboard that have a Category as a Foreign Key. I want to achieve these through a form. I have 2 models, API & APICategory Here is my Models.py from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify class API(models.Model): api_name = models.CharField(max_length=30, default='', unique=True, verbose_name="API Name") short_description = models.CharField(max_length=250, default='', unique=True, verbose_name="Short Description") full_description = models.TextField(default='', unique=True, verbose_name="Full Description") category = models.ForeignKey(APICategory, on_delete=models.CASCADE, … -
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 upload their own. When they upload the photo it works just fine including the profile information. However, if they only edit the profile information after already having their own profile photo and do not change the photo I get a MultiValueDictKeyError and the exception value for 'image' below is my views.. def editProfile(request): if 'user_id' not in request.session: return redirect('/') user = User.objects.get(id=request.session['user_id']) context = { 'user': user, } return render(request, 'editProfile.html', context) # updates edited information on profile and updates new image photo. def updateProfile(request, user_id): userProfile = User.objects.get(id=request.session['user_id']) userProfile.profile.location = request.POST['location'] userProfile.profile.favorite = request.POST['favorite'] userProfile.profile.about = request.POST['about'] userProfile.profile.image = request.FILES['image'] userProfile.save() return redirect(f'/userProfile') this is my models: class User(models.Model): first_name = models.CharField(max_length=45, null=True) last_name = models.CharField(max_length=45, null=True) username = models.CharField(max_length=255, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=45) confirm_pw = models.CharField(max_length=45) objects = UserManager() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE) location = models.CharField(max_length=45, null=True) favorite = models.CharField(max_length=255, null=True) … -
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 to use the remote debugger with rdb it doesn't detect the breakpoint -
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= True , null = True class App(models.Model): name = models.CharField(max_length=250, blank=True, null=True) description = RichTextField(blank=True, null=True) core_asset = models.CharField(max_length=250, blank=True, null=True) country_of_origin = models.ForeignKey( Country, related_name='country_of_origin', on_delete=models.DO_NOTHING) other_countries = models.ManyToManyField( Country, related_name='other_countries',) in admin panel if I want to add more than one country to my new app model I have to hold the control and select those. but I got more than 200 counries and it gets too difficult to add like 10 countries to app. how can I add a checkbox next to the name of the countries . I added this code in my admin panel class AppAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } admin.site.register(App, AppAdmin) but it shows a very long list of coutries with checkbox.(but without scroll) how can I handle m2m field in admin panel if the numbers of models are too many to use cntrl key and pick them. ps: I have to handle this in admin panel. thank's in advance. -
serialize don't show data
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() return comment //////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// model ///////////////////////////////////////////////////////////////////////////// class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") text = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) response_to = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name="comments") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") like = models.ManyToManyField(User, related_name="like", blank=True) ////////////////////////////////////////////////////////////// view ///////////////////////////////////////////////////////////// @api_view(['PATCH']) @permission_classes((permissions.IsAuthenticated,)) def Comment_like(request, comment_id=False): if request.method == 'PATCH': _comment = get_object_or_404(Comment, id=comment_id) user = request.user if user in _comment.like.all(): _comment.like.remove(user) like = False else: _comment.like.add(user) like = True return Response({'like': like, 'likes': LikeSerializer(_comment.like, many=True).data}, status=status.HTTP_200_OK) -
React components not rendering using babel, webpack and django
I've created Django application and integrated React using Babel and Webpack. I've also created components which don't render (when I replaced component with <h1> and typed some text it worked). index.js import React from 'react'; import ReactDOM from 'react-dom'; import Home from './components/Home'; ReactDOM.render( <Home />, document.getElementById('root') ); index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1" > <meta name="theme-color" content="#000000" /> {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}" /> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet"> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> component function Home() { return ( <> <h1>Home page</h1> </> ); } export default Home; -
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 why I want to create a url: After the posts are shared, they will be listed in the index and users will enter and comment on the post. This is the thing that got me in trouble. Model Form URL (I collected the urls in another app called Pages) Views