Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a Django form that allows for user to enter their own value for "other" radio option
I have a Model in Django called VolunteerOpportunity that has an attribute called event_name. I'd like the event_name attribute to be a foreign key to another table where the app admins can create default event names such as Career Fair, Senior Bingo, PAWS, etc. I'd also like there to be an "Other" option, that when selected, a user can type in his/her own value. I'd like that value to be stored, however, I don't want it to show up for users as an option the next time the form is loaded. I've attached an example of what I'd like, but this is done through Google Forms. Google Form sample How should I structure the Model(s) and form to allow for such a structure? -
selected checkbox django delete database
I am trying to use checkbox and delete corresponding database selected using Django. I was able to find some resources on Stack overflow to use AJAX but my code won't work... when I click on the button nothing happens. Is there a simple way to use checkbox and delete selected database backend in Django? vlan_id is pk of Vlans model and I want to delete vlan_id in Vlans then it cascades all other database in different model. template {% for object in vlan_query_results %} <tr #id='items-table' > <td scope="row" value="checkbox" class="checkbox-row"><input type="checkbox" name="chk" /></td> <td scope="row" class="item" name="number">{{ forloop.counter}}</td> <td class="item" name="name">{{object.0}}<td> <td class="item" name="allocated">{{object.1}}<td> <td class="item" name="vlan_id">{{object.2}}<td> <td class="item" name="rdp">{{object.3}}<td> <td class="item" name="subnet">{{object.4}}<td> <td class="item" name="nat">{{object.5}}<td> <td class="item" name="dns">{{object.6}}<td> <td class="item" name="dhcp">{{object.7}}<td> <td class="item" name="dhcp_start">{{object.8}}<td> <td class="item" name="dhcp_end">{{object.9}}<td> <td class="item" name="vip">{{object.10}}<td> <td class="item" name="master">{{object.11}}<td> <td class="item" name="backup">{{object.12}}<td> <td class="item" name="vhid">{{object.13}}<td> </tr> {% endfor %} views.py def niro_list(request): gateways = Gateways.objects.all() vlans = Vlans.objects.all() subnets = Subnets.objects.all() vlan_query_results = Vlans.objects.select_related('vlan_id').values_list('name', 'allocated', 'vlan_id', 'subnets__rdp', 'subnets', 'gateways__nat', 'subnets__dns', 'subnets__dhcp', 'subnets__dhcp_start', 'subnets__dhcp_end', 'gateways__vip', 'gateways__master', 'gateways__backup', 'gateways__vhid').order_by('vlan_id') context = { 'gateways': gateways, 'vlans': vlans, 'subnets': subnets, 'vlan_query_results': vlan_query_results, } return render(request, 'niro/niro_list.html', context) html page enter image description here -
Django - Model not creating pk
When creating a new instance of UserProfile it is not creating a primary key. I'm following the one-to-one instructions in this tutorial (that's what all the @receiver stuff is about) I have the following in my models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') guid = models.UUIDField(null=True) @classmethod def create(cls, first_name, last_name, email, guid=None): user = User.objects.create(first_name=first_name, last_name=last_name, email=email) user_profile = cls(user=user, guid=guid) if guid else cls(user=user) return user_profile def most_recent_device(self): return self.devices.order_by('-pk').first() @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Device(models.Model): guid = models.UUIDField(null=True) fcm_token = models.CharField(max_length=4096, null=True) user_profiles = models.ManyToManyField(UserProfile, related_name='devices') def most_recent_user(self): return self.user_profiles.order_by('-pk').first() @classmethod def create(cls, guid=None, fcm_token=None, user_profiles=None): self = cls() self.save() ## possibly excessive saving trying to get this to work if guid: self.guid = guid if fcm_token: self.fcm_token = fcm_token if user_profiles: for user_profile in user_profiles: self.user_profiles.add(user_profile.user.pk) self.save() ## possibly excessive saving trying to get this to work return self When I go to create an instance of the UserProfile model, the pk is not automatically created. For example, I enter this into the interactive shell: >>> user_profile = UserProfile.create( first_name = 'firstname', last_name = 'lastname', email = 'firstname.lastname@company.com', guid = "ed282e0c-4e9d-404b-ba70-8910ec7fe780" ) … -
How to get a certain number of elements in django template
I wonder how I can get a specific number of items when i put an if statement inside a for loop i know we can do {% for i in items|slice ":5"%} to get a number of items but when i do {% for img in post_imgs %} {% if img.link == post.link %} <img class="class" src="{{img.img.url}}" style="width:100%"> {% endif %} {% endfor %} there's no way of doing that inside the if tag .. any solution -
get only text from element
I have this : var y = $(document.getElementById('{{ forloop.counter }}')).text(); console.log(y) In my console I have this : My text1 var y = $(document.getElementById('1')).text(); console.log(y) My text2 var y = $(document.getElementById('2')).text(); console.log(y) How can i get just My text, without funcs. Tried .textContext but console shows that the element undefined -
Django: How do I customize the default add-page for the AbstractUser model
I have a model CustomUser which extends Django's built-in AbstractUser class. Among other fields, AbstractUser contains username, first_name, and last_name. In the CustomUser model, username is automatically generated from the first_name and last_name fields. For this reason, I have overridden the first_name and last_name fields to make them mandatory. from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): first_name = models.CharField(max_length=40, blank=False) last_name = models.CharField(max_length=40, blank=False) def save(self, *args, **kwargs): self.username = self.generate_username() super().save(*args, **kwargs) By default, the admin add-user page (/admin/myapp/customuser/add/) looks like this. How can I make the form in the admin add-page show the first_name and last_name fields instead of the username field? -
How to handle x_accel_redirect using the requests library for inter-server file transfers
We have two servers, both running on ngix: Server A is a Flask application that stores video files Server B is a Django web app that handles database/application logic The Flask app is configured to use X_ACCEL_REDIRECT header for file transfers. I'd like to be able to transfer video files from the Flask app to the Django app, and then package the video files into a zip (among other data), before serving it to the user. I'm trying to download the video files from the flask server to the django application using the requests library like this: import requests def get_files(videos): """ for each video: return a list of tuples (filename, data) where data is bytes-like object containing the file that was retrieved from Flask server. """ files = [] for video in videos: response = requests.get(video.url, allow_redirects=True) if response.status_code == 200: print(response.__dict__) # see output below data = response.content files.append((video.name, data)) return files The code above works fine when i turn of the X_ACCEL_REDIRECT header in the flask server settings. However, when they're enabled the response object that i receive on the Django server has the correct content_length header, but the '_content' property is an empty bytes object: b''. … -
Display names in Django admin deployed on heroku
I have deployed a django app on heroku. If i visit /admin of my app and login, I am getting Category object displayed here instead of the actual name of the category, though I have mentioned it in models.py. class Category(models.Model): name = models.CharField(max_length=128) abbr = models.CharField(max_length=5) sales_price = models.FloatField() def __unicode__(self): return self.name I have added those category objects through the admin interface itself. Might this have anything to do with the display? -
one request but n responses django rest framework, angular 6
I am not sure if this is the actual problem but it appears to be. Can someone shed some light? When I make a request to my django backend it seems I get n number responses instead of one. For example. I request venue objects, and I get a response of 4 objects. But I get 4 responses of 4 objects. Here is the typescript: this.venueservice.browsevenues(this.selectedcity, null) .subscribe( (req: any)=>{ this.filteredvenues = req; console.log('this is the filtered venues'); console.log(this.filteredvenues); for(let venue in this.filteredvenues){ let images = this.filteredvenues[venue].venueimage_set; console.log('this is the venue images before ordering'); console.log(images); ..... (for loop not closed only because I am not showing that part of the code) browse venue service: browsevenues(city, queryparams){ console.log('this is the queryparams'); console.log(queryparams); let params = new HttpParams(); (.... code hidden as not relevant ...) const browseurl = browsevenuesroot + String(city); return this.http.get(browseurl, {params: params}); } django backend: class BrowseVenues(APIView): def get(self, request, *args, **kwargs): city = kwargs.get('city', 0) venuelist = Venue.objects.filter(online=True) (.... code hidden as not relevant ...) serialized = BrowseVenuesSerializer(venuelist, many=True) return Response(serialized.data) what I don't understand is why am I getting 4 responses? Shouldn't I just get one? Is it just because I am console logging and the log … -
Insert Html in database in django
How i can insert html in django database like this: And not like this: -
Django multi site or multi tenancy?
I am using django with python social auth as a way to authenticate users and allow them access to a specific service. This is working fine, but now I'm faced with the problem of scaling up the solution, having multiple busineses using the solution, each with their own social users and own web templates. Businesses would also have to have django admin interface to see their users and other personal metrics. I imagine something like: www.my www.mywebpage.com/businessA/business_own_urls www.mywebpage.com/businessA/admin_url www.mywebpage.com/businessB/business_own_urls www.mywebpage.com/businessB/admin_url www.mywebpage.com/businessC/business_own_urls www.mywebpage.com/businessC/admin_url I am not sure what initiative to take, and which would be the most apropiate one. Any help appreciated -
Reverse after POST (NoReverseMatch)
I am a beginner in Python. In this situation, all I want is to go back to details (index.html) of a Person Profile after UPDATE the data. I Got the error NoReverseMatch. models.py from django.contrib.auth.models import User from modulos.administracao.models import * from django.urls import reverse class PessoaVinculada(models.Model): class Meta: ordering = ['nome'] verbose_name = 'Pessoa Vinculada á Unidade' verbose_name_plural = 'Pessoas Vinculadas á Unidade' user = models.OneToOneField(User, unique=True, related_name='pessoa_vinculada', on_delete=models.CASCADE) nome = models.CharField(max_length=200, null=True, verbose_name='Nome completo') apelido_em_uso = models.CharField(max_length=20, null=True, verbose_name='Apelido em uso') genero = models.ForeignKey(Generos, null=True, verbose_name='Género', on_delete=models.SET_NULL) acesso_a_aplicacao = models.BooleanField(default=True, verbose_name='Acesso à aplicação') def __str__(self): return '{}'.format(self.nome) def get_success_url(self, **kwargs): # obj = form.instance or self.object return reverse("profile", kwargs={'pk': self.id}) def nim(self): return '{}'.format(self.user.username) def nome_apelido_em_uso(self): if self.nome and self.apelido_em_uso: n = self.nome.split() return '{} {}'.format(n[0], self.apelido_em_uso) else: return '{}'.format(self.nome) views.py from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from modulos.gestao.forms import * @login_required(login_url="/login/") def estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais(request, pk=None): context = {} context['user'] = get_object_or_404(User, id=pk) context['pessoa_vinculada'] = get_object_or_404(PessoaVinculada, user_id=pk) context['pessoa_vinculada_identificacao'] = PessoaVinculadaIdentificacao.objects.filter(user_id=pk) context['pessoa_vinculada_foto'] = PessoaVinculadaFoto.objects.filter(user_id=pk) return render(request, 'gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/index.html', context) @login_required(login_url="/login/") def estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais_editar(request, pk=None): user = get_object_or_404(User, id=pk) pessoa_vinculada_identificacao = PessoaVinculadaIdentificacao.objects.filter(user_id=pk) pessoa_vinculada_foto = PessoaVinculadaFoto.objects.filter(user_id=pk) pessoa_vinculada = get_object_or_404(PessoaVinculada, id=pk) if request.method == 'POST': user_form = PessoaVinculadaForm(request.POST, … -
django 2.0 work with forms without jquery
from django import forms class Find(forms.Form): object_name = forms.CharField() views.py def get_obj(request, object_name='000'): print(object_name) form = FindSSK() print(request.GET) urlpatterns = [ # path(r'ssk/<str:object_name>/', get_obj), re_path(r'^(?P<object_name>)#$', get_obj), path(r'', get_obj), ] {% block find %} <form class="form-inline ml-5" action="#" method="GET"> {% comment %} {{form}} {% endcomment %} {% comment %} <input type="number" class="form-control" placeholder="Enter obj" aria-label="Search"> {% endcomment %} {% comment %} <input type="text" > {% endcomment %} <input type="text" name="object_name" /> <input class="btn btn-outline-success ml-1 fas fa-search" type="submit" > </input> </form> {% endblock %} When i push to submit on forms, he will redirect http://127.0.0.1:8000/?object_name=001 But var object_name steal 000 result print in get_obj() 000 <QueryDict: {'object_name': ['001']}> Sorry for bad English. -
Make an ID counter for a model in django
I want to make a simple ID counter for a model in django. I'd prefer it to start at 1000 instead of 0, so I'm thinking it might be better not to use the built in id function, as I've tried to do here: def __str__(self): return "Job #" + str(id) This (and all other attempts that involve writing a function) just return something like this: Job #<built-in function id> Maybe it's easier to just use a for loop somehow? -
fetch data from 3rd party API - Single Responsibility Principle in Django
What's the most elegant way to fetch data from an external API if I want to be faithful to the Single Responsibility Principle? Where/when exactly should it be made? Assuming I've got a POST /foo endpoint which after being called should somehow trigger a call to the external API and fetch/save some data from it in my local DB. Should I add the call in the view? Or the Model? -
Nginx is not serving my django site although uwsgi is working
I have a project with django + uwsgi + nginx I have 2 django projects that will work on sockets on same server. I run "uwsgi --ini /etc/uwsgi/sites/proj.ini" , it is working. Than i start nginx. Nginx default page is coming but it is not serving my django project. Also proj.sock is created. I have nginx config files for both projects in /etc/nginx/conf.d The proj project nginx conf file is proj.conf It is; server { listen 80; #server_name 127.0.0.1; server_name proj.tr; access_log /var/log/nginx/proj_access.log; error_log /var/log/nginx/proj_errors.log; sendfile on; client_max_body_size 20M; keepalive_timeout 0; location = favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/proj/work/proj; } location /media/ { root /home/proj/work/proj; } location / { include uwsgi_params; uwsgi_read_timeout 9000; uwsgi_send_timeout 9000; uwsgi_connect_timeout 9000; uwsgi_pass unix:/run/uwsgi/proj.sock; } } The strange thing is if i make "server_name 127.0.0.1" it is working on http://127.0.0.1 . But if i make it "server_name proj.tr" http://proj.tr it is not working. The domain name proj.tr is mapped to 127.0.0.1 in /etc/hosts file in linux. My uwsgi ini file is : [uwsgi] py-autoreload = 2 project = proj username = proj base = /home/%(username) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = … -
Call a model Field in a view in Django
I'm not sure if it's possible to do what I'm trying. I want to execute a python file, and one of the arguments is the file which is uploaded with the FileField model Field, and I have programmed this in a view, so when you click a button in my html template, It calls that view and executes this command. The only problem is that I need to call that model Field and I don't find the solution. I want to call it as the third argument I post here my code: views.py: def index(request): if request.POST: subprocess.call(['python', '/home/josema/MEGA/Universidad/Universidad/PROYECTO/MIDIPIRCUSSION/MIDIPIRCUSSION_APP/static/MIDIPIRCUSSION_APP/parser.py', 'CALL THE MODEL FIELD']) return render(request,'index.html',{}) models.py: class Cancion(models.Model): @property def filename(self): return self.archivo.path archivo = models.FileField() -
Django Background Process Not Working Properly
I am trying to install django-background-task to run some simple background tasks after a response is sent to the user. However, I am not able to run migrations, "python manage.py makemigrations background_task" gives an error. After installation actually I get an error, File "/root/.venvs/netadc/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/db/migrations/loader.py", line 203, in build_graph self.load_disk() File "/root/.venvs/netadc/lib/python2.7/site-packages/Django-1.11-py2.7.egg/django/db/migrations/loader.py", line 107, in load_disk for name in os.listdir(directory): OSError: [Errno 20] Not a directory: '/root/.venvs/netadc/lib/python2.7/site-packages/django_background_tasks-1.1.13-py2.7.egg/background_task/migrations' I am not sure what I am missing. These are pretty simple steps. I installed the package from source and installed the dependencies. Any help is appreciated. -
Django Query current month
Im trying to filter in DJango Query the current month models.py class Album_Requests(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) request_date = models.DateTimeField(auto_now_add=True) request_user = models.CharField(default='', blank=True, max_length=100) ... ... views.py def current_month(request): current_month= Album_Requests.objects.filter(request_date__month='07') return render(request, 'month.html', {'current_month': current_month}) month.html {% if current_month%} {% for album in current_month%} <tr> <td>{{album.request_date|date:"Y-m-d H:i " }}</td> <td>{{albums.current_month}}</td> </tr> {% endfor %} {% else %} {% endif %} But when I try to open the template, I get this Error: Variable Value current_month Error in formatting: OperationalError: function raised exception datetime <class 'datetime'> 7 request <WSGIRequest: GET '/month/'> can someone help me here? I don't know what to do to fix this error. -
Wagtail: Setting a dedicated Static folder for each app in Multisite
I am using Multisite to administer several websites and a custom admin on a single build of Wagtail. Currently, I have my static folder set like this: settings.py: INSTALLED_APPS = [ 'websites.sua_umn_edu', 'admin_sua_umn_edu', ... ] STATIC_URL = '/static/' Is there some way to set the STATIC_URL dynamically, so each app looks for a static directory within its own folder? -
What is request.GET.get doing?
I am looking at A.Mele Django by Example,chapter1 def post_list(request, category=None): object_list = Post.published.all() paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) This line that gets page is what I really do not understand. page = request.GET.get('page') Get method sends user information with the request. But what is get actually doing? This is blog/post/list.html {% extends "blog/base.html" %} {% block title %}My blog{% endblock %} {% block content %} {% include "pagination.html" with page=posts %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} -
How To Display One form error in Django
I have this in my template and i want only to display username error not all form errors {% for field in form %} {% for error in field.errors %} <div class="row"> <div class="small-12 columns val-error-msg error margin-below"> {{ error }} </div> </div> {% endfor %} {% endfor %} -
How to access specific Model fields in template?
I have a Model Form in views.py: a_form = MyModelForm(request.POST or None) MyModelForm has many fields: field1,field2,field3 plus many more How do I access only certain fields (lets say field2 and field3) in a loop in a template? I tried: #template.html <label>Example: </label> {% for text in fields %} <label>{{text|return_var}}{{text}</label> {% endfor %} #views.py fields = ['field2', 'field3'] return render(request, 'template.html', {'a_form':a_form,"fields":fields) #forms.py @register.filter def return_var(text): return "a_form." + text but that only gave me a_form.field2a_form.field2 a_form.field3a_form.field2 as text on my page and not the checkbox with label like I wanted. Thanks in advanced. -
Changing a default model field name that django class based views look for
I am using PasswordResetView (the class-based view in Django 2.0) to implement Forgot Password functionality into my app. I am new to class based views and by default it looks for is_active in my user model. However, I overrode the default user model and my model instead contains the field with the name active. How do I change this behavior? FieldError at /account/reset-Password/ Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username Request Method: POST Request URL: http://127.0.0.1:8000/account/reset-Password/ Django Version: 2.0.5 Exception Type: FieldError Exception Value: Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username Exception Location: /home/yash/Desktop/ltigo/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path, line 1379 Python Executable: /home/yash/Desktop/ltigo/bin/python Python Version: 3.6.5 Python Path: ['/home/yash/Desktop/ltigo/src', '/home/yash/Desktop/ltigo', '/home/yash/Desktop/ltigo/lib/python36.zip', '/home/yash/Desktop/ltigo/lib/python3.6', '/home/yash/Desktop/ltigo/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/yash/Desktop/ltigo/lib/python3.6/site-packages', '/snap/pycharm-professional/68/helpers/pycharm_matplotlib_backend'] Server time: Mon, 16 Jul 2018 15:18:07 +0000 -
How to Call django model field name from a list?
django models.py class mymodel(models.Model): date_check = models.DateField() item_1 = models.NullBooleanField() item_2 = mod`enter code here`els.NullBooleanField() item_3 = models.NullBooleanField() item_4 = models.NullBooleanField() item_5 = models.NullBooleanField() Task: >>> from .models import mymodel >>> >>> a_list = ['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_5', ] >>> a_year = 2018 >>> param1 = {} >>> param2 = {} >>> param3 = {} >>> for item in a_list : >>> param1[item] = mymodel.objects.filter(date_check__year = a_year, item=True).count() >>> param2[item] = mymodel.objects.filter(date_check__year = a_year, item=False).count() >>> param3[item] = mymodel.objects.filter(date_check__year = a_year, item=None).count() .....error here how do we call field name from list?