Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to compare 2 fields in django 2.1?
Models.py This is my model class where i have 2 tables .on each table we have a field called label.My question is that how will i compare the 2 labels and return values to a new field (returnlabel) class Server(models.Model): label = models.TextField(max_length=200,null=True) #compare this upload1 = models.FileField(null=True, blank=True) Image1 = models.TextField(upload1, null=True) class Android(models.Model): label=models.TextField(max_length=200,null=True) #with this imagestring=models.TextField(null=True,blank=True) returnlabel=models.TextField(null=True,blank=True) #return to this Serializers Class class FoodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model=Server fields=('url','label','Image1','upload1') class AndroidSerializers(serializers.ModelSerializer): class Meta: model = Android fields = ('label', 'imagestring', 'returnlabel') Views class FoodViewSet(viewsets.ModelViewSet): queryset = Server.objects.all() serializer_class =FoodSerializers class Androids(viewsets.ModelViewSet): queryset =Android.objects.all() serializer_class = AndroidSerializers -
Single javascript controller for a audio files generated through loop in Django
I am trying to find a way to have a single javascript controller so i could play the audio files that were shown on the list using a loop in my django app : <script type="text/javascript"> {% for m_word in movie_vocab %} ## here i could generate the ids for each instance of movie_vocab {% endfor %} {% for b_word in blog_vocab %} ## here i could generate the ids for each instance of blog_vocab {% endfor %} {% for e_word in event_vocab %} ## here i could generate the ids for each instance of blog_vocab {% endfor %} var music = document.querySelectorAll([here i could have a list of ids so i can play and pause them ]) function play() { if (music.paused) { music.play(); pButton.value = "Pause"; pButton.className = "btn btn-primary"; } else { music.pause(); pButton.value = "Continue"; pButton.className = "btn btn-light"; } } </script> Hopefully this kind of solution could also pause a previous audio when i would click on the different button Is it possible to do sth like that in javascript ?? -
Program hangs after docker-compose up command for django app
I am trying to run a simple django app through a docker container, using docker-compose. Everything works perfectly down to when I insert the commands 'docker-compose up', which then performs system checks, has no issue, but then hangs. -
Django-Import-Export to import CSV, how to work with u'\\ufeff, UTF-8 BOM issue?
When I'm trying to import CSV file using django-import-export modules gives this error, KeyError: u"Column 'id' not found in dataset. Available columns are: [u'\ufeffid', u'username', u'name', u'email']" -
How to get current user in forms.py def save(self)?
How to get user logged in def save(self, commit=True) at forms.py. I tryed self.request.user, but doesn't work...self doesn't have request :/ Can anyone help me? -
Django deploy Gunicorn and NginX
While trying to finally deploy my NEW rover web app a problem occured. I already configured Gunicorn and bind it to 0.0.0.0:80 (with wsgi). Website loads, but without any images, css, javascript files (even "admin" site is without any style). Postgres is installed and running fine. I already did python manage.py collectstatic python manage.py migrate I watched tons of tutorials how to do it. But still after I try to run: systemctl status nginx.service i get an error: Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details. #systemctl status nginx.service output: ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since śro 2018-11-28 02:57:12 CET; 1min 13s ago Process: 14721 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=2) Process: 25481 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=1/FAILURE) Process: 25477 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 10279 (code=exited, status=0/SUCCESS) nginx[25481]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) nginx[25481]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) nginx[25481]: nginx: [emerg] … -
Using {{ form.media }} for multiple forms is causing jquery to be loaded multiple times?
I am restoring an old Django project and noticed I was getting a console error when I loaded a page: TypeError: $(...).select2 is not a function. After some searching on the internet I found that the error could be related to Jquery being loaded more than once. So I looked at the rendered source for all of my pages and saw that where ever in my template I use {{form.meda}} it adds all of these scripts in: <link href="/static/admin/css/vendor/select2/select2.css" type="text/css" media="screen" rel="stylesheet" /> <link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet" /> <link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet" /> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/vendor/select2/select2.full.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> Keep in mind that I have multiple forms in other templates and use {{form.media}} all over. I didn't realize it all of those scrips were being added each time for every {{form.media}} and I feel it might be causing problems. I am also using Django Autocomplete-light (dal) for some of my form widgets and notice that it also is not working. Is it normal to have all of those scrips added from form.media? Why would it be adding /static/admin/js/vendor/jquery/jquery.js multiple times (or at all) … -
Django Rest Framework : Authentication credentials were not provided
Images in the current database have one piece of data. But, I am currently experiencing the following error "GET /images/all/ HTTP/1.1" 401 58" "detail": "Authentication credentials were not provided." My Git Hub URL : https://github.com/Nomadcoders-Study/Nomadgram Which part of the setup went wrong? -
Breadcrumbs Django python
Can any one help me in creating breatingcrumbs dynamically for Django 2.1versions.i have tried so many plugins but am getting the errors in plugin code itself.. Pl help me. Waiting for the response -
Displaying different Django forms at different template locations
I have a model like this: models.py from django.db import models class Foo(models.Model): text = models.TextField() Example instances of this model are: Foo.objects.create(text="My first text [[@shorttext_1@]] random text.") Foo.objects.create(text="Select something from below [[@multipleselect_1@]]. text.") Foo.objects.create(text="A different form [[@shorttext_1@]] and another" "form [[@shorttext_2@]] random texts.") Foo.objects.create(text="Mixed form [[@shorttext_1@]] and another" "form [[@multipleselect_1@]] random text.") The values [[@shorttext_1@]], [[@multipleselect_1@]] represent the location and the type of the forms to be placed in the template below. [[@ @]] is a randomly chosen markdown style placeholder. forms.py from django import forms class ShortTextForm(forms.Form): # [[@shorttext_1@]] form short_text = forms.CharField(max_length=300) class MultipleSelectionForm(forms.Form): # [[@multipleselect_1@]] form selection = forms.ChoiceField( choices=[('A', 'A text'), ('B', 'B text')], widget=forms.RadioSelect()) views.py from django.shortcuts import render def text_view(request): if request.method == 'POST': # get the info for each form else: foo = Foo.objects.order_by('?').first() return render( request=request, template_name='templates/index.html', context={'text': foo.text}) templates/index.html {% extends "base.html" %} {% block body %} {{ text }} {% endblock %} Is it possible to show the foo.text in template and render the desired forms? Currently, I have a type variable in my Foo class to designate the type of the form. And my view can render only one desired type of form which can only placed at … -
Encrypt InMemoryUploadfile and save the encrypted file on disk
I searched for different solution for encryption for user uploaded file. All of the tutorials or solution which i found where about opening an existing file on the disk encrypting it and and saving it to the disk. I am trying to encrypt the user uploaded file with out saving the original file and directly saving the encrypted file. Right now user upload > save to disk > open the file > encrypt it >save the encrypted file > delete the original file i am doing this now. -
Update database column if other specific column matches variable
I'm in process of creating a script for my django server that updates a database column named TaskStatus if data from myVariable matches the data stored in my other column named TaskID. Something like a loop that updates every single row, one after one. if myVariable and TaskID matches Update TaskStatus with mySecondVariable I know Django has a exist() function so I assume that should be incoorporated into the script. -
How to generate PDF for a single object in Django Admin?
Greetings mighty community of stackoverflow! Thanks to relevant questions here, I managed to figure out how to get every object of a model with Invoice.objects.all() feeded to an html template pdf.html and then converted to PDF via xhtml2pdf and io. I am able to feed in data of a single object manually , putting Invoice.objects.get(pk=1) and removing the jinja {% for invoice in invoices %} {% endfor %}. Previosly I was able to make a column with clickable link for every object in admin (for a different model) which takes the value from object attribute. This is how it was achieved: from django.utils.html import format_html class SipAccountAdmin(admin.ModelAdmin): list_display = ('sip_no', 'show_phone_url') def show_phone_url(self, obj): return format_html("<a href='{url}'>{url}</a>", url=obj.sip_account_ip) show_phone_url.short_description = u'Web interface' However, I do not understand how to create a column in admin view with clickable link in a manner as described above, for this Invoice model on every object to generate PDF using the render method. P.S. It may be that the approach is fundamentally incorrect and the task can be achieved way more elegantly. I apologize in advance , because I am new to django and coding as well as it is a first post here... P.P.S. … -
How to validate signature on the token on SPA using Azure and Django?
I am trying to use Microsoft Outlook mail API in our web application. Followed this tutorial https://docs.microsoft.com/en-us/outlook/rest/javascript-tutorial first, but some important thing is skipped in it. [Skipped part] https://docs.microsoft.com/en-us/outlook/rest/javascript-tutorial#using-the-id-token This sample won't do all of the required validations listed in the OpenID spec. Most notably, it won't validate the signature on the token. Currently requesting the signing keys from Azure would require a server-side component, so we'll skip that step for the sake of simplicity. However, production apps should not skip this important step! In the example code: // Per Azure docs (and OpenID spec), we MUST validate // the ID token before using it. However, full validation // of the signature currently requires a server-side component // to fetch the public signing keys from Azure. This sample will // skip that part (technically violating the OpenID spec) and do // minimal validation I have a server-side component created with Django, but I'm not sure how to fetch the public signing keys from Azure. The actual feature I am implementing is sending email via HTML form. I chose to implement this feature on client-side due to several reasons. It's working and I'd like to make authentication secure before deployment. Just … -
Running two Django projects on one droplet with Gunicorn and Nginx
I've exhausted myself trying to solve this, I hope I can get some help I wish to host two Django projects on a single DigitalOcean droplet. I can host one site with no problem after following this guide but I just cant figure out a way to make this work with two sites. Currently example.com works, and example2.com has the problem that it is Using project1 settings module - project1.settings. I need it to use project2.settings nodule from his project directory and I've no idea how to do this. My gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target My gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=rain Group=www-data WorkingDirectory=/home/rain/rv/project1-web ExecStart=/home/rain/rv/rv-env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project1.wsgi:application [Install] WantedBy=multi-user.target I figured there should be a second service file for the other project so I created project2.gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=rain Group=www-data WorkingDirectory=/home/rain/rv/project2-web ExecStart=/home/rain/rv/rv-env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project2.wsgi:application [Install] WantedBy=multi-user.target My nginx sites-available file: server { server_name example.com; charset utf-8; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rain/rv/project1-web; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 … -
How to "autodiscover" a different location for the admin.py file?
I think it makes sense to organize my Django apps in a different way (by protocol): 📂myapp apps.py models.py utilities.py 📂html admin.py urls.py views.py 📂rest serializers.py urls.py views.py 📂graphql etc This would move the admin.py file into the rest folder, but sadly autodiscover does not seem to find it anywhere else than in the myapp folder. Is there a way to point to the correct location: perhaps in apps.py? I am sure a symlink would work, but not really what I am after. -
evenly spaced, horizontal radio buttons with labels underneath
For a user form I need several likert items. (Questions to assess the degree of an opinion. Example at the bottom) I'm required to use the oTree library, which heavily builds on django. A solution that deviates from oTree as little as possible is desirable. The RadioSelectHorizontal widget seems like the obvious choice here. But two differences to the default are mandatory: the option labels ("agree", "neutral", etc.) have to be positioned just underneath the radio buttons. the radio buttons have to be evenly spaced. (Ideally, they are aligned across the entire page) In contrast, the default look will have the labels between the radio buttons and allow only as little space as each label needs: The code: question_1 = models.IntegerField(widget=widgets.RadioSelectHorizontal, label="some question", choices=[[1, "strongly disagree"], [2, "disagree"], [3, "neutral"], [4, "agree"], [5, "strongly agree"]]) How can I approach this? django documentation mentions several approachs, i.e. custom widgets, custom CSS and more. But as far as I can tell, oTree is a bit more limited than django. For illustration an example that meets both requirements: -
Validate a form field in django with a default value
I'm here working with django and I'm having some problems to validate my login form. I want the text areas to appear with a default value, only for esthetic, and then I want to write the real username. The problem is that, I don't want the default value to be admitted, because it is not a correct username. Same with the password. I post here my code: forms.py class AutenticacionForm(forms.ModelForm): class Meta: model = User fields = ['username','password'] widgets={'password': forms.PasswordInput(),} def __init__(self, *args, **kwargs): super(AutenticacionForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = None self.fields['username'].label = "" self.fields['username'].widget.attrs.update({'required':'true','data-html':'true', 'value':'USUARIO', 'onfocus':'this.value="";', 'onblur':'if(this.value == ""){this.value = "USUARIO";}'}) self.fields['password'].label = "" self.fields['password'].widget.attrs.update({'required':'true','data-html':'true', 'value':'PASSWORD', 'onfocus':'this.value="";', 'onblur':'if(this.value == ""){this.value = "PASSWORD";}'}) That's the way my form looks. USUARIO is just a default value, so I don't want the login to admit that value as correct. -
Django middlewre to catch exceptions
I am trying to create a Django middleware that checks whether the view raised an exception. I am trying with the login form but I cannot raise an exception. Could you give some example of how could there be an exception when the user tries to login? And how to process that through custom middleware. In the end I want to store these exceptions in the database. -
Django Return File and Template
I currently have a view that just returns a word document once the form is submitted. The page/template doesn't change at all. def form_view(request): context = dict() if request.method == 'POST': #do a bunch of things http_word_response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') http_word_response['Content-Disposition'] = 'attachment; filename=%s' % filename doc.save(http_word_response) return http_word_response else: return render( request, 'mysite/form.html', context) I'd like to have it so it return the document like it does, but then update the page from my context dictionary. I know how to return the variables into my template, but I'm having trouble combining it with returning the document. I tried adding this: return render(request, 'mysite/form.html', context, http_word_response) instead of return http_word_response but it returned a document that has literally my entire html template file and did not return the word document. I'm not against returning a URL or link to download the file if that's what is needed, this way has just always been the easiest since it doesn't save anything on the server side. -
Retrieving Records from oauth2_provider_grant table in Django Oauth Toolkit
How do I retrieve records from the oauth2_provider_grant table? Does Django Oauth Toolkit provide the functionality to do this? Thanks in advance. -
Bound form without template variable {{ form }}
This is my view. def edit_listing(request): if request.method == 'POST': form = edit_listingForm(request.POST) if form.is_valid(): new = form.save(commit=False) new.owner = request.user new.save() return render(request, 'dashboard.html') return render(request, 'edit_listing.html') elif request.method == 'GET': return render(request, 'edit_listing.html') I want the form to be returned bound with data if form is not valid. Following is the ideal solution for this #..... return render(request, 'edit_listing.html', {'form':form}) .....# But the problem is I don't have form variable in template. I designed the form with pure html for customization. Is it possible to bound the form without {{ form }} variable ? If yes then how can I do it ? -
Logging out with Python Social Auth
I have seen multiple questions about this problems but none of the solutions offered worked for me. I need to log my user out. my current code looks like this {% if user.is_authenticated %} <a class="nav-item nav-link">{{ user.email }}</a> <form action="{% url 'social:disconnect' 'google-oauth2' %}" method="get"> {% csrf_token %} <button type="submit" class='nav-item nav-link btn btn-md btn-danger ms-auto' > Log out </button> </form> {% else %} <a class="nav-item nav-link" href="{% url 'social:begin' 'google-oauth2'%}"> <img id="signInButton" src="{% static 'generator/btn_google_signin_dark_focus_web.png' %}" onclick="document.getElementById('signInButton').src={% static 'generator/btn_google_signin_dark_focus_web.png' %}"> </a> {% endif %} I get this error when I attempt to do so: NotAllowedToDisconnect at /disconnect/google-oauth2/ No exception message supplied Request Method: POST Request URL: http://127.0.0.1:8000/disconnect/google-oauth2/ Django Version: 2.2 Exception Type: NotAllowedToDisconnect Exception Location: /home/romeo/anaconda3/lib/python3.7/site-packages/social_core/pipeline/disconnect.py in allowed_to_disconnect, line 7 Python Executable: /home/romeo/anaconda3/bin/python3 Python Version: 3.7.0 Python Path: ['/home/romeo/Desktop/schedule_generator', '/home/romeo/anaconda3/lib/python37.zip', '/home/romeo/anaconda3/lib/python3.7', '/home/romeo/anaconda3/lib/python3.7/lib-dynload', '/home/romeo/anaconda3/lib/python3.7/site-packages'] Server time: Tue, 27 Nov 2018 20:38:39 +0000 -
Group of chains hanging forever in celery
I am trying to build the following workflow in celery: (chainA) task1 -- task2 -- task3--| | (chainB) | (group) task1 -- task2 -- task3--|------------- | (chainC) | task1 -- task2 -- task3--| . . . I end up with this code: list_chains = build_s_chains() group(*list_chains)() The moment the line group(*list_chains)() is executed everything stops and halts. Seems like a deadlock, no error thrown. If I try to execute the chains in for loop everything works just fine, but if I execute them in a for loop I can connect another task at the end of the for loop. I know that that is the definition of chord, I tried chord as well, it is still blocking. Checked my rabbitmq and backend result, everything seems fine since I can run the chains manually. It seems to me that this should be straightforward but I can not see the reason why it isn't working. Any help is appreciated chainA for example looks like this: job_chain = ( process_task.s(chip_measurement_object.raw_result_ref, process_args, process_args['file_path'], process_args['meas_data'], process_args['marker_data'], process_args['session'] ) | update_marker_data.s() | plot_task.s(chip_measurement_object.id) | grade_task.s(chip_measurement_object.id) | postgres_async_res_update.s(chip_measurement_object.id, self.input_args) ) as I mentioned job_chain.apply_async() will execute just fine however it hangs or blocks when multiple chains are … -
Bokeh and Django: Bokeh to retrieve only data of an authenticated Django user
Since I have not found a clear way to integrate an interactive Bokeh app within Django, I am trying to make a Bokeh app and Django backend talk to each other via API. So the Bokeh app is running on its own server and is only querying the API for data. Next, the Bokeh app is displayed in an iframe within Django template. Thing is the Bokeh app should retrieve data only for the currently logged in user. But the Bokeh app knows nothing about current user, since it is basically only an interactive chart fed with data from API, and the whole authentication is done on Django's side, on separate server. Is there any way to solve this?