Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django traffic tracking
I have a website using django which has blog posts section where all blogs are summarised. you can expand the blog by going to a more detailed article on the blog by clicking "View" button which you will redirect to the necessary url. I would like to implement a feature on the detailed blog page where it shows how many visits the detailed blog has had. I am aware I can use google analytics to track this for my personal view but is they some sort of analytics sites where I can use an API to populate the data so I can show it on the page? -
How to create a demo audio file after uploading with Django?
How to create a demo audio file after uploading with Django? I am using django admin and for security reasons I need to create a demo file when an audio file is sent. This is the model class AudioFile(models.Model): name = models.CharField('Name', max_length=100) full_file = models.FileField('Fullmedia', 'upload_to='fullmedia') demo_file = models.FileField('Demo') This is the function to cut the file, note that it was using pydub to create a file with 30 seconds def make_demo(self, file): """Create a demo file with 30 secondes from real file uploaded""" song = AudioSegment.from_mp3(file) time = 30 * 1000 demo = song[:time] return demo.export(file.name + 'demo', format='mp3') What is the best way to process the upload and create this file, within the model? no admin file? -
What makes a good combinations to provide shape files on an web app?
I am attempting to develop a web app with docker. I have tried to look around and have been confused with the essential components of making one. Please bear me if you see my question is naive. This is my first attempt. I would love to use docker - to make it light weight. I have Postgres/PostGIS as data storage, and know that I can use GeoServer and other map tools, as well as GeoDjango (and other web frameworks). The question is - I am not going to provide geotiff files (no raster layers), but only shape files that people can download to make their own desk-top version maps. I am also not going to provide maps (so no need to have open layers and such). Do I need GeoServer? Would GeoDjango and PostGIS in a docker environment simply make this happen? Thank you for your help. -
Django and database connector problems
I have this installed for mysql and django , still i receive an error -Django 2.1.3 -mysql-connector-python 8.0.13 -pip 18.1 -pytz 2018.7 -setuptools 39.0.1 -virtualenv 16.0.0 -virtualenvwrapper-win 1.2.5 -wheel 0.32.3 How can i connect to mysql and django with mysql-connector. I still receive an error to install mysqlclient. Is there anything missing. please let me know -
Unexpected behavior on delete of a model row
Situation: I have two Model classes, in two different apps which are part of the same project. class doctor defined in appointments.models is a set of attributes associated with a doctor, like name, username, email, phone etc. class DoctorProfilePic is a Model defined in clinic.models, which has a StdImageField which stores images. doctor has a One to One mapping to DoctorProfilePic. class doctor(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) username = models.CharField(max_length=15) ... profilepic = models.ForeignKey(DoctorProfilePic, blank=True, null=True, on_delete=models.CASCADE) ... class DoctorProfilePic (models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=255, blank=True) pic = StdImageField(upload_to="data/media/%Y/%m/%d", blank=True, variations={ 'large': (600, 400), 'thumbnail': (150, 140, True), 'medium': (300, 200), }) doc = models.ForeignKey('appointments.doctor', blank=True, null=True, on_delete=models.CASCADE) Anticipated response: When user selects one of the profile pics from a selection box, and clicks Delete, django is supposed to delete the picture from the collection of pictures uploaded by the doctor. Problem: When the delete button is clicked, django deletes both the picture and the doctor, instead of just the former. Code: def removeprofpic(request, docid): docid = int(docid) if not IsOwnerorSuperUser(request, docid): return HttpResponse("You dont have permissions to do this.") doc = doctor.objects.get(docid = docid) if request.method == … -
python pil colour fill
I have a shape below: and I would like to colour only this shape, the background is transparent so I feel as if there is some way to colour an entire image. Right now I am using put pixel and colouring every pixel in the picture but I am wondering if there is a more efficient way to do this? putpixel(xy=(i,j), value=(red)), where i,j is coloured if it exists -
Django: limit API view output to contain only data of OAuth authenticated user?
My app requires user consent to use activity data from his Strava account (Strava is a social service for athletes). Strava uses OAuth flow for this, so the user logs in to Strava, gives his consent, and Strava redirects to a predefined URL with code added to query string that can be then exchanged for access token via another request: def strava_redirects_to_this_view(request): #strava redirects to this view after authentication, with code in query string #get tokens code = request.GET.get('code', '') # extract code from redirect URL query string access_token = exchange_code_for_token(code) # custom function to make exchange request I want my other app - running on another server - to get data of only authenticated user via API. However, I don't know how to limit the output of the API to contain only the data of the currently authenticated user. Currently my API view queries all data (activities), regardless of user: class ListActivitiesView(generics.ListAPIView): queryset = Activity.objects.all() serializer_class = ActivitySerializer I know I could limit the queryset to only logged in user if I had user registration in my app, but I would prefer not to have another registration as the user already has to log in to Strava. How would … -
Django Similar query and duplicate
Want to create user from User model. Code below class UserCreateView(CreateView): model = User fields = '__all__' template_name = 'add.html' queryset = User.objects.select_related('permission__content_type').all() But lots of duplicated query from content_type. -
How to retrieve the week value from the django model to view and pass it to the dictionary?
I just want to retrieve the week value from the model to view and pass it to the dictionary. What am I doing wrong? Model import datetime from datetime import date from django.db import models class WeekNumber(models.Model): """Week number""" objects = models.Manager() @staticmethod def number_of_week(): week = date.today().strftime("%U") return week View from django.views import View from django.shortcuts import render from .models import WeekNumber class WeekNumbers(View): model = WeekNumber template_name = 'week_number' def get(self, request): week = WeekNumber.objects.get() context = {'week': week} return render(request, 'week_number.html', context) Template <tr> <td>Week {{ week }}</td> </tr> and I have in browser: Week WeekNumber object (1) Many thanks in advance! -
Comparing two django variable in a django if block
I am having a tough time with following code. {% if object.author == user.username %} ( it is not working neither giving error) So i have articles app inside my django project. I want to make sure that if a user goes to their own post, then only they should be able to see delete and edit links(i will be placing them inside if block). Here {{object.author}} and {{user.username}} both are valid django variables. {{user.username}} specifies username of current logged in user and {{object.author}} specifies author of that particular post. Please help me out to implement with comparision logic of both variables. I am using python 3.6, django 2.1 and django template language. -
invalid literal for int() with base 10: 'Ice Cream' error
I am trying to show stock records of a particular product. While passing id of that product to stock records, it is showing invalid literal for int() with base 10: 'Ice Cream' error. My code looks like this: models.py class mProduct(models.Model): mProduct_id=models.AutoField(primary_key=True) mProduct_name=models.CharField(max_length=50) mProduct_qtyunit = models.ForeignKey(mProductUnit,on_delete=models.CASCADE) #Product ##Unit has one to many relationship with ##mProduct mProduct_qty=models.FloatField(default=0) ##current stock def __str__(self): return self.mProduct_name class mStock(models.Model): mStock_id=models.AutoField(primary_key=True) mStock_date=models.DateTimeField(default=timezone.now) mStock_product=models.ForeignKey(mProduct,on_delete=models.CASCADE) mStock_qty=models.FloatField() views.py In this view, I am trying to get object for a particular product and use it to get it's stock records through filter(). def mStockDetailView(request,id): model=mStock m=get_object_or_404(mProduct,mProduct_id=id) stock=mStock.objects.filter(mStock_product=m.mProduct_name) context={ 'stock':stock, } return render(request,'dairyapp/stock-details.html',context) template: productlist.html I passed product id as parameter with url. {% for p in product %} <a href="{% url 'dairyapp:stock-detail' id=p.mProduct_id %}"> {{p.mProduct_name}}</a> {%endfor%} urls.py path('stockrecords/<id>',views.mStockDetailView,name='stock-detail'), Despite this, I am getting invalid literal for int() with base 10: 'Ice Cream' error Can anyone provide solution for this error? Traceback: Request Method: GET Request URL: http://localhost:8000/stockrecords/5 Django Version: 2.1.3 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dairyapp.apps.DairyappConfig', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) …