Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to store mathematical expressions in mysql and then use them
I am using Django and want users to be able to store mathematical expressions like the following in a mysql database following the BODMAS rule: (A / B) * C + D / (E - D) + J^2 Then I want to be able to use these expressions later on in my views. Much like MS Excel. I could build some models that stores as their objects, the variables and operators and build a function to implement BODMAS but it sounds like a lot of complication for a simple task. Is there a simpler, shorter way to do both these steps? -
Unable to makemigrations while using postgres
I am new to pgsql, did not configure this error while I'm trying to makemigration in the Django-rest app. what should I install? I've installed the requirements.txt which consists of : PyJWT==1.7.1 pytz==2021.1 sqlparse==0.4.1 psycopg2>=2.8 psycopg2-binary>=2.8 python_dotenv==0.16 the error: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? -
Best way to copy an attachment file from other's server to your server in Django
I'm importing data from another platform to mine via API they provide. They provide me attachment file URL in response and now I want to save that file on my Django server and use that Django media file URL in my application. So I wanted to know, what is the best way to do this task?? Thanks in advance :) -
Django get other fields value with aggregate function in result
I have query like which is given below todayData = User.objects.filter(log__created_at__date=curDate,og_type='credit').annotate( max_price=Sum('log__bits')).exclude(log__bits=300).order_by('-max_price') through this query i am getting the user which have max count of credit amount after this through this query i am getting the total count of match and user total price newList = [] for user in todayData: highCredit = Log.objects.filter(user_id=user.id,log_type='credit',created_at__date=curDate).exclude( bits=300).aggregate(credit=Sum('price'),match_count=Count('match')) result : print(highCredit) [{'credit': 200, 'match_count': 1}, {'credit': 300, 'match_count': 2}] this is correct but the thing is that i want log table other fields in this variable like log table id with match id how can i get this . i am not getting these values with aggregate. can anyone have any idea please suggest me -
django annotation max min AND first last
From a datatable that stores the BTC price each minute, I'am trying to get an queryset objet that aggregate values by hours (need min, max, first and last). It works well for the max and min class BTCDayDataCandles(APIView): authentification_classes = [] permission_classes = [] def get(self, request, format=None): now = datetime.now() BTCData = BTCminute.objects\ .annotate(test = Trunc('dateTimeEntry', 'hour'))\ .order_by('-test')\ .values('test')\ .annotate(Max('price'), Min('price')) data = { 'BTCData': BTCData, } print(BTCData) return Response(data) How can I add the fist and last price value for each hour in the queryset Object? -
Chained dropdown in Django is not storing data to database(Postgresql)
I am trying to create a chained drop-down in Django that is on selecting country only those states who belongs to the country should come in the drop-down to select.I have used J-Query for drop-down and is working fine. But after sending data from form the form data is coming to console as i have print the form values into the console for better understanding, but is not saving the data to the database and form.is_valid is giving False even if data is correct. Why it is not storing to the database even if the form data s correct models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,AbstractUser class Country_Model(models.Model): country = models.CharField(max_length=50) def __str__(self): return self.country class State(models.Model): country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class StudentsRegistrationModel(AbstractUser): GENDER = (('F', 'Female',),('M', 'Male',),('O', 'Other',)) email = models.EmailField(unique=True) fathers_name = models.CharField(max_length=25) gender = models.CharField(max_length=1,choices=GENDER,default=None) address = models.CharField(max_length=50) country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) state = models.ForeignKey(State,on_delete=models.CASCADE) phone_number = models.CharField(verbose_name="Phone Number",max_length=10) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS=[] form.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from app1.models import StudentsRegistrationModel,State class … -
How to get the Verification code from Django GraphQL Auth
how can I get verification token from this message that prints on the CLI after registering on Django GraphQL Auth? <h3>localhost:8000</h3> <p>Hello a!</p> <p>Please activate your account on the link:</p> <p>http://localhost:8000/activate/{ verification token }</p> -
Django forms with stored procedure in MySQL
I am trying to invoke a stored procedure within a django form. This will fill a select in the template. Apparently it can be called with cursor.execute (), but I can't get it to work. I leave part of the code: class FormX(forms.ModelForm): fieldX = forms.ModelChoiceField(queryset=cursor.execute('SELECT * FROM table'), required=True) -
Can anyone explain How to encrypt a url in Django?
I am going to develop a application in Django. I need to encrypt the url which needs to be decrypted again in business logic. Which module should I need to use.Can any one help me out please.... -
Adding multiple many_to_many from query
I'm going crazy with this problem. So I have a model Template which basically is a template of permissions (when you create a user it will automatically give the good permissions). My model looks like this: class PermissionTemplate(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, on_delete=models.CASCADE) permissions = models.ManyToManyField(Permission, blank=True, related_name='templates') class Meta: default_permissions = () permissions = ( ("can_delete_template", "Can delete a permission template"), ("can_create_template", "Can create a permission template"), ("can_edit_template", "Can create a permission template"), ) constraints = [ UniqueConstraint(fields=['company', 'name'], name='Unique_template_name_per_company') ] def __str__(self): return self.name I'm now writing the tests so in my setupTestData I do this: @classmethod def setUpTestData(cls): templateperms = PermissionTemplate.objects.create(name="Administrators", company=company) perms = Permission.objects.filter( content_type__app_label__in=['authentication', 'company']) templateperms.permissions.add(*perms) print(perms) print(templateperms.permissions) But the result is not as expected the first print will return my queryset well: <QuerySet [<Permission: authentication | permission template | Can create a permission template>, <Permission: authentication | permission template | Can delete a permission template> .... ] But my second print: auth.Permission.None And I don't have the permissions saved in my template If someone have an idea it would be much appreciated -
<embed?> element not able to show pdf preview on safari
My embed element is able to show pdf preview in chrome but not in safari. Can anyone advise on how I can render the embed PDF Preview element on safari? I have tried some of the methods but none worked. Recommended way to embed PDF in HTML? Thank you! <embed src="" type="application/pdf"> -
unable to get groups and permissions working for auth0 user in django admin
I am using Auth0 authentication and allowing the users to login to admin site. How ever, I am not able to get the django groups and permissions to work with these users. The users are getting saved to auth_user table. I am using social_django with auth0. here is a brief of the authentication backends, login, logout urls . # declaring authentication backends for auth0 users AUTHENTICATION_BACKENDS = { 'django.contrib.auth.backends.ModelBackend', 'core.authentication.auth0.Auth0' } ##### Login and Logout Urls and Redirections LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/admin' LOGOUT_REDIRECT_URL = '/login/auth0' # social auth pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'core.authentication.authorization.process_roles', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) if I disable superuser status, staff users are not able to access anything in the admin site, even after assigning to a group. I would like to add users to a group and allow access based on that. Also I haven't created any custom user model on django side to read the users. Should I use a custom user model for auth0 authentication? Any guidance on this front would be really helpful. -
Filter many to many objects from parent queryset
I have 2 models like this class A(models.Model): x = models.CharField(blank=True, null=True, max_length=256) y = models.CharField(blank=True, null=True, max_length=256) class B(models.Model): m = models.ManyToManyField(to=A, blank=True) #other fields class C(models.Model): p = models.ManyToManyField(to=A, blank=True) #other fileds now when i query the objects of model 'B' using query_b = models.B.objects.all() i want to exclude those objects from many to many field 'm' if they exist in models.C.objects.all() and return query_b -
Django - Add block inside an included html
In Django, can we add block content in a included html page? Is it feasible? base.html {% block title %} <p>This is title base.html</p> {% endblock title %} {% include "head.html" %} head.html {% block subtitle %} <p>This is subtitle head.html</p> {% endblock subtitle %} index.html {% extends 'base.html' %} {% block title %} <p>This is title index.html</p> {% endblock title %} {% block subtitle %} <p>This is subtitle index.html</p> {% endblock subtitle %} Final result <p>This is title dashboard.html</p> <p>This is subtitle head.html</p> Meaning, that when we are rendering index.html, it will not find the subtitle block on head.html Thanks! -
How to extract the data from the uploaded file using filesystemstorage in django?
Hi I am learning python I tried uploading a file using FileSystemStorage defualt class that is defualt class in django and the file is uploading but I want to extract the data from the uploaded file that is being stored media folder like name: "soso" age: "so" the code which I tried so far is as below views.py: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage def index(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'index.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'index.html') index.html: {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django - How access the value of an instance in views.py
I have this model class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField(default=timezone.now) content2 = models.TextField(default=timezone.now) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Then I have this simple view function that allows me to access each of its field in my HTML: def home(request): postings = { 'listings' : Post.objects.all(), } return render(request, 'front/front.html', postings) {% for listings in listings%} <h1>{{listings.content}}</h1> {% endfor %} With this, I'm able to access the content field for every instance of that model and display it My question is how can I access the content field in my view function and change it. The content field holds a zipcode and I want to use an API to display the city of that zipcode(which I already know how to do) and pass it back to the h1 tag. Each instance holds a unique zipcode so I need it to apply for each instance. How would I approach this? -
How to use object.id to make another object, creator of the current object?
I have two models in my django application 'Client' and 'Installment'. Below is my models.py: models.py rom django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') and my views.py view.py # To create new client class ClientCreateView(CreateView): model = Client fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment'] # To add new installment class AddInstallmentView(CreateView): model = Installment #template_name = "property_details/addinstallment_form.html" fields = ['installment_month', 'installment_amount'] And the URL that I have to add a new installment is below: urlpatterns = [ path('', ClientListView.as_view(), name='client_list'), path('new/', ClientCreateView.as_view(), name='add_client'), path('<int:pk>/', ClientDetailView.as_view(), name='client_details'), path('<int:pk>/Add-Installment', AddInstallmentView.as_view(), name='add_installment'), path('confirmation/', views.installment_added, name='installment_confirmation'), ] You can see that the URL for adding new installment is unique. For example, /<local_server_addr>/<client.id>/Add-Installment (because of <int:pk> above) I can create a new client and also I can add installment. But … -
How to obtain geo co-ordinates of a remote user in group video chat?
I am building a group video chat application in Django with the help of Agora where I want to show the user their geo distance from every other user. To a given user, the UI would look something like this (along with the video of course) User A - (User A's remote video) - 5 miles away from you User B - (User B's remote video) - 100 miles away from you User C - (User C's remote video) - 10 miles away from you User D (local user - you) Now in the video chat, a user can log off & a new user can join the call any time. To compute the geo distance of a remote user with the local user, I need geo-coordinates of both the parties. I can obtain the geo-location of the local user by integrating with some location library. I am confused on how to obtain the geo-coordinates of the remote user? My django code flow looks something like renders links to views.py ----> video.html -------> agora.js Video.html renders the video chat room. I am using Agora to power the group video chat whose code is defined in agora.js. Any time a new … -
Is there a way to show Django messages in Django admin site?
I need to display a Django message on the Django admin index site. I am looking for a way to add certain conditions for the message to be displayed and pass it to Django index site. Is there a way to achieve that? -
how do i seed some data in to my table , that i have fetched from a specific extrernal api in Django?
so my requirment is i need to fetch some data from a github api and seed it into the table in my django api application. so while the app is running it should always be seeded with that data.. And then i need to make a REST api using that Table data which is already seeded with github api data. im a beginner and i have searched a lot but couldnt find what to do ? i have already created mmy fuction to fetch data and also i have created a model based on my requirment. all i need to know where should i put that code so that it seeds my table when the application runs so that i can create a rest api using that table data .. this is the data fetching code(which i currently have put in view as a function to see if its working) def apiOverview(request): mainarr=[] url = 'https://api.github.com/repos/afhammk/components/contents' try: r = requests.get(url, auth=("afhammk","token")) fish = r.json() for ele in fish: try: desc=requests.get("https://api.github.com/repos/afhammk/components/contents/"+ele["name"]+"/description.txt?ref=main" ,auth=("afhammk","token")).json() content=str(base64.b64decode(desc["content"])) name=content.split("'")[1::2][0] description=content.split("'")[1::2][1] y=Task(component=ele["name"],url=ele["html_url"],owner=name,description=description) y.save() except: mainarr=["cant fetch second url"] except: mainarr=["cant fetch first url"] below is the model i created class Task(models.Model): component=models.CharField(max_length=200) owner=models.CharField(max_length=200) description=models.CharField(max_length=200) url=models.CharField(max_length=200) def __str__(self): … -
how can i get category name instead of the ID
I'm working on a small project using Django Rest Framework, I have two models ( contacts and category) So a contact can be in a category, I have a foreign key between the models, I would like to know how can I get data category name instead of getting the id number. This is my code : class Category(models.Model): cat_name = models.CharField(blank=False, max_length=255) comment = models.CharField(blank=False, max_length=255) private = models.BooleanField(default=False) allowed = models.BooleanField(default=False) def __str__(self): return self.name class Contact(models.Model): category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) My serializer class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = "__all__" Result I get : "first_name": "John", "last_name": "Doe", "category": 1 ( i want to get the name of the category instead of the id ) -
Refused to execute script from 'chunk.js' because its MIME type ('text/html') is not executable,and strict MIME type checking is enabled
i have a django rest framework + reactjs app in frontend , It has deployed successfully in aws, and it's working fine in debug mode, When i change to production: i get these errors: Refused to execute script from '***ff1c1f05.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to apply style from 'https://www.dentistconsultationhub.ai/static/css/main.85597d13.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. can anyone explain to me what mayb be the problem ? cordially -
Django Model Form not saving to database
I have the following ModelForm which when I use as below it is not saving to the database. I have tried other posts and answers on here but cannot get this to save. If I use the same Class Base View (CreateView) and use the input of {{form}} in the HTML I can get this working and it saves to the database, but I need to have the form fields added separately in the HTML page as below that has been created for me with separate inputs. The output of the post prints in the terminal ok, but then as mentioned not to the database. Hope this all makes sense and thanks in advance for any help I can get on this. models.py class ASPBookings(models.Model): program_types = ( ('Athlete Speaker & Expert Program', 'Athlete Speaker & Expert Program'), ('Be Fit. Be Well', 'Be Fit. Be Well') ) presentation_form_options = ( ('Face to Face', 'Face to Face'), ('Virtual', 'Virtual'), ) organisation_types = ( ('Goverment School', 'Goverment School'), ('Community Organisation', 'Community Organisation'), ('Non-Goverment School', 'Non-Goverment School'), ('Other', 'Other') ) contact_name = models.CharField(max_length=80) program_type = models.CharField(max_length=120,choices=program_types) booking_date = models.DateField() booking_time = models.DateTimeField(default=datetime.now()) duration = models.CharField(max_length=10, default="1") email = models.EmailField() phone_number = models.CharField(max_length=120) speaker_brief … -
django 3.1 passing raw column aliases to QuerySet.order_by() is deprecated
I'm working on a project which just moved to django 3.1. And I need to remove the usage of this "passing raw column aliases to QuerySet.order_by()" thing. However, I am not sure if my project is using it. So I need to understand how "passing raw column aliases to QuerySet.order_by()" actually works, if someone could provide me an example of the code that does the passing of raw column aliases to QuerySet.order_by(), it would be really helpful and appreciated. -
Django - Accessing Model Field in class based view
I have this model class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField(default=timezone.now) content2 = models.TextField(default=timezone.now) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) and this function based view that uses the model: class PostListView(ListView): model = Post template_name = 'front/front.html' context_object_name = 'listings' ordering = ['-date_posted'] def get_context_data(self, **kwargs): check_for_zipcode = #where I want to access the author for the current instance context = super().get_context_data(**kwargs) context['zipcodes'] = check_for_zipcode return context All I want to know is how can I access the author field in the class-based view. I can access the author in my HTML like so" {% for listings in listings %} <h3>listings.author</h3> {% endfor %} With this, I'll get back the author field for every instance of that model. How would I get the author for the instance in the variable check_for_zipcode? I tried self.author, self.listings.author, etc; but nothing works