Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django one-to-many relationship in models (not about lookups)
I am trying to figure out how to define a one-to-many relationship between two models. The difficulty here is that I do not want to touch one of the models and therefore can not use the usual ForeignKey (Many-to-one). There are many question on this topic but they all either talk about how to do the lookup (reverse ForeignKey lookup) or they suggest to just add a Foreign Key to one side. Here is a similar question. I will use the same code example. This is what I am looking for: class Dude(models.Model): numbers = models.OneToManyField('PhoneNumber') class PhoneNumber(models.Model): number = models.CharField() Usually I would go ahead and just add a Foreign Key to PhoneNumber as suggested in many answers: class PhoneNumber(models.Model): dude = models.ForeignKey(Dude, related_name='numbers') But in my situation I would like to not touch the PhoneNumber model and therefore define something on the Dude model. The reason for this is that I am defining a model describing a special circumstance which is rarely used. If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all models leave this field blank. I do not really like the idea to have a field which is always blank … -
Django + Bootstrap 4 + white-space pre-wrap/|linebreaks
I have a form with a comment as textfield where the user also uses linebreaks etc. It looks nice. Now I want to preserve these linebreaks when I call the comment in my templates. Using {{ comment|linebreaks }}does not help. Should I use white-space:pre-wrap with bootstrap and my {{ comment }} instead? Thanks in advance! -
Django forms with one-to-many relationship
I have two models in django class Project(models.Model): name = models.CharField(max_length=250) customer = models.CharField(max_length=250) class Subproject(models.Model): name = models.CharField(max_length=250) project = models.ForeignKey(Project, on_delete=models.CASCADE) I would like to create form for creating projects. The problem is that I would like to have on one form fields to create Project and dynamic number of fields to create Subproject because Project can have several Subprojects and I don't know what will be the amount of Subprojects before creating a form. At the moment my view function looks like this: def project_new(request): if request.method == "POST": form = ProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.save() return redirect('subproject_new') else: form = ProjectForm() return render(request, 'projects/project_edit.html', {'form': form}) And template looks like this: {% block content %} <div class="form__background"></div> <div class="box-form"> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% endblock %} I am using ModelForms: class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'customer',) class SubprojectForm(forms.ModelForm): class Meta: model = Subproject fields = ('project', 'name',) -
Django has no attribute 'GeoManager issue
from django.db import models from django.contrib.gis.db import models location = models.PointField(srid=4326,null=True,blank=True) objects = models.GeoManager() I am hosted my Django project on AWS server. I cant able to run the project because of the error I added below, but I implemented the same project in my ubuntu system and its working fine. Unhandled exception in thread started by .wrapper at 0x7f527104b6a8> Traceback (most recent call last): File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/init.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/django_env/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 10, in class BusStop(models.Model): File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 17, in BusStop objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager' -
Django 2.0 multiselect issue
I am testing 2.0 and have encountered the same error in two different places. It has to do with multi-select. I get the following error. Exception Value: not enough values to unpack (expected 2, got 0) here is the code from crispy-forms-foundation {% if not field|is_checkbox and not field|is_checkboxselectmultiple %} {% crispy_field field %} {% endif %} the other package error was from: localflavor.us.models import USStateField, PhoneNumberField, USZipCodeField What do I need to change to get these to work properly in 2.0? Cheers -
How to isolate django apps of same project with team members
We are a team of 5 members, we have one Django project with multiple apps, now we want to divide each member to different-2 apps and other members can't make any change to any other apps but they are allowed to use it, how to achieve that, please help. -
What happens when server request files exceed memory size?
I'm trying to figure out what happens when files of varying sizes are uploaded to the server at the same time and their collective size exceeds that of the memory. More specifically, what does Django do then? Does virtual memory come into play or are the files moved to disk? According to Django documentation, you can specify the FILE_UPLOAD_MAX_MEMORY_SIZE value which decides whether the temp file remains in memory or goes to disk. If I set this value to, say, 50 GB, and I send one or more files at the same time to the server, AND my RAM is only 16 GB, what happens then? I'm asking this question because I need to encrypt the files I receive at the server without saving them flat anywhere in the disk, even as a temporary file, due to sensitivity of the data. I want to make sure that under no circumstance the file(s) will be moved from the (volatile) memory to (secondary) disk storage in its original form. -
Can anyone help in Django image modal display in web template?
I'm pretty new to Django Framework for web designing. In my web project, I have a template which contains a table coming from Oracle database and it is designed by django-tables2. In this table, I'm having a column which is linked to local images stored on my local machine. When user clicks the link in the table, an image is displaying on the same tab. Now my question is can I display this image in a separate popup window or in new tab or in modal dialog box instead of displaying it in same tab? I have referred online for this but in most cases results are for Form modal and not for media files and I could not figure it out that how those would be implemented in my case. Please, can anyone help me in this? I'm using Django-Bootstrap for overall UI design, django-tables2 for table design, django-material for form design, Oracle database 11g, Python3.6 and Django 11.1. Thanks in advance... -
How to secure web services when authentication is done at client side (frontend)
I have web application which structure is as- webapi : django web services [NOT REST] no security implemented frontend : Angular2. authentication implemented via SAML Database : Mongodb Can you please suggest best way to secure webapi, as currently anyone can access web services who has server[api] url It will be big help if you suggest the authentication and authorization flow because I am totally stuck. Thanks in advance. -
:: acting as delimiter in my csv file and spliting data
I have a django template where I have stored some tables and have written a function to export it to csv but when i am doing it some columns in my table have :: in them and csv is treating it as a delimiter and splitting the column there how can i prevent this from happening my views.py f = open("static/output.csv", "w") f.write("Customer Name" + "," + "Status" + "," + "Product" + "," + "Operating System" + "," +"Server_Type" + "," + "Version"+"," +"Citrux_URL"+"," +"F5_URL"+","+"\n") for c in custom: f.write(c.summarise()+"\n") my models.py def summarise(self): s = ",".join([str(self.name), str(self.Status), str(self.Product),str(self.SSO),str(self.SSO_URL),str(self.JCES_URL),str(self.L3),str(self.PM))]) return s -
ImportError: No module named 'mysite' from omv of pi3
I want to work with Apache 2 and Django 2.0. So I modified /etc/apache2/sites-sites-available/000-default.conf and /home/duen/django/mysite/wsgi.py. python = 3.4.2 django = 2.0 apache = 2.4.10 device = raspbarry pi 3 model B os = OpenMediaVault 3.0.88 000-default.conf <VirtualHost *: 80> ServerAdmin sin12070@gmail.com DocumentRoot / var / www / html ErrorLog $ {APACHE_LOG_DIR} /error.log CustomLog $ {APACHE_LOG_DIR} /access.log combined WSGIDaemonProcess mysite python-path = / home / duen / django / mysite: /home/duen/django/venv/lib/python3.4/site-packages WSGIScriptAlias / /home/duen/django/mysite/wsgi.py <Directory / home / duen / django / mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> wsgi.py import os import sys sys.path.append ('/ hoem / duen / django') sys.path.append ('/ hoem / duen / django / mysite') sys.path.append ('/ home / duen / django / venv / lib / python3.4 / site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault ("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application () However, when I accessed the web page, I could see this error in error.log. error.log mod_wsgi (pid=9040): Exception occurred processing WSGI script '/home/duen/django/mysite/wsgi.py'. Traceback (most recent call last) File "/home/duen/django/mysite/wsgi.py", line 20, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.4/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.4/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.4/dist-packages/django/conf/__init__.py", line … -
Upload_to with name of objects
I have a question I think it's easy to your guys about upload_to in Django but it's difficult to me. Hope your helps! # Upload_to Def from datetime import datetime def avatar_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_avatar.%s" %(filename, datetime_str, ext) def cover_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_cover.%s" %(filename, datetime_str, ext) def flag_country_path(instance, filename): ext = filename.split('.')[-1] filename = '%s' % (instance.id) datetime_str = datetime.now().strftime("%Y%m%d%H%M%S") return "geo/country/%s/%s_flag.%s" %(filename, datetime_str, ext) class BaseCountry(Place, SlugModel): # More avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True) cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True) flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True As you see, I need 3 Defs to make upload_to with a similar Path, just different in NAME OF FIELDS (avatar, cover, flag) but I dont know how to shorten it. Could you guys help me? -
Updating point total on User model via signals and save() method django
I want to assign points to a User via another model (UserPoints). I know that I need to use the save() method to save the points to the correct User. And I also know that I need to use a signal to notify the User model to save the points there. However, the code I wrote generates this error: 'User' object has no attribute 'userpoints_set' Can someone please tell me what I am doing wrong? Why am I getting that error? And how do I fix it? The goal is to store the points in one model and then update the point total on the User model. Thanks in advance! models import datetime from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models import Sum from django.db.models.signals import post_save from django.dispatch import receiver from points.models import PointValue @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) image = models.ImageField(upload_to='user/%Y/%m/%d', default='') point_total = models.IntegerField(default=1) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) @python_2_unicode_compatible class UserPoints(models.Model): … -
django forms multiple form with one field same by default
I have a list of links,(A,B,C,D,) each link opens the same pop up form with fields (name , email, region, service) all the inputs except SERVICE is user input. I want the service field to have a default name of the links. EXAMPLE: LINK A ---FORM------- NAME= ......... EMAIL=........ REGION=........ SERVICE=FORM A =========================== LINK B ---FORM------- NAME= ......... EMAIL=........ REGION=........ SERVICE=FORM B ==================================== I want the service field to have that default value. how can I achieve that in Django?????? -
Save avatar from facebook in allauth
There are questions here which answer this, but my case is different. Instead of letting allauth create a new user I'm catching wheter or not the email exists and performing a login using user = User.objects.get(email=email) sociallogin.connect(request, user) social_account_added.send( sender=SocialLogin, request=request, sociallogin=sociallogin, ) But, I can't set the avatar here due to the way my conditions are setup and this may never be hit. The alternative is in get_redirect_url from what I see, but this isn't called if I use sociallogin.get_redirect_url so it seems theres opportunity for both to be skipped. There's a signal user_logged_in = Signal(providing_args=["request", "user"]) under account app in allauth but what if they have multiple socials connected? How would I determine the proper avatar to get... -
Walrus is not indexing the words properly
In my Django project, I am using walrus to cache location names. eg: New Zealand, New York City, Newcastle e.t.c So, when I am searching for a key 'new', I am expecting it to return all the above locations but it is only giving me New Zealand. But I when I use 'n' or 'ne' as a key I am getting all of these. I tried changing the stopwords_file to a blank file on initializing the walrus autocomplete. Any help is appreciated. -
change button based on previously "liked" status by usr django
I am new to Django and am trying to create a favorite application. I would like to have the liked button change based on whether or not the user has already favorited the physician. I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this. Any help would be much appreciated! models.py class Physician(models.Model): speciality = models.CharField(null=False, blank=False, max_length=30) first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) title = models.CharField(null=False, blank=False, max_length=2) address1 = models.CharField(null=False, blank=True, max_length=50) address2 = models.CharField(null=True, blank=True, max_length=20) city = models.CharField(null=False, blank=False, max_length=50) state = models.CharField(null=False, blank=False, max_length=2) zip = models.CharField(null=False, blank=False, max_length=12) likes = models.IntegerField(default=1) def __str__(self): template = '{0.last_name} {0.first_name} {0.speciality}' return template.format(self) class Voter(models.Model): user = models.ForeignKey(User) physician = models.ForeignKey(Physician) My template is {% if physicians %} {% for physician in physicians %} <tr> <td> <a href="/getmd/{{physician.id}}/"> {{ physician.last_name }}, {{ physician.first_name }} </a> </td> <td>{{ physician.state }}</td> <td>{{ physician.speciality }}</td> <td>{{ physician.id}}</td> <td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td> <td> {% if user.is_authenticated %} {% if likedalready.physician].liked %} <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved"> <span class="glyphicon … -
Sending data stream from python program to web app
I have a python program appending lines to a .csv file every few seconds. I also have a web app that was created using Django. My goal is to continuously read the data from the python program as it runs and display it on the website without having to refresh. My proposed solution is to send the python output to a server using requests.put(), and then read from the server using AJAX. 1.) Is this the best solution, or is there a better manner to connect the program and the site. 2.) If this is a good solution, what's the easiest way to get a server running to POST, PUT, and GET from? It can be local and will never expect heavy traffic. Thank you! -
Proper way to share temporary data between two users
Here is my case in django,i need to create a match between two users, users take turn, after one of them has finished, i need to send user1 score to user2 and vise versa. How can i create a match between two players? How do i store their data(scores) in a way that can be accessed for both users. Here is what i've tried : user1 sends GET request to get a user2 as a opponent by getting user2 id (i can say i made a match there), then after user1 finished he make another GET request with hes id and score to django. and here is where i stuck : I don't know how to send user1 score to user2. I don't know how to store the data so both users can access each other score. I'm quite new to django, so i did all that based on my basic knowledge of the framework, please correct me if i'm wrong and possibly suggest a better approach. -
TypeError: 'question_text' is an invalid keyword argument for this function in django 2.0 tutorial
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error. Here is my code for the models.py import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200), pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE), choice_text = models.CharField(max_length=200), votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Also the question text and choice text is not appearing on the django-admin page enter image description here -
Youtube uploads
I am using Django/Python to create a project that allows users to automatically upload their youtube videos to my site. Is there a way to do this? Would using python-social-auth be the solution? Please advise. Many thanks! -
Django's sitemap framework giving error when using aggregate max function on lastmod
I'm trying to use Django's sitemap framework feature. I've implemented the code and it works with current article objects post_date. However I'm trying to get a more accurate last modification date using the following code and it gives me error. Traceback of error http://dpaste.com/3Z04VH8 Regards. Thanks for any help from django.contrib.sitemaps import Sitemap from django.db.models import Max from article.models import Article class ArticleSitemap(Sitemap): changefreq = 'hourly' priority = 0.5 def items(self): return Article.objects.all() def lastmod(self, obj): from post.models import Post return Post.objects.filter(article=obj).aggregate(Max('post_date')) #return obj.post_date -
Django arranging model foreign key attributes after delete()
I have a model like so: class RepairOrder(models.Model): user = models.ForeignKey(User) ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)]) service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True) RO_STATUS_CHOICES = ( ('P', 'Pending'), ('O', 'Open'), ('C', 'Closed') ) ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES) open_date = models.DateTimeField() closed_date = models.DateTimeField(null=True, blank=True) mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)]) line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_1') line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_2') line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_3') line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL , related_name='line_number_4') line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_5') line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_6') line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_7') line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_8') line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_9') line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL, related_name='line_number_10') vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle') def __str__(self): return str(self.ro_number) Some of these objects might have line_number_(1 through 5) assigned to a JobLine object and the remaining set as Null. Other RepairOrder objects may only have line_number_(1 through 3) assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the line_number_(x) attributes are always assigned in ascending order starting from 1. Here is what I am trying to accomplish: Lets assume I have a RepairOrder … -
nginx redirect with authorization header
I configured django together with nginx. Static files get served directly using nginx. It's all working fine, but the problem is, now I need to proxy a download from another source. The other source requires authentication, at the moment I am using Django's StreamingHttpResponse, but I want to somehow directly serve it using nginx. I know it's possible to set the authorization header in nginx using proxy_set_header, but the problem is that the authorization header is different for every user. Would it work if I just (from django) return a redirect and modify the authorization header of the request object? Does nginx have a solution for such exotic cases? Do I need to write a module to make it work, or does it even make sense to write a module because maybe it's completely the wrong way of doing it? Thanks in avance. -
Sending a csv file via curl POST to Django REST Framework endpoint
I have a csv file that I want to send via curl to a Django Rest Framework API View I have developed. The csv file itself contains only foo,bar and this is the curl command I'm using: curl URL -H 'Accept: application/json' -H 'Referer: http://localhost:5011/ost:5011' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36' -H 'Authorization: JWT TOKEN -H 'Content-Type: multipart/form-data' -F upload=@testcsv.csv When it hits my API View in Django, and I run request.data.get('file').read() the output is some metadata around the file and not the file contents itself: (Pdb) b'--------------------------001ec735bfc1a929\r\nContent- Disposition: form-data; name="upload"; filename="testcsv.csv"\r\nContent-Type: application/octet- stream\r\n\r\n\r\n--------------------------001ec735bfc1a929--\r\n' How can I access the actual file itself through this method? My APIview is using class FileUploadView(APIView): parser_classes = (MultiPartParser,) Thanks!