Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Thinkific and multiple login prevention
I recently started using Thinkific and happy about well documented API & Webhook. However, one of the major concern is unable to prevent or monitor 'multiple login access and usage'. Made a request to Thinkific support team for help, no feature so no solution. Can anyone put some light on how to deal with such issue on SaaS platform like Thinkific, is there any middle ware like Django can be used to solve, if so, how to integrate with SaaS like Thinkific? Or is there any other tools can be used - if so please suggest. Any help would be grateful. -
Setting Global Axios Headers in Vue 3
I am trying to use Axios to hit my backend (Django), but I am having some trouble setting my global headers to include the CSRF token in the header. This is reaching my server: import axios from "axios"; async function loadCards() { var instance = axios.create({ xsrfCookieName: window.rootData.csrfToken, xsrfHeaderName: "X-CSRFTOKEN", }); return await instance.post(window.rootData.urlpaths.loadCards, { 'state': props.state.label, 'filter': props.filter.label, 'project': window.rootData.project }) } However, I want these headers to apply to all of my internal api requests. So I thought I would establish them in a separate file: axios-site.js import axios from "axios"; var siteApi = axios.create({ xsrfCookieName: window.rootData.csrfToken, xsrfHeaderName: "X-CSRFTOKEN", }); export default { siteApi } Vue Component import siteApi from "@/axios-site"; setup () { async function loadCards() { return await siteApi.post(window.rootData.urlpaths.loadCards, { 'state': props.state.label, 'filter': props.filter.label, 'project': window.rootData.project }) } } Here is the error in console: Uncaught (in promise) TypeError: _axios_site__WEBPACK_IMPORTED_MODULE_4__.default.post is not a function at _callee$ (ActionColumn.vue?ba4f:97) at tryCatch (runtime.js?96cf:63) at Generator.invoke [as _invoke] (runtime.js?96cf:293) at Generator.eval [as next] (runtime.js?96cf:118) at asyncGeneratorStep (asyncToGenerator.js?1da1:3) at _next (asyncToGenerator.js?1da1:25) at eval (asyncToGenerator.js?1da1:32) at new Promise (<anonymous>) at eval (asyncToGenerator.js?1da1:21) at _loadCards (ActionColumn.vue?ba4f:80) It seems something is being lost when I run it through the external file. I'm sure I … -
django rest api serializer cant update a nested serializer
I created two model named office and phone that phone save the office phones (each office can have several phone number) for working with this two model I created a nested serializer and two generic view shown in below in pictures one for post and get request and the other one for put delete and retrieve I don't have problem in post ,get ,delete ,retrieve but in case of update cant update phone numbers how can I update the phone number??? image of office and phone model image of office and phone serializer image of office views -
how to map user model to customer model (Django)
I'm using Django as backend, PostgresSQL as DB and HTML, CSS, Javascript for Frontend. I stuck on mapping the User with Customer model. Error: I get "null value in column "user_id" of relation "product_cart" violates not-null constraint" when I try to map user with Customer Model in Django. What I'm trying do: When customer visit my website and choose the product then customer click the ADD button to put that product into cart. But while clicking user get error as above. So I deleted that code, And I try to do something else like this Question link here. But didn't help me. I'm failing to link the customer model with the user. Please do help me to get out with this problem. The Code goes here. account/views.py (User Registration) def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') htmly = get_template('account/email.html') d = { 'username': username } subject, from_email, to = 'welcome', 'your_email@gmail.com', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() messages.success(request, f'Your account has been created ! You are now able to log in') return redirect('account:login') else: form = UserRegisterForm() return render(request, 'account/register.html', {'form': form, … -
Display crypto price in a table using django and cryptocompare
I'm trying to make a simple webpage in django where I can display the price of some cryptocurrencies. The user stores in the database the name of the crypto and its initial price. Then I want to fill a table with the ticker and the initial price taken from the database and the current price of each crypto taken with cryptocompare. This is where the problem begin: the value of 'current price' is taken using cryptocompare, but how can I dinamycally display the value of the current price of each crypto in the table? Maybe the problem is easy to solve but I'm really new and I'm stuck, thanks in advance! If you need more information ask me! This is how the table in the index look like. I need to fill the last column with the daily price of the crypto models.py from django.db import models # Create your models here. class crypto(models.Model): ticker = models.CharField(max_length=200) initial_price = models.FloatField() def __str__(self): return self.ticker views.py from .models import crypto def index_view(request): chart = FuncAnimation(plt.gcf(), animate, interval=1000) ticker_list = crypto.objects.all() return render(request, 'cryptochart/index.html', {'chart': chart, 'ticker_list': ticker_list}) and last, in a file called utils.py I wrote the functions to get the … -
Django get sub domain from which the request was sent from
i have a standalone front ends serving on different sub domains, and a single backend responding to all requests through API(s) Say i have following subdomains first.example.com second.example.com third.example.com and my backend is at backend.example.com in my backend views i want to know which subdomain sent me request i tried self.request.get_host().split('.')[0] but this gave me "backend" as result from every sub-domain what i want to have : if request was sent from first.example.com > in my backend.example.com view i want to have "first" if request was sent from second.example.com > in my backend.example.com view i want to have "second" and so on Technologies information: Subdomains using React Backend using Django Server Nginx other server Gunicorn -
Django/Python - Save file from command output to ImageField
at my models.py I have a ImageField cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) I need to save an Image to this field the following command outputs (preferably only saved in RAM): ffmpeg -i "path_to_my_mp4_file" -map 0:v -map -0:V -c copy cover.jpg Can smb. Help? Thanks in advance -
How to save user that created and modified a record in django admin site?
I have a ReportModel in my django app with 2 field create_user (represents the user that created the report) and write_user (represents the user that last modified the report). I want to automatically save that two fields according to the user that is logged in on django admin site . How do I do that? Here is the definition of the model class ReportModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False) location = models.PointField(verbose_name=_("Localización"), srid=4326, blank=False, null=False) report_type_id = models.ForeignKey("ReportTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="reports") start_date = models.DateField(verbose_name=_("Fecha inicio")) end_date = models.DateField(verbose_name=_("Fecha fin")) create_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Creado por'), editable=False, null=True, blank=True) write_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Modificado por'), editable=False, null=True, blank=True) def __str__(self): return self.name -
How to dynamically create and close infinitely running Celery tasks using Django Channels
I am creating a Cryptocurrency application where users get real-time data of currency pairs (e.g. 'BTC/USD'). I am trying to set up a system where users subscribing to the same pair can share API calls. So far I can dynamically create websocket connections and users are added to the groups. # routing.py URLRouter([ path('ws/data/<pair>/', PriceFeedsConsumer.as_asgi()), ]) # consumers.py class PriceFeedsConsumer(AsyncWebsocketConsumer): async def connect(self): self.pair = self.scope['url_route']['kwargs']['pair'] self.pair_group_name = 'pair_group_%s' % self.pair await self.channel_layer.group_add( self.pair_group_name, self.channel_name ) await self.accept() ... I have set up redis as the broker service and celery as a task manager system. I know how to send data from celery tasks to the consumer groups, but I want to begin the tasks when a group is created, and ultimately close the task when the group is discarded. This seems to be the most efficient way to manage API calls. Is it possible to initialize celery tasks from the creation of a django group? And in doing so, pass a parameter (pair, in this case) to the celery tasks? Alternatively, is this the correct architecture for this type of problem? -
A form field is None in django and has an initial value
Hello I have this django's form: class userRequest(forms.Form): def __init__(self, *args, **kwargs): super(userRequest, self).__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Origin'}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Origin'}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Dest'}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Dest'}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'destination_address'})) date=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id'})) maxPrice=forms.FloatField(label='Max price:',widget=forms.NumberInput(attrs={'class':'data_aux data order','step': '0.1'}),required=False) CHOICES_ORDERTYPE =( ('NONE', 'NONE'), ('ASC', 'ASC'), ('DESC', 'DESC'), ) OrderType = forms.ChoiceField(label='Order',choices = CHOICES_ORDERTYPE,initial='NONE',required=False,widget=forms.Select(attrs={'class':'data order'})) CHOICES_ORDERBY =( ('PRICE', 'PRICE'), ('DURATION', 'DURATION'), ) OrderBy = forms.ChoiceField(label='Order by',choices = CHOICES_ORDERBY,initial='PRICE',required=False,widget=forms.Select(attrs={'class':'data order'})) And When I print the form in the post method I obtain that lat_Origin, lon_Origin, lat_Dest and lon_Dest are None: if request.method == 'POST': form = userRequest(request.POST) if form.is_valid(): print(form.cleaned_data) else: form = userRequest() {'lat_Origin': None, 'lon_Origin': None, 'lat_Dest': None, 'lon_Dest': None, 'origin_address': 'Lugar Diseminado, 82, 45312 Cabañas de Yepes, Toledo, España', 'destination_address': 'Calle San Roque, 28, 50324 Santa Cruz de Grío, Zaragoza, España', 'date': datetime.date(2021, 6, 12), 'maxPrice': 0.5, 'OrderType': 'NONE', 'OrderBy': 'PRICE'} I don't know how to fix this problem. Thank you -
Django ORM, Q statements and customized sorting
I am simplifying this for clarity. Let's say I had this function that finds Document records based on a requestedColor. def find_docs(requestedColor): docs = Document.objects.filter(Q(color=requestedColor) | Q(other_color=requestedColor)) I'd like to order the results so that Document found using color will appear before objects found with other_color. Is there a way to do this within the ORM query? I could not find a way to do that. Pointers will be appreciated. -
When running docker-compose, I get a permission error
I am new to deployment using docker so I believe that I am missing something vital here. I am trying to launch my app using docker/nginx and I have gotten to a stage where I am able to run the dev-environment as a container, but when I go to run the yml that I would use for deployment I get a PermissionError: [Errno 13] Permission denied: 'app/vol' Error. That is to say I can run docker-compose -f docker-compose.yml up --build and that provides me access to my app in the dev environment, but running docker-compose -f docker-compose-deploy.yml up --build causes the shown error message. This is from following along a tutorial online but adding extra dependencies and content to the Django project. I have made a version identical to the tutorial and that works, and when I check what I have against that version, nothing seems to differ. Any help would be massively appreciated. Terminal Error Output: proxy_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration proxy_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ proxy_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh proxy_1 | 10-listen-on-ipv6-by-default.sh: info: can not modify /etc/nginx/conf.d/default.conf (read-only file system?) proxy_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh proxy_1 … -
DRF: What is the difference between serializer.save() in views.py vs instance.save() in serializers.py
I am confused regarding the DRF Serializer Documentation: For serializers, it was mentioned that, If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this: def create(self, validated_data): return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance From serializers.py code, it seems that .save() will update the instance in the database. However, it was later mentioned, Now when deserializing data, we can call .save() to return an object instance, based on the validated data. comment = serializer.save() Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance. serializer = CommentSerializer(data=data) # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) It seems that calling serializer.save() in views.py will update the 'comment' instance in the database. Calling instance.save() in serializers.py will also update the 'comment' instance in the database. My question is if there is a difference between the … -
How can I redirect to another page when someone send something back to me via callback url
Is there anyway to get the callback url parameter in current page? For example, currently I am in pageA, pageA have a qr code. When I scan the qrcode, another API partner will send back an authorization code as a parameter in my callback url. So how can I redirect to pageB when API partner send back an authorization code to my callback url? -
Django filter that also grabs a reverse ForeignKey, or better way to combine associated database info?
I am working on some backend django work that requires me to grab an Employee by filtering, but I also need to grab the EmployeeAddress object that is associated to the Employee. I was wondering if this was possible within a single query. I need the employees address, and employee info to be in a combined single dictionary, to access on the front end side with JS. I have models as such, Class Employee(models.model): first_name last_name email Class EmployeeAddress(models.model): employee = models.ForeignKey(Employee): street city state I have a view, that kinda does the job, but having trouble merging merging the two separate QuerySets into a single listed dictionary with all values. I was hoping there was just a way to get the EmployeeAddress without even writing the second query, and just grabbing that associated data in the first employee_list query? def employee_ajax_list(request): email = request.GET.get('email', None) employee_list = Employee.objects.filter(email=email) employee_address = EmployeeAddress.objects.filter(employee_id__in=employee_list).values( 'street', 'city', 'state',) # this chain kinda works, but splits them into 2 separate dictionaries? employee_info = list(chain(employee_list.values(), employee_address)) data = { 'employee_list': employee_info } return JsonResponse(data) Just looking on some advice to make this work a little smoother! -
request.POST.get('submit_target') empty
When i work with django form i use in my view request.POST.get('submit_target') to do something on variable if they are submitted. But when i use a HTML form i can't do that and request.POST.get('submit_target') is empty? it does not pass in if $(document).ready(function(){ console.log('fichier js ok'); $('.form_norefresh').submit(function(e){ e.preventDefault(); // avoid to execute the actual submit of the form. var post_url = $(this).attr("action"); var request_method = $(this).attr("method"); var form_data = $(this).serialize(); $.ajax({ url : post_url, type: request_method, data : form_data, }).done(function(resp){console.log('Submission was successful')}); return false; }); }) def accueil(request): if request.method == 'POST': if request.POST.get('submit_target') : import GV GV.target = request.POST.get('Key_target') if request.POST.get('submit_target'): import GV GV.weight = request.POST.get('Key_weight') return render(request, 'base.html', locals()) Target : <form class="form_norefresh" id="form_target" action="{% url 'accueil' %}" method="POST"> {% csrf_token %} <select name="Key_target" id="Key_target"> {% for column in columns_list_target %} <option> {{ column }} </option> {% endfor %}} </select> <input type="submit" name="submit_target" class="btn btn-primary" value="ok"/> </form> Weight : <form class="form_norefresh" id="form_weight" action="{% url 'accueil' %}" method="POST"> {% csrf_token %} <select name="Key_weight" id="Key_weight"> {% for column in columns_list_weight %} <option> {{column}} </option> {% endfor %}} </select> <input type="submit" name="submit_weight" class="btn btn-primary" value="ok"/> </form> -
Save page data after GET request?
Here is a GIF explaining the problem. Queries to the database are made with GET requests. When I make a GET request to pull additional data, all the checkboxes get unchecked. How can I save the checkbox state (session data, local storage) after those GET requests? -
Fastest way to get a not required specific record in database using Django
What would be the fastest way to get a specific record, that can or cannot exists, using Django. Some possible approaches: results = ModelExample.objects.filter(label="example1") if(results.exists()) item = results.first() results = ModelExample.objects.filter(label="example1") if(len(results) > 0) item = results.first() -
filter staff user in combo box in django admin
i want to show only staff user in combo box django admin how i most do it. Article(models.Model): author = models.Foreignkey(User) ... # other fields I want only staff use show in django admin combo box. -
Trouble with hosting a django app on digital ocean
When I visit http://[ip address], I get a 502 bad request error. /etc/systemd/system/gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=mainuser Group=www-data WorkingDirectory=/home/mainuser/Personal_Web ExecStart=/home/mainuser/Personal_Web/vr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myapp file: server { listen 80; server_name [ip address]; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/mainuser/Personal_Web; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When I run sudo tail -F /var/log/nginx/error.log, I get a connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream error. Im not sure why im getting this or how to fix it? -
Which should i choose? [closed]
I am learning beginner python from youtube. I want to develop a simple website or a web app. Which of the two, Django or Flask should I choose after learning python? ps: I am pursuing a beginner course on youtube -
Reverse lookup on a Django asymmetric 1:N relationship
In Django, what is the query manager associated for reverse lookup of a 1:N relationship? Let's say I have a simple Django model: class Entity(models.Model): name = models.CharField(max_length=100, primary_key=True) score = models.IntegerField(default=0) parent = models.ForeignKey("self", null=True, default=None, on_delete=models.CASCADE) and a few objects defined as follows: a = Entity.objects.create(name="A", score=5) b = Entity.objects.create(name="B", score=10, parent=a) c = Entity.objects.create(name="C", score=11, parent=a) If I want to find out all entities that have a score of less than 10, or any entities that have a parent whose score is less than 10, it is easy: Entity.objects.filter(Q(score < 5) | Q(parent__score < 5)) The above will match exactly one entity, "a", as expected. However, if I want to know all top-level (parent == None) entities whose score is more than 10, or who have children whose score is more than 10, how do I define the query? Entity.objects.filter(parent=None).(Q(score > 10) | Q(?__score > 10)) I need the matched answer to be the parent, not the child (and I need a queryset so I can refine it as needed). And if I exclude the non-parent entities then I cannot figure out the query to write. What should I write in place of the ? above so … -
django: needs to have a value for field "id" before this many-to-many relationship can be used
When saving a new entry into a Issue model for field cylinder, Django throws ValueError: "<IssueCylinder: anyone>" needs to have a value for field "id" before this many-to-many relationship can be used. I understand this is because I need to save the first model before I can use the id of the new record in the second model, but I’m struggling with how to actually make it do this. I’ve looked at examples but I can’t really relate them to my models. Your help will be nice for me. Here are that codes: views:- def issue(request): form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): confirm=form.save(commit=False) confirm.save() form.save_m2m() return redirect(cylinderListView) return render(request,'cylinderentry_form.html',{'form':form}) models: class CylinderEntry(models.Model): substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued'), ] cylinderId=models.CharField(max_length=50,primary_key=True) Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ManyToManyField('CylinderEntry') userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) form: class IssueForm(forms.ModelForm): class Meta: model=IssueCylinder fields=['cylinder','userName','issueDate'] cylinder= forms.ModelMultipleChoiceField( queryset=CylinderEntry.objects.all(), widget=forms.CheckboxSelectMultiple ) userName=forms.CharField() issueDate=forms.DateInput() -
Python/Django string too large for String.io?
I am writing a small Django application in which I want to upload a file and use a parser to analyze this file. Unfortunately, files up to a certain size (don't know exactly the limit, but >3Gb anyway) can be parsed, but at a certain size the application just stops and crashes. I expect the program to be able to parse files up to 20 Gb. Here my code: import io def webinterfaceViews(request): context = {"graph": ""} if request.method == "POST": inputForm = BasicInputDataForm(request.POST, request.FILES) if inputForm.is_valid(): try: inputFile = request.FILES['file'].read().decode('UTF-8') streamInputFile = io.StringIO(inputFile) processInputfile(streamInputFile) ... The program never reaches the processInputfile function and returns no error when it is crashing. I am using the io.StringIO() function, because I use another package within the processInputfile function which uses a parser for these kind of files, but only parses files and not strings. So is there a way to fill the io.StringIO() with large strings or do I need to parse the large string myself without using an external parser? Or is there a problem with Django? -
Django CSRF error: is it a symptom or a root cause?
This is more sharing experience rather than a question. So, it might happen for Django to throw a CSRF error accompanied by a 403 Forbidden code. There are numerous posts out there suggesting more or less to add some sort of exception/exemption for the CSRF token/cookie. From my experience though, the CSRF error it is just a symptom and not the root cause. What can be the root cause? This error occurs even before executing any view code. Therefore, there is a high chance it is an API issue. You API path might not be correct. For example, you might ask for /api/x/data/ from the front-end whereas in reality the corresponding back-end api is /api/x/y/data/. I wish Django could throw a better error message. Feel free to share you experience w/ this error.