Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django self.save() not updating the status of the model
I have a very simple model and view py file for cats (trying to test out/learn basic features of django. However the cat's happiness status never really updated. class Cats(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) name = models.CharField(max_length = 200) description = models.TextField() happiness = 6 def pet(self): self.happiness = self.happiness+1 self.save() from django.shortcuts import render, get_object_or_404 from .models import Cats def cat_detail(request, pk): cat = get_object_or_404(Cats, pk=pk) return render(request, 'cats/cat_detail.html', {'cat': cat}) def cat_interact(request, pk, action): cat = get_object_or_404(Cats, pk=pk) pet = False if(action == 1): cat.pet() pet = True return render(request, 'cats/cat_interact.html', {'cat': cat, 'pet': pet}) action will always be 1 (that's the only current action possible). Inside the html file of both "detail" and "interact" I print out the happiness status of the cat. When I go to the interact page, the cat's happiness status is printed as 7 (since default/start happiness is 6). I expect this value (7) to be saved to the database and when I go to the detail page again it also prints 7. However, even after running the function cat.play() on the detail page it still prints 6, which is the default. Is the 7 never saved to the data base? … -
Chained drop down fileds
lets say that i have this 3 tables class Dhmos(models.Model): name = models.CharField(max_length=100,verbose_name='Πελάτης', blank=False) address = models.CharField(max_length=100,verbose_name='Διεύθυνση', blank=True,default='-') city = models.CharField(max_length=100,verbose_name='Πόλη', blank=True,default='-') phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) fax = models.CharField(max_length=50, verbose_name='Fax', blank=True) teamviewer = models.CharField(max_length=60, verbose_name='TeamViewer', blank=True) email = models.EmailField(blank=True) website = models.URLField(max_length=250, blank=True, null=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Meta: verbose_name = 'Πελάτες' verbose_name_plural = 'Πελάτες' ordering = ['id'] def __str__(self): return self.name class Employee(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', null=True) firstname = models.CharField(max_length=150, verbose_name='Όνομα', null=True) lastname = models.CharField(max_length=150, verbose_name='Επώνυμο', null=True) tmhma = models.CharField(max_length=100, choices= tmhma_choice, verbose_name='Υπηρεσία', blank=True) phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) cellphone = models.CharField(max_length=30, verbose_name='Κινητό', blank=True) email = models.EmailField(blank=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Ergasies(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', default='-') importdate = models.DateField(default=datetime.date.today,verbose_name='Ημ. Κατ.') app = models.CharField(max_length=100, choices=app_choice,verbose_name='Εφαρμογή', blank=True) jobtype = models.CharField(max_length=100, choices=job_choice, verbose_name='Τύπος Εργασίας', default='TeamViewer') info = models.TextField(max_length=1000, verbose_name='Περιγραφή') text = models.TextField(max_length=1000, verbose_name='Σημειώσεις', blank=True) employee = models.ForeignKey('auth.User', max_length=100, verbose_name='Υπάλληλος', on_delete=models.CASCADE,default='-')#delete kai time = models.CharField(max_length=20,verbose_name='Διάρκεια', default=0) name = models.CharField(max_length=100, verbose_name='Υπάλληλος Επικοιν.', null=True,help_text='Επώνυμο-Όνομα', blank=True) ticketid = models.CharField(max_length=50,verbose_name='Αίτημα OTS', blank=True) When i add a record to Ergasies table i want when i choose Dhmos to filter the Employees and display only employees related to Dhmos. How can i do that, … -
dash_bootstrap_components.min.js not found when running Dash inside Django
I am getting dash_bootstrap_components.min.js not found when i try to integrate Dash with Django. Installed dash_bootstrap_components for Dash css Dash Python: external_stylesheets = ['https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'] app = DjangoDash('SIPPage',external_stylesheets=external_stylesheets) -
Django model.delete() reseed primary key
Busy developing my Django app and as it goes I have test data that I would like to delete from some of my tables. How can I delete the entries and "reset" the primary keys so that the next time an element is inserted, it has id=1? When I run .delete() I am able to delete the row, but the primary key is not reset. According to a bit of research this is standard with databases and I need to truncate the table. Some suggestions are to Truncate the table with raw SQL code: import sqlite3 conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() cur.execute("TRUNCATE TABLE 'table'") which does not seem to work and just gives the following error: OperationalError: near "Truncate": syntax error Other suggestions are to comment out the model and redo migrate. This is not an option either as there are multiple dependent foreign keys across the tables. Is there no way to reset the primary key of a table? -
Restrict options to a ChoiceField Django
thanks for your time: i'd like to know if there is a way to restrict an option on a choicefield if other field starts with a letter 'A': basically i want to don't let the user set the choice (2, 'GATO') on Animal.tipo if his name starts with letter 'a' on People.nome models.py: from django.db import models from django.core.validators import RegexValidator class People(models.Model): nome = models.CharField(max_length=200) birthday_date = models.DateTimeField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) class Animal(models.Model): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] pessoa = models.ForeignKey(People, on_delete=models.CASCADE) name = models.CharField(max_length=100) tipo = models.IntegerField(choices=field_choices) custo = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return '%s %s' % (self.pessoa, self.name) def cant_have_cat(self): self.maiusculo = self.pessoa.upper if self.maiusculo[0] == 'A': self.tipo != 2 -
PostgreSQL psycopg2 error: there is no unique constraint / InvalidForeignKey
I have the following models: class Contact(models.Model): email = models.EmailField() class EventList(models.Model): event_contacts = models.ManyToManyField(Contact, through=EventMembership) class EventMembership(models.Model): event_list = models.ForeignKey(EventList, null=True, on_delete=models.PROTECT) event_contact = models.ForeignKey(Contact, null=True, blank=False, on_delete=models.PROTECT) However, when applying migrations for EventMembership on a completely clean database I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "contacts_contact" class Migration(migrations.Migration): initial = True dependencies = [ ('lists', '0001_initial'), ('contacts', '0002_auto_20200308_2253'), ] operations = [ migrations.CreateModel( name='EventMembership', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('event_contact', apps.utils.django_multitenant.fields.TenantForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='contacts.Contact')), ('event_list', apps.utils.django_multitenant.fields.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='lists.EventList')) ] ] Table contacts_contact clearly has a unique constraint in id as the primary key. What could be causing this error? / How do I debug this? -
How to create a subscriber with PubSub on Google Cloud App Engine that listens to a message via Publisher from a Google Cloud App Engine Flex?
I have a Django Application running on Google App Engine. There is another time consuming application running in Google App Engine Flex that is triggered from the Google App Engine Application. When the Google App Engine Flex Application finished its execution, I want it to trigger a message and send it to Google App Engine Django Application, so Django can update the database item accordingly. How can I use Google Cloud PubSub to achieve this? -
Loops through other loops
Loops through other loops I am trying to insert data from views.py context. How can I avoid in this case looping through other loops. How can I fix it?I am fetching data from wiki by using beautifulsoup. Uploading Image. template.html {%extends 'profilecontent/base.html' %} {%block content%} <div class="container-home"> <div class="home-wrapper home-wrapper-first"> <p class='home-matches'>Przyszłe mecze <span class='home-week'>W3 D2</span></p> <div class="match-wrapper"> <table> {%for second_team in second_team_names%} {%for first_team in first_team_names %} {%for hour_game in hours_games%} <tr><td>{{first_team}}</td><td>{{hour_game}}</td><td>{{second_team}}</td></tr> {%endfor%} {%endfor%} {%endfor%} </table> </div> </div> <div class="home-wrapper home-wrapper-second"> </div> </div> {%endblock%} views.py from bs4 import BeautifulSoup import requests def home(request): source = requests.get('https://lol.gamepedia.com/Ultraliga/Season_3').text soup = BeautifulSoup(source, 'lxml') first_team_names = [] second_team_names = [] td1s = None td2s = None hours_games = ['17:30', '18:30', '19:30', '20:30'] tables = soup.find_all('table', class_='wikitable matchlist') for table in tables: td1s = table.find_all('td', class_='matchlist-team1') td2s = table.find_all('td', class_='matchlist-team2') for td in td1s: span = td.find('span') first_team_names.append(span.text) for td in td2s: span = td.find('span') second_team_names.append(span.text) context = { 'first_team_names':first_team_names, 'second_team_names':second_team_names, 'hours_games':hours_games, } return render(request, 'profilecontent/home.html', context) -
How to connect a database is MySQL Workbench to my website deployed with IIS
I deployed my django project through IIS and have my database stored in mySQL workbench. Can anyone tell me how to connect my website to the MySQL workbench database? Everything I'm finding is very old, 2008/2009, and the instructions are not supported anymore. -
How to show only one object if there's multiple equal objects in Django?
I am sorry for the title but this is the best way I can explain it. I have a trips model that has in_flights and out_flights associated to a Client. I wanted to show which Clients have trips after now so I did the following: ClientsArriving = Client.objects.filter(trip__in_flight__date__gt=timezone.now()) ClientsLeaving = Client.objects.filter(trip__out_flight__date__gt=timezone.now()) ClientsDash = ClientsLeaving | ClientsArriving The problem is, if one Client has an in_flight and an out_flight in the same trip, it will display twice. How can I show the trip only one time? -
Django unable to access admin login page after creating superuser
i am a new python Django learner for the first time i have a problem with access and login admin after creating superuser account python version : 3.7.0 Django version : 3.0.4 below is models.py and i migrated with it. checked my db with sqlite3 which has no problem class Fcuser(models.Model): username = models.CharField(max_length=64, verbose_name='username') password = models.CharField(max_length=64, verbose_name='passward') registed_dttm = models.DateTimeField(auto_now_add= True, verbose_name='regstedtime') this is the urls.py never changed anything from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] after that, i created a superuser which is successfully done. i started the server with "python manage.py runserver" and access to 127.0.0.1:8000 it is possible to access to access 127.0.0.1:8000 but the problem is... when i try to access to 127.0.0.1:8000/admin there are 3 cases showed up cannot access to the admin page without any error msg. it seems it is automatically shutdown the server. can access to the admin page sometimes but after trying to login with superuser account, it automatically shutdown the server without any error msg again trying to access again with other browser, able to access admin page first but cannot login with the superuser account again, also shows no error … -
How to validate multiple fields in model clean method in Django
In my Django model I am using clean() method to validate two sets of fields' values. I am housing both the conditions in the same clean() method. However I find that the first condition is checked by the system and the second one is ignored. Here is my model and the fields: class Rates(models.Model): master_doc = models.ForeignKey(Origin, ... exit_rate = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0.00) from_date = models.DateField(null=True, verbose_name='From date') to_date = models.DateField(null=True, verbose_name='To date') def clean(self): if self.exit_rate <= 0: raise ValidationError({'exit_rate': _('The exit rate must more than 0.')}) if self.from_date is not None: if (self.to_date == self.from_date): raise ValidationError({'to_date': _('From Date and end date may not be same.')}) In this instant case, validation error is raised only for the first i.e. field exit_rate. If I reverse the order of the check, validation error is raised for the date fields alone, and not the rate field. I tried this solution and used error_dict but getting error 'ValidationError' object has no attribute 'error_list' How do I ensure that validation error is raised in case either of the conditions are not met? -
Indexing does not work when using postgres with Django
So, the issue is pretty simple but I couldn't find any info related to it >>> Match.objects.all()[0].team_set.all() <QuerySet [<Team: EG>, <Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[1:2] <QuerySet [<Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[0:1] <QuerySet [<Team: Liquid>]> >>> Match.objects.all()[0].team_set.all()[0] <Team: Liquid> >>> Match.objects.all()[0].team_set.all()[1] <Team: Liquid> Basically it refuses to give me ForeignKey object by its index. Any ideas? -
In command line, what does "python file.py shell" do?
I have run into a Django tutorial where the instructor is running python manage.py shell. This yields: (env) MBP:Project user$ python3 manage.py shell Python 3.7.6 (default, Jan 8 2020, 13:42:34) [Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Couple questions: What does shell do in python manage.py shell? What does (InteractiveConsole) in the above mean ? I don't see this when I run python without the shell. I have googled InteractiveConsole to no avail. What is "being done" to manage.py here? Is it being "run" or "served"? -
Return extra Fields along with model fields in JSON - Django
I am using a Modelserializer to serialize data. In one of the cases, I have to send some extra fields other than model fields to the UI. How can I do that? Below is my code - My Model - class Group(models.Model): groupID = models.AutoField(primary_key=True, db_index=True) groupName = models.CharField(verbose_name="Name", max_length=30) sectionID = models.ForeignKey(Section, on_delete=models.PROTECT, db_column='sectionID') My Serializer - class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['groupID', 'groupName', 'sectionID'] My View - @api_view(['GET']) @permission_classes((permissions.IsAuthenticated,)) def getGroupInfo(request): groups = models.Group.objects.all() for group in groups: group.logical_fied = True if <Custom condition> serializer = GroupSerializer(groups, many = True) return Response(serializer.data) Expected response on UI [{ "groupID":1, "groupName":"A", "sectionID":1, "logical_field":True }] Response I am getting [{ "groupID":1, "groupName":"A", "sectionID":1 }] In my serializer.data, I don't get logical_field on the UI as it is not defined in GroupSerializer. Is there any way to achieve this? -
Git merge: conflict I don't know how to resolve
I have a Django project on Git I am not very confortable with Git I have juste finalized, commit and push my feature/22 branch I have commit (after git add .) and push my master So my two branchs are up to date Now, I would like to merge my master with my feature/22 locally but I have an conflict Even after commit, I have 2 files in "Unmerge paths" : Unmerged paths: (use "git add <file>..." to mark resolution) both modified: unblind/migrations/__pycache__/0002_auto_20200124_0904.cpython-37.pyc both modified: unblind/migrations/__pycache__/0003_auto_20200124_1007.cpython-37.pyc What if I use the recommanded command git add? Why these 2 files were not contained in the previous git add . command? -
Django choice field filter the choices
Eu tenho esse meu campo choicefield no meu models onde tem três opções ("Administrador", "Professor", "Bolsista") Porém o que eu quero mostrar na hora de criar um usuario é ("Professor","Bolsista") sem tirar a opção administrador models.py class Usuario(AbstractBaseUser): #1 campo da tupla fica no banco de dados #2 campo da tupla eh mostrado para o usuario TIPOS = ( ('ADMINISTRADOR', 'Administrador'), ('PROFESSOR', 'Professor' ), ('BOLSISTA', 'Bolsista' ) ) USERNAME_FIELD = 'email' tipo = models.CharField(_(u'Tipo do usuário'),null=False, blank=False, max_length=15, choices=TIPOS, default='PROFESSOR') views.py class UsuarioRegisterView(CreateView): model = Usuario template_name = 'usuario/usuario_register_form.html' fields = [ 'nome' , 'email' , 'tipo' , 'password' ] def form_valid(self, form): self.object = form.save(commit=False) self.object.is_active = False self.object.tipo = 'PROFESSOR' self.object.save() return super(UsuarioRegisterView, self).form_valid(form) def get_success_url(self): message = EmailMessage('usuario/email/validacao_email.html', {'usuario': self.object}, settings.EMAIL_HOST_USER, to=[self.object.email]) message.send() return reverse('usuario_register_success') usuario_register_form.html {% extends "usuario/usuario_register_base.html" %} {% load bootstrap3 %} {% block actions %} {% endblock %} {% block title %} {% bootstrap_icon 'user' %} Cadastro de usuário {% endblock %} {% block content %} <form class="form" role="form" method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% bootstrap_form form %} {% buttons submit='Gravar' %} <a href="javascript:history.go(-1);" class="btn btn-info" role="button">Voltar</a> {% endbuttons %} </form> {% endblock %} -
Django Aggregation with a Model that has two foreign key fields pointing to same foreign Model?
I have this model: from reviews.models import * from django.db.models import Count class Review(models.Model): user = models.ForeignKey('core.User') status = models.CharField(default='5 star', max_length=100) reviewed_date = models.DateField(default=datetime.date.today, blank=True, null=True) reviewer = models.ForeignKey('core.User', related_name='reviewer', null=True) I can list the top 5 Review.user's with the most Reviews like this: for u in User.objects.annotate(num_reviews=Count('review')).order_by('-num_reviews')[:5]: ... print u.login, u.num_reviews, u.title ... bobby 395 Manager paul 377 Project Manager micheal 283 Program Manager kim 252 Engineer goober 210 Engineer But how can I list the top 5 Review.reviewers? -
Why does nulls_last=False not put the nulls first in Django?
I'm finding that while nulls_last=True works, nulls_last=False doesn't. Example below is in a Django shell. In [10]: [x.date for x in Model.objects.all().order_by(F('date').asc(nulls_last=True))] Out[10]: [datetime.datetime(2020, 3, 10, 16, 58, 7, 768401, tzinfo=<UTC>), datetime.datetime(2020, 3, 10, 17, 4, 51, 601980, tzinfo=<UTC>), None, ] [ins] In [11]: [x.last_run_created_at for x in Model.objects.all().order_by(F('date').asc(nulls_last=False))] Out[11]: [datetime.datetime(2020, 3, 10, 16, 58, 7, 768401, tzinfo=<UTC>), datetime.datetime(2020, 3, 10, 17, 4, 51, 601980, tzinfo=<UTC>), None, ] In [12]: I've tried this with both desc() and asc(). -
How to send the value of two dependent dropdowns via an AJAX post request to a Django view?
I'm currently trying to send the values of two dropdowns to a django view. My code would have worked properly had the dropdowns been independent. The problem is that it isn't the case. The first one updates the second one, so I need to make my AJAX post request once the second dropdown has been updated. Here is my current html/Javascript code: <select name="d1" class="toChange"> {% for item in items1 %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <select name="d2"> {% for item in items2 %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <script type="text/javascript"> function dropdownChange () { var value_d1 = $(".toChange option:selected").val(); var value_d2 = $("select[name=d2] option:selected").val(); $.ajax({ url: '/myApp/templates/', type: 'POST', data: {'d1': value_d1, 'd2': value_d2}, success: function(data) { var str = ''; data.forEach(function(opt){ str += '<option value="' + opt + '">' + opt + '</option>'; }); document.getElementById("d2").innerHTML = str; } }); $(".toChange").change(dropdownChange); So here the change in d1 updates d2 but the AJAX call is made before d2 gets updated and therefore sends the wrong value to my view. How can I overcome this issue? -
How to use pytest's live_server fixture in docker
I am trying to test my app with selenium and pytest. I want to use the live_server fixture for this because I need my tests to be self contained. Pytests offers this fixture and I do this: def test_user_can_visit_website_with_chrome(live_server): """Visit website with chrome browser. """ browser = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME ) browser.get(live_server.url) assert 'mywebsite' in live_server.title I can see in my VNC that it connects and visits the site localhost:42345 . If I run it again it uses a different port. I can see in my VNC that it says: ++ localhost: refused to connect. ERR_CONNECTION_REFUSED if I don't use the liveserver but a normal url I get: selenium.common.exceptions.SessionNotCreatedException: Message: session not created E from disconnected: Unable to receive message from renderer I can get it to work using djangos inbuilt LiveServerTestCase but I don't want to use it since I get problems with my fixtures and my whole setup. I set the ALLOWED_HOSTS everywhere to ['*']. I don't know how to solve this. Anyone any ideas? Thanks so much for any help!! Appreciated a bunch! My dockerfile looks like this: services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: mywebsite depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - … -
Django loggin in AWS
I was just wondering what is the current best way to perform logging within Django and AWS. I was looking at this article, which suggested writing to the following location, but I have found that this doesn't work: /opt/python/log Then use commands such as command: chmod g+s /opt/python/log command: chown root:wsgi /opt/python/log I have also seen articles that suggest using watchtower, but I don't like the idea of adding my secret access keys into the code: https://medium.com/@zoejoyuliao/plug-your-django-application-logging-directly-into-aws-cloudwatch-d2ec67898c0b What is the current and best way to do this ? Thanks -
for python 3.7.6 which myql-client version is supported
for python 3.7.4 the myqli client library is supported which is given below mysqlclient-1.4.4-cp37-cp37m-win32.whl but i have python 3.7.6 which mysql-client wheel is supported Any Help would be appreciated -
Adding IntegerField along with multiselectField?
I've been using MultiSelectField to select multiple list items, but after selecting I want to add their quantity too? Like a solution to add IntegerField alongside with the multiselectfield?? -
Django App: Timezone issues when running my Heroku app?
I'm creating a scheduling app on Django. As per most recommendations on the topic, the appointments (in my Appointments model) are stored in UTC. So my settings.py are set to TIME_ZONE = 'UTC'.The app was working perfectly on my local environment, but when I deployed to Heroku I started having issues. To give you an example (in production): >>> heroku run bash >>> python manage.py shell >>> from datetime import datetime >>> datetime.now() datetime.datetime(2020, 3, 10, 17, 10, 10, 453536) Yet, on local, I get: datetime.datetime(2020, 3, 10, 13, 10, 10, 196794) I tried to solve the issue (ie, 4-hour difference) by changing the TZ config value of the app to my local time, like so: heroku config:add TZ='America/Toronto' No luck. Anyone understands why this is happening? Any suggestions on how to solve this?