Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
How get multiple BooleanFields in a form using Django
I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid. The field "who paid" is a table containing the name of all users and a checkbox. Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text). How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name? model.py from django.db import models #created_date attibute needs it from django.utils import timezone # This Model is a super class "Financial Transaction" class GroupTransaction(models.Model): name = models.CharField(max_length=257, default='') who_paid = models.CharField(max_length=257, default='') value = models.DecimalField(max_digits=6, decimal_places=2) justification = models.CharField(max_length=257, default='') created_date = models.DateTimeField(default=timezone.now) date = models.CharField(max_length=257, default='') receipt = models.FileField(upload_to='comprovantes', blank=True, null=True) its_type = models.CharField(max_length=257, default='') def __str__(self): #INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant) return "%s - %s" % (self.name , self.who_paid) view.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from deposit.forms … - 
        
Django admin: how can i make related modle show only after selecting primary model
class Company(models.Model): name = models.CharField(max_length=200, help_text="Enter Company name") class Product(models.Model): company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True) sku = models.CharField(max_length=200,null=True,blank=True,unique=True) class Inventory(models.Model): product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) quantity = models.PositiveIntegerField(null=True,default=0) Every product is owned by a Company, in my Add Inventory i have Product dropdown field but it only displays Product, how can I make the user first select the company then the product owned by that company displays? - 
        
Django: How to use get_form() method in CreateView?
I have a CustomForm in my forms.py that needs the public key of the URL. I mean e.g. /book/<pk>/create. In my views.py there is this CreateView: class CustomCreateView(CreateView): form_class = CustomForm Now my question is how can I pass the public key of the URL to the CustomForm. The CustomForm expect a keyword argument named pk. I thing the get_form() method could help, but I am not sure and do not know how to use it: https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form - 
        
If condition works not so as I expect it
On screenshot below you can see Im trying to save this model given one value for "RESULTAT 1 HZ" and empty value for "RESULTAT 1 HZ" on downside. In my my_callback Im doing some calculation but as you can see only if both of fields are not None. So, why I get error that shown on second screenshot? TypeError Exception Value: '>' not supported between instances of 'int' and 'NoneType' @receiver(pre_save, sender='tournament.GroupstageTournamentModel') def my_callback(sender, instance, *args, **kwargs): # Point for first half time if not (instance.team_1_first_halftime_score is None and instance.team_2_first_halftime_score is None): if instance.team_1_first_halftime_score > instance.team_2_first_halftime_score: instance.team_1_first_halftime_point = 2 Here is my Traceback http://dpaste.com/0DDP4QC - 
        
Angular relationship of tables from many to many
I have a problem in angular i dont now how to call from the table to an object that has many to many relationship [ { "id": 2, "username": "test", "email": "test1@gmail.com", "groups": [ { "id": 2, "name": "Empleados", "permissions": [] } ] }, ] <tr *ngFor="let item of users;"> <td>{{item.id}}</td> <td>{{item.username}}</td> <td>{{item.email}}</td> <td>{{item.groups.name}}</td> <td> <a href="" class="btn btn-default">Leer</a> <a href="" class="btn btn-warning">Editar</a> <button class="delete" (click)="Eliminar(item)">Eliminar</button> </td> </tr> that does not work for me, it only works for me when the relationship is one to many try to do this, I only work the first column {{item.groups[0].name}} - 
        
Django: Form validation based on public key/foreign key
I have an Event model and a Registration model (one event can have multiple registrations -> ForeignKey). At event/<pk>/register I want to present a Form where you can register for the certain event. So, I have to do Form validation in my forms.py. However, I need access to the public key of the URL. But I do not know how I get the public key? The other way would be to include the pk to the Form. Problem here is that when you surf at event/5/register the field for the event MUST be 5 and should not be editable. But I could not find a solution to initially set the Event in the Form for the Registration creation. Additionally, it must not be editable. I'm pretty sure that's quite a common problem. What is the solution? - 
        
Django with PIL - '_io.BytesIO' object has no attribute 'name'
I'm using PIL to resize an uploaded photo before saving. Note that I'm using formsets to upload the pictures. I'm using BytesIO to open the file. At the last step, I get the error - '_io.BytesIO' object has no attribute 'name'. Why is this? def fsbo_create_listing(request): PhotoFormSet = formset_factory(OwnerListingPhotoForm, extra=15) if request.method == 'POST': form = OwnerListingForm(request.POST) photo_formset = PhotoFormSet(request.POST, request.FILES) if form.is_valid() and photo_formset.is_valid(): form.instance.user = request.user form.save() for i in photo_formset: if i.instance.pk and i.instance.photo == '': i.instance.delete() elif i.cleaned_data: temp = i.save(commit=False) temp.listing = form.instance temp.save() # Where the error happens def clean_photo(self): picture = self.cleaned_data.get('photo') # I had to import ImageFieldFile. If picture is already uploaded, picture would still be retrieved as ImageFieldFile. The following line checks the variable type of `picture` to determine whether the cleaning should proceed. if type(picture) != ImageFieldFile: image_field = self.cleaned_data.get('photo') image_file = BytesIO(image_field.read()) image = Image.open(image_file) image = ImageOps.fit(image, (512,512,), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file #if picture._size > 2*1024*1024: #raise ValidationError("Image file too large. Max size is 2MB.") return picture class OwnerListingPhoto(models.Model): listing = models.ForeignKey(OwnerListing, on_delete=models.CASCADE, related_name='owner_listing_photo') photo = models.ImageField(upload_to=owner_listing_folder_name) - 
        
Show the data points in tabular format in Html from Django
My goal is to print the data points of the DataFrame in Django to Html page, along with the index values. My views.py def view_data(request): data_cols = list(data.columns.values) # to retrieve the column names context_data_sample = { 'data': data_, #data_ contains the data in DataFrame 'columns': data_cols #contains the columns of the data frame } return render(request, 'polls/home.html', context_data_sample) HTML code {% for i in data %} <tr> <td>{{ i.columns }}</td> </tr> {% endfor %} Although I mentioned above that I would like to print with the index values I am stuck with projecting just the name of the variable and nothing else, for instance, if I have Passenger column it is showing the Passenger and nothing else. Could anyone help me in projecting my dataset with the index values for respective rows? Thanks in advance. - 
        
Django ORM: Group by and SQL Agregation
I know that exists any same topics there, but that are not described my situation :( I have a model below: class SecurityPrice (models.Model): security = models.ForeignKey(Security, on_delete = models.CASCADE) created = models.DateTimeField() price = models.FloatField() class Meta: ordering = ('-created',) def __unicode__(self): return u'%s - %s - %s' % (self.created, self.security.ticker, self.price) or in sqlite: CREATE TABLE IF NOT EXISTS "restful_api_securityprice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "price" real NOT NULL, "security_id" integer NOT NULL REFERENCES "restful_api_security" ("id")); And I want to select last prices for each security paper In raw SQL I may do it with such SQL-request: SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; Below Some Examples for understand my needs: All records from table sqlite> SELECT * FROM restful_api_securityprice; 1|2018-01-07 23:13:02|920.0|1 2|2018-01-07 23:13:43|137.12|2 3|2018-01-07 23:13:58|147.3|3 4|2018-01-09 00:46:29|920.0|1 5|2018-01-09 00:47:27|137.12|2 6|2018-01-09 00:48:08|147.3|3 A what I to need sqlite> SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; 2018-01-09 00:46:29|1|920.0 2018-01-09 00:47:27|2|137.12 2018-01-09 00:48:08|3|147.3 In raw SQL it's ok. But how I can do the same in Django ORM API without include raw sql? - 
        
Django Foreign key that could contain objects of different classes
is there a way to be able to use a foreign key to reference objects of diffrent classes for example, this is what i'm doing : Class discussion(models.Model): id_discussion = models.CharField(db_column='id_Discussion', primary_key=True, max_length=100) id_worker = models.ForeignKey('Worker', models.CASCADE, db_column='id_user', blank=True, null=True) id_director = models.ForeignKey('Director', models.CASCADE, db_column='id_user', blank=True, null=True) Class Message(models.Model): #some other fields id_sender = models.CharField(db_column='id_Sender', max_length=100, blank=True, null=True) id_receiver = models.CharField(db_column='id_Receiver', max_length=100, blank=True, null=True) id_discussion = models.ForeignKey('discussion', models.CASCADE, db_column='id_Discussion', blank=True, null=True) I want to turn id_receiver and id_sender into foreign keys, my problem is that the sender could be an object of class "Worker" or of class "Director". - 
        
Data from 1:n relation in Django into a flat file
I've spent quite some time googling, but none of the findings seem to fit my situation. I am ramping up a little data warehouse where I store all Facebook Posts of my pages and I do performance snapshots (impressions, clicks, shares, comments...) of every post every 20 minutes for the first week, so that I can build some prediction models for fresh posts in a later project on this dataset. This means that there is a 1:n relation between Post and Performance-Snapshot and every post has around 500 performance snapshots. For a start I just have to create a CSV-API for an external visualisation tool, so I need a flat file format for every post in a given time range together with it's final (i.e. latest) performance snapshot in the same line. And the problem is that I can't find a way to build the list of all posts and their latest performance snapshot in a single shot as I can do with JOINS in direct SQL. My slightly simplified models: class FBPost(models.Model): post_id = models.CharField(max_length=64, unique=True) type = models.CharField(max_length=32) message = models.TextField() description = models.TextField() created_time = models.DateTimeField() permalink_url = models.TextField(blank=True) class Meta: get_latest_by = 'created_time' class FBPostPerformance(models.Model): post_id … - 
        
null=True,blank=True but still error may not be null is raised everytime during post
my model: Assets(modes.Model): assset_code=models.CharField(max_length=12,null=True,blank=True) In my serializers.py: asset_code=serializers.CharField(max_length=12,allow_blank=True,required=False) When I post data, it still says this field may not be null. It lets me pass only if I put data. While I am at it, whats the correct way to make JSONField() optional in serializers too? - 
        
How does Django handle multiple requests?
How does Django handles multiple requests in production environment? Suppose we have one of web server: Apache, Nginx, gunicorn etc. So do those servers for any request from web browser start new process to serve that request? If it's true, doesn't it cause huge overhead? If it's not true, then how the same view (let it be def hello(request) view bound to /hello url) serve several requests at the same time. I've seen answers for question "... handle multiple users" - 
        
How to match any url using path() method django
I have a project called gigi and app called account. Inside gigi/urls.py i have the following code urlpatterns = [ path('account/',include('account.urls')), ] Inside account/urls.py urlpatterns = [ path('', views.dashboard, name="dashboard"), ] I want to include authentication urls from django.contrib.auth.urls using include('django.contrib.auth.urls')) How can i include it so that any url that doesn't match '' inside account.urls be get looked up inside auth urls - 
        
Django Attribute Error: Type Object has no attribute 'all'
I am running into this error at my Django 2.0.2 (Python 3.6.4) project: AttributeError at /upload/ type object 'Tag' has no attribute 'all' The idea is to have tasks and to add one or more tags to each task. The task models reference to the tag class is tags = models.ManyToManyField(Tag, blank=True) and works fine in the admin interface. Now when I call my upload form the error above shows up. Here is the upload form class UploadForm(forms.Form): title= forms.CharField(label='Tasktitle', max_length=255) data= forms.FileField(label='Data') tags = forms.ModelMultipleChoiceField(Tag) The upload view is def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): newTask = Task(titel=request.POST['title'], tags=request.POST['tags'], data=request.FILES['data']) newTask.save() return HttpResponseRedirect('success/') else: form = UploadForm() return render(request, 'upload/upload.html', {'form': form}) I tied to adjust the different parameters, but I can't figure out where the call for an 'all' attribute comes from. If you need more information or clarification just add a comment. Thank you very much. - 
        
PyCharm VENV doesn't launch
I was working in PyCharm on a Django project when I decided to move my project folder to a different location. After I moved the project and opened it, PyCharm stopped automatically launching the virtual environment on startup. On PyCharm launch I get this error in the terminal: bash: source: /Users/Alex/Documents/Projects/MyProject: is a directory I tried reselecting the interpreter, changing the path in the activate files of the venv, but nothing seems to work. I even tried moving the project to the original location, but it still doesn't launch venv. The new address of my project is /Users/Alex/Documents/Projects/MyProject-API/venv/... All other projects that stayed where they were created have venv running when I open them. I also know that I can launch venv manually, but I'm trying to figure out the reason of this frustrating problem. The PyCharm setting all seem to be in order. Do I need to change the script and indicate a new path to my venv somewhere? Any help would be appreciated - 
        
Django best practice: Should I split non-app specific models into my project folder?
I am going to extend the django user models - is it best practice to create a new models.py in my project directory: I.e: project application migrations static models.py (all my application specific models) project forms.py urls.py views.py *** project models.py ? *** I want to add email confirmation to my user sign up. So basically just extend the user model. I am thinking this may not be best practice to do in my application models, but for this case it is only going to be one model so would not really matter. However if I want to extend more non-application specific models then it might be better to do this in a separate file? Does anyone do anything similar and have any tips? Thanks - 
        
Django filter by date like "201803"
Srry for my english. I try create some filter list like ?date=201803 - its meen get all data 2018 years 03 month. This is my model: class TestModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) date = models.DateTimeField(blank=False) text = models.TextField(max_length=256, blank=False) This is my view: class TestView(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = TestSerializer queryset = TestModel.objects.all() filter_backends = (DjangoFilterBackend,) filter_fields = ('date',) but if i can view some date if do like this: ?date=2005-03-12T21:48:00Z field date = models.DateTimeField(blank=False) must be DateTimeField How can do request like this: ?date=201803 ? - 
        
How to run a python file from remote link by posting request from android application
I'm developing a mobile app that will use a python back-end for posting to MySql database.Normally I was using php link for the post purposes and tried it with python as well. protected void TrySignUp() { HttpURLConnection connection; OutputStreamWriter request = null; URL url = null; String response = null; String parameters = "username=" + mUserNameString + "&password=" + mPasswordString.hashCode()+"&email="+mEmailString+"$pic_link="+""; try { url = new URL("https://www.pythonanywhere.com/user/menimadim/files/home/menimadim/backend.py"); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); request = new OutputStreamWriter(connection.getOutputStream()); request.write(parameters); request.flush(); request.close(); String line = ""; InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Response from server after login process will be stored in response variable. response = sb.toString(); // You can perform UI operations here Toast.makeText(this, "Message from Server: \n" + response, Toast.LENGTH_LONG).show(); isr.close(); reader.close(); } catch (IOException e) { // Error Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } My question is: How can I run the python script from remote link as an API with Android. Any suggestion would be welcomed such as free server for beneficial usage. Please consider that I'm new python developer... - 
        
Django: Show existing data in ModelForm of another field
In my model CustomModel there is a field called file: file = models.OneToOneField('File', on_delete=models.PROTECT, editable=False, blank=True, null=True) The File model looks like this: class File(models.Model): file = models.FileField( upload_to=get_filepath, max_length=45, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ] ) original_name = models.CharField(max_length=45) extension = models.CharField(max_length=3) In my forms.py there is this: class CustomModelForm(forms.ModelForm): upload = forms.FileField(max_length=45, required=False, validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']), file_size, ],) My problem: When people edit the CustomModel then they can find all existing data. Only for the upload field that is not possible. My goal is to show the people, when they edit CustomModel, the content of CustomModel.file. However, in my CustomModelForm there I cannot show this field, but only the upload field. I need to show for the upload field the contet of CustomModel.file if available. I just don't know how to do this. - 
        
Innosetup Runhidden flag is not working
I have wrapped up my django project using pyinstaller and later used Innosetup to make installer. Since django command prompt running background looks ugly, I used runhidden flag in Innosetup.But when i click on desktop icon application starts running by hiding command prompt, and when i run once more time without closing previous opened app command prompt become visible. I want to make command prompt hidden always. For more details have a look on my ISS script: [Run] Filename: "{app}\{#MyAppExeName}"; Description: "Start Crumbs For Tableau"; Flags: waituntilidle postinstall runhidden skipifsilent - 
        
django.db.utils.IntegrityError: UNIQUE constraint failed: ProgrammerProfile_posts.author_id
So I am trying to make this website and I get this error while I was making changes to my models django.db.utils.IntegrityError: UNIQUE constraint failed: ProgrammerProfile_posts.author_id models.py- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Person(models.Model): id = models.IntegerField(primary_key=True) Name = models.CharField(max_length=255) age = models.IntegerField() Description = models.TextField() ProfilePic = models.FileField() def __str__(self): return self.Name class Posts(models.Model): id = models.IntegerField(primary_key=True) Name = models.CharField(max_length=255) post = models.TextField() author = models.ForeignKey('Person', on_delete=models.CASCADE) def __str__(self): return self.Name - 
        
AWS Kubernetes RDS connection
I'm having some trouble with my AWS Kubernetes instance. I'm trying to get my django instances to connect to the RDS service via the DB endpoint. DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ['NAME'], 'USER': os.environ['USER'], 'PASSWORD': os.environ['PASSWORD'], 'HOST': os.environ['HOST'], 'PORT': os.environ['PORT'] } } The host string would resemble this service.key.region.rds.amazonaws.com and is being passed to the container via env in the deploy.yml containers: - name: service env: - name: HOST value: service.key.region.rds.amazonaws.com This set up works locally in kubernetes but not when I put it in the cluster I have on AWS. It returns the following error instead: django.db.utils.OperationalError: could not translate host name Any suggestions or am I missing something in how AWS likes handling things? - 
        
Django TypeError, drop
I want to signed in user to be able to invite users to a 'team', where the teams they can select from are only those they are a part of. I keep getting the same error (init() missing 1 required positional argument: 'user') when I try and output a list of all teams in model UserTeams where the userID = current logged in user. My view: def invite(request): if request.method == 'POST': form = InvitePlayerForm(request.POST) if form.is_valid(): userteam = form.save(commit=False) userteam.save() else: form = InvitePlayerForm() query = UserTeams.objects.all() return render(request, 'teammanager/invite.html', { "invite": query, "form": form }) My Form: class InvitePlayerForm(forms.ModelForm): class Meta: model = UserTeams fields = ['userID','teamID'] def __init__(self,user,*args,**kwargs): super (InvitePlayerForm,self ).__init__(user,*args,**kwargs) self.fields['teamID'].queryset = Team.objects.filter(id__in = UserTeams.objects.filter(userID = user)) My UserTeams model: class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) My HTML: <html> <body> <h4>Invite players to your team</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-success" type="submit" value="Add Player"></button> </form> - 
        
Object list into chart labels not working
I have the next view, where I get three lists. 1-dates list 2-questions made by users in a time range. 3-answers of users in the same time range. views.py data_list_question = [] data_list_answer = [] timeline = [] for n in range(24,0,-4): t1 = timedelta(weeks=n) t2 = timedelta(weeks=n-4) c = today-t1 timeline.append(c) a = int(question.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count()) data_list_question.append(a) b = answer.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count() data_list_answer.append(b) Then I use this values in a scipt in the template like next: chart.html <script type="text/javascript"> $( document ).ready(function() { var ctx = document.getElementById("lineChartstats"); var lineChart = new Chart(ctx, { type: 'line', data: { labels: {{ timeline|date:"j b" }}, datasets: [{ label: "Questions", backgroundColor: "rgba(38, 185, 154, 0.31)", borderColor: "rgba(38, 185, 154, 0.7)", pointBorderColor: "rgba(38, 185, 154, 0.7)", pointBackgroundColor: "rgba(38, 185, 154, 0.7)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", pointBorderWidth: 1, data: {{ data_list_question}} }, { label: "Answers", backgroundColor: "rgba(3, 88, 106, 0.3)", borderColor: "rgba(3, 88, 106, 0.70)", pointBorderColor: "rgba(3, 88, 106, 0.70)", pointBackgroundColor: "rgba(3, 88, 106, 0.70)", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(151,187,205,1)", pointBorderWidth: 1, data: {{ data_list_answer }} }] }, }); }); </script> The problem is that the data for each dataset works, however the labels 'timeline' does not work. I do not know how to solve this problem. Thanks …