Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I update heroku requirements.txt?
I've had pkg-resources==0.0.0 in my requirements.txt so heroku can't run the app. After removing this string and commiting it still can't. Tried to remove whole project and create new -- nothing. If I commit again I see "nothing to commit, working tree clean" remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.8 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Django==2.2.3 (from -r /tmp/build_00cd1392df5f26408e135a402fc2038d/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/39/b0/2138c31bf13e17afc32277239da53e9dfcce27bac8cb68cf1c0123f1fdf5/Django-2.2.3-py3-none-any.whl (7.5MB) remote: Collecting pkg-resources==0.0.0 (from -r /tmp/build_00cd1392df5f26408e135a402fc2038d/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_00cd1392df5f26408e135a402fc2038d/requirements.txt (line 2)) (from versions: ) remote: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_00cd1392df5f26408e135a402fc2038d/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed -
Why django is adding an extra slash / in the last , i want to remove it?
I am getting an extra slash in the end it is giving me error , but when i remove the slash after 2 (i.e. from last) i am getting my result.enter image description here http://127.0.0.1:8000/book/2/ -
Django Messages + Pinax
I get this error when I try to install pinax notifications together with django messages: django_messages.Message.sender: (fields.E304) Reverse accessor for 'Message.sender' clashes with reverse accessor for 'Message.sender'. HINT: Add or change a related_name argument to the definition for 'Message.sender' or 'Message.sender'. django_messages.Message.sender: (fields.E305) Reverse query name for 'Message.sender' clashes with reverse query name for 'Message.sender'. HINT: Add or change a related_name argument to the definition for 'Message.sender' or 'Message.sender'. pinax_messages.Message.sender: (fields.E304) Reverse accessor for 'Message.sender' clashes with reverse accessor for 'Message.sender'. HINT: Add or change a related_name argument to the definition for 'Message.sender' or 'Message.sender'. pinax_messages.Message.sender: (fields.E305) Reverse query name for 'Message.sender' clashes with reverse query name for 'Message.sender'. HINT: Add or change a related_name argument to the definition for 'Message.sender' or 'Message.sender'. Where can I change the fields? I cant find them in dist-packages Thank you -
Running my own daemon on Heroku, how can I contact it from the Internet?
I have a Django application that runs fine on Heroku. At this point, I'd like to start a second process that implements a daemon that exchanges data with other devices and populates the database of the Django app. I implemented this second daemon as a custom command of a Django app, so in my Procfile I have web: gunicorn portal.wsgi --log-file - listener: python manage.py listen_to_devices At this point I start the daemon with heroku ps:scale listener=1. Devices are not able to connect. While debugging, I noticed that my app has several entries in the DNS, I guess for load balancing: ottavio@debian:~$ nslookup xxx.herokuapp.com Server: 192.168.69.2 Address: 192.168.69.2#53 Non-authoritative answer: Name: xxx.herokuapp.com Address: 52.51.85.80 Name: xxx.herokuapp.com Address: 52.212.106.249 Name: xxx.herokuapp.com Address: 54.171.30.127 Name: xxx.herokuapp.com Address: 54.171.254.93 Name: xxx.herokuapp.com Address: 54.194.235.52 Name: xxx.herokuapp.com Address: 99.80.174.196 Name: xxx.herokuapp.com Address: 52.18.173.71 Name: xxx.herokuapp.com Address: 52.48.204.199 ottavio@debian:~$ So, I guess I am doing something wrong. Port 8080 does not seem to be open whenever I try to telnet to it. How can I have my devices reach my daemon port? -
Send form context through an html file by mail
I want to send the context of my form rendering an HTML template, which I send by mail, but it sends me on behalf of the fields. Not the data that is entered in the fields. I've tried several tags in the html file like: {{form.name_field}}. But it doesn't show the information my funtion or views.py def solit(request): """Gestion de solicitudes""" if request.method == 'POST': form = SolitForm(request.POST) if form.is_valid(): form.save() subject = 'Bienvenido {}'.format(request.user) from_email = 'xxxxxn@xxxx.com' html_content = render_to_string('plantillas/mailsended.html', {'form':form,'user':request.user}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, ['xxxxxxxx@xxxxx.com']) msg.attach_alternative(html_content, 'plantillas/mailsended.html') msg.send() print (form) return redirect ('home') else: form = SolitForm() return render(request, 'plantillas/testform.html', {'form':form}) my forms.py class SolitForm(forms.ModelForm): class Meta: """Formulario de solicitud""" model = peticion fields = [ 'disponer', 'razon2', 'periodo_init', 'periodo_fin', 'horas_r', 'dias_r', ] labels = { 'disponer':'Tipo de Solicitud', 'razon2':'Razon', 'periodo_init':'Rango de fecha inicial', 'periodo_fin':'Fecha final', 'horas_r':'Dias a adicionar, si es mas de 8 horas', 'dias_r':'Horas a adiciona, si es menos de 1 dia', } my models class peticion(models.Model): #Modelo para (solicitar vacaciones y reportar tiempo) peticion_choice = ( ('Reportar', 'Reportar Tiempo'), ('Vacaciones', 'Vacaciones') ) disponer = models.CharField(max_length=255, choices=peticion_choice, null=True, blank=False) usuario = models.ForeignKey(users, on_delete=models.CASCADE, null=True, blank=True) razon2 = models.TextField(max_length=255, null=True, blank=False) periodo_init = … -
Django CreateView reload without double submitting
I'm trying to add data to a createview on form save (using a modal), and then just close the modal and stay on the same page OR reload page. However when I reload the page the data saves twice. I've tried multiple changes but nothing seems to help. Im new to coding, apologies if this is simple. Would sincerely appreciate any help! My views.py @login_required(login_url="/login") # Home (Logged In Dashboard) page view def vhome(request): prescription_table = Prescription.objects.filter(veterinary_practice = request.user.veterinary_practice) # veterinary practice id context = {'prescription_table': prescription_table} return render(request, 'app/veterinary/vhome.html', context) class PrescriptionCreateView(BSModalCreateView): template_name = 'app/veterinary/snippets/create_prescription.html' form_class = PrescriptionForm def form_valid(self, form): form.instance.prescription_type = 'Prescriber-Initiated' # prescription type form.instance.status = Prescription_status.objects.get(pk=2) # draft status form.instance.veterinary_practice = self.request.user.veterinary_practice # veterinary practice id form.instance.save() return redirect('vhome') -
Django restframework as a backend for offline first mobile app
I've just finished django app for mutliple choice questions. However,I wanted to develop Ionic android app version of the web app. It's my first app and I am still learning web development. I'm not sure if Django RestFramework or firebase backend is more suitible for offline first app,particularly with respect to mostly text based questions. -
How to get primary key inside detailview and use to pre fill a hidden field in a form?
I have two models: Properties and Bedroom, which are connected through a foreign key "Property" on the Bedroom model. #models.py class Property(models.Model): property_reference = models.CharField(db_column='Property_Reference', max_length=10, unique=True) # Field name made lowercase. address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase. post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase. bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase. bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase. usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase. notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. feature_image = models.ImageField(upload_to='properties',null=True) class Meta: db_table = 'Property' def __str__(self): return self.property_reference def get_absolute_url(self): return reverse("properties:property_detail",kwargs={'pk':self.pk}) class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True, blank=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom') I have a Property DetailView Class that shows all the details on my template at "property-detail.html". Also on my template I have a button like this: <a class="btn btn-secondary float-right" href="{% url 'properties:add_bedroom' pk=object.pk %}"><i class="fas fa-plus-circle"></i> Add New</a> This … -
Push rejected, failed to compile Python app in heroku (Python Crash Course)
I am working through the learning log project in Python Crash Course by Eric Matthes, specifically working on the learning log app. I am trying to deploy to heroku but get this error: (ll_env) C:\Users\benpg\Documents\Coding\Python\learning_log>git push heroku master Enumerating objects: 54, done. Counting objects: 100% (54/54), done. Delta compression using up to 4 threads Compressing objects: 100% (46/46), done. Writing objects: 100% (54/54), 16.54 KiB | 940.00 KiB/s, done. Total 54 (delta 4), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.7.4 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to pacific-refuge-12657. remote: To https://git.heroku.com/pacific-refuge-12657.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/pacific-refuge-12657.git' Tried everything here including the two other questions linked at the start, no luck. Here's my requirements.txt: Django==1.8.4 dj-database-url==0.3.0 dj-static==0.0.6 django-bootstrap3==6.2.2 gunicorn==19.3.0 static3==0.6.1 psycopg2>=2.6.1 -
Why does get and filter work differently for annotated fields?
I have a get_queryset in a custom Manager for a Model that renames fields: class Manager: def get_queryset(self): return super(Manager, self).get_queryset().values(renamed_field=F('original_field')) Why is it that I can do a .filter on the renamed field but when I do a .get I need to use the original field name? This works: Model.objects.filter(renamed_field='Test') But this errors out with matching query does not exist: Model.objects.get(renamed_field='Test') -
How to run for loops in template? (django)
I want to run the for loop to show all images but the problem is that I have to change the "id" of each image (pic-1 -> pic-2 ...so on) I know how to do it in normal python but I'm lose on how to do this in template of django. Please someone help me out? <div class="preview-pic tab-content"> <div class="tab-pane active" id="pic-1"><img src="{{product.image.url}}"></div> {% for image in image_list %} <div class="tab-pane" id="pic-2"><img src="http://placekitten.com/400/252" /></div> <div class="tab-pane" id="pic-3"><img src="http://placekitten.com/400/252" /></div> <div class="tab-pane" id="pic-4"><img src="http://placekitten.com/400/252" /></div> <div class="tab-pane" id="pic-5"><img src="http://placekitten.com/400/252" /></div> {% endfor %} </div> <ul class="preview-thumbnail nav nav-tabs"> <li class="active"><a data-target="#pic-1" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li> {% for image in image_list %} <li><a data-target="#pic-2" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li> <li><a data-target="#pic-3" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li> <li><a data-target="#pic-4" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li> <li><a data-target="#pic-5" data-toggle="tab"><img src="http://placekitten.com/200/126" /></a></li> {% endfor %} </ul> </div> -
Selenium - show notes about what is going on in browser
I'm working on Selenium test which simulates every User action on my website. From registration to modifying forms etc. There are hundreds of actions so I would like to see what is currently going on. Is there a way to add some notes to Selenium so I can see them in the browser real time? For example some transparent overlay with text? I think it is possible to create a workaround using AJAX but maybe there is something built in. -
How to get multiple files from a django FileField after model form object has been saved when form.save() does not return object
I have a django form class that extends django-postman's WriteForm (which is a ModelForm) with an additional field to upload some files. from postman.forms import WriteForm class MyWriteForm(WriteForm): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) However, I need the saved model before I can do anything with the files. If I follow the example in the docs, I can extend postman's FormView and overwrite the save() method: from postman.views import FormView class MyFormView(FormView): form_class = MyWriteForm def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: # Do something with each file. result = form.save() # result is a Boolean instead of the object! return self.form_valid(form) else: return self.form_invalid(form) However, django-postman WriteForm's save() method does not return the object as expected, and instead returns a Boolean. Is there any other way I can get the ModelForm's object after it is saved? Either through the view or the form? -
Transferring django settings to Environment Variables
I set the django project settings and added values to environment variables at my local ubuntu mashine and AWS Ubuntu server using .bashrc file at the root folder. ... export DEBUG="True" ... At local all working good, but at production server values are not importing. Why doesn't it work on both machines? How do I set up production? -
Django Import-Export Importing with User object failing
I am attempting to import data using the Import-Export library. I have a User foreign key in my model called creator, and rather than referencing the pk of the User i want to use usernames. But when i try to import the data it fails Some other Stack posts have suggested adding a skip feature, or creating a custom widget that queries the database first but that is also not working. model class MediaEntry(models.Model): media_number = models.CharField(max_length=20, default=increment, editable=False) media_designation = models.ForeignKey(MediaDesignation, null=True, on_delete=models.SET_NULL) creator = models.ForeignKey(User, on_delete=models.CASCADE) date_used_or_received = models.DateTimeField(default=timezone.now) resources from import_export import resources, fields, widgets from import_export.widgets import ForeignKeyWidget from .models import BlankMedia, MediaLocations, AuditLocation, MediaType, MediaEntry from django.contrib.auth.models import User class MediaEntryResource(resources.ModelResource): creator = fields.Field( column_name='creator', attribute='creator', widget=ForeignKeyWidget(model=User, field='username') ) class Meta: model = MediaEntry fields = ('id', 'media_number', 'creator',) Admin from .resources import BlankMediaResource, MediaLocationResource, MediaTypeResource, AuditLocationResource,MediaEntryResource class MediaEntryAdmin(ImportExportModelAdmin): resource_class = MediaEntryResource If the code worked it should preview the imported values but it fails with NOT NULL constraint failed: medialog_mediaentry.creator_id -
How to save queryset directly to redis?
I'd like to save results of Django QuerySets directly into redis cache instead of using Django's built in cache. The reason is to use a separate redis db for certain queries, in order to accelerate data retrieval. Here is my sample code: def cached_post(id): r = redis.StrictRedis(unix_socket_path='/tmp/redis.sock', db=6) key = "post:" + id if not r.get(key): post = Post.objects.get(pk = id) r.set(key, post, AN_HOUR) return r.get(key) But I get this error: cannot concatenate 'str' and 'long' objects So clearly simple string is not the correct data type to use to store querysets but I don't know what redis data type should I use and how? I have check the docs but not seen any such example, or hints about the data type which django cache.setuses to save querysets. -
Django add unique constraint only for new records
I have a django model: from django.db import models class TestModel(models.Model): name = models.CharField("Name", null=False, blank=False, max_length=300) After some time I got a task to add a unique constraint such that my new model looks like this: from django.db import models class Test(models.Model): name = models.CharField("Title", null=False, blank=False, max_length=300, unique=True) After this I need to do makemigrations and migrate. However in my DB I already have records with duplicate names. My question: I want to apply constraint only for the new records. Is there a way to do so? (allow old duplicates to remain in the DB but prevent new ones to be created). At the moment I am getting IntegrityError on my old records while migrate. -
Django migration didn't migrate authtoken and sessions
When running python manage.py migrate not all migrations were run, specifically django_celery_results, authtoken and sessions. This resulted in the application related migrations erroring out. However, if I first manually migrate those three, and then specifically migrate auth (not sure why I'd need to migrate that again) and then do python manage.py migrate it'll work. The installed apps on Django are like so: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_celery_results', 'celery.contrib.testing.tasks', 'api_app' ] I'm wondering why that's happening, I thought migrate will run all the migrations listed in "operations to perform". -
Get Timezone to take effect
I am going through the Django tutorial. I thought the TIME_ZONE in settings.py was of form 'UTC-5', but it isn't. I replaced it with 'America/Chicago' However, when I do: python manage.py shell from django.utils import timezone timezone.now() I get 'UTC' How do I get the timezone to take effect? -
data migration is triggering a query at import time
my last migration was a data migration that Trigger thumbnails update for profile app def trigger_thumbnails_update(apps, schema_editor): """ Trigger thumbnails update for profile app """ User = apps.get_model('profile', 'User') for user in User.objects.all(): if user.photo: make_image_thumbnail.delay() class Migration(migrations.Migration): dependencies = [ ('profile', '0008_auto_20190611_2120'), ] operations = [ migrations.RunPython(trigger_thumbnails_update), ] after that, I added a field called is_daleted, and run makemigrations : class Migration(migrations.Migration): dependencies = [ ('profile', '0009_trigger_thumbnails_update'), ] operations = [ migrations.AddField( model_name='user', name='is_deleted', field=models.BooleanField(default=False), ), ] that works fine, but when I run tests (pytest) I get that error : django.db.utils.ProgrammingError: column profile_user.is_deleted does not exist I think that it's caused by my data migration is triggering a query at import time, so it runs before the migration itself. commenting the triggering code solve the problem temporary, I need a real solution, please -
Get several unique fields values in django
I have a model: class MyModel(models.Model): a = models.CharField(...) b = models.CharField(...) And some substring "substring" To get all unique values from fields a and b which contains those substring I can do that: a_values = MyModel.objects.filter(a__icontains=substring).values_list("a", flat=True).distinct() b_values = MyModel.objects.filter(b__icontains=substring).values_list("b", flat=True).distinct() unique_values = list(set([*a_values, *b_values])) Is it possible to rewrite it with one database request? -
Verify a Django model field inside a Django model
I have a Django model called Attendance that has the clock in and clock in times of an employee along with the status of that entry, to see whether it's authorized or not. I then, am making another model called Payroll. I want this to check inside the Attendance entries to see all the Authorized entries and then do some action on them. How do I check all the status fields for all the entries in Attendance? To better elaborate my question, this is how I've setup my Attendance model: class CWorkAttendance(models.Model): AUTO_ATT = "AU" MANUAL_ATT = "MA" WORK_ENTRY_TYPES = ( (AUTO_ATT, "Auto-Attendance"), (MANUAL_ATT, "Manual-Attendance"), ) AUTHORIZED = "AU" UNAUTHORIZED = "UA" WORK_ENTRY_STATUSES = ( (AUTHORIZED, "Athorized"), (UNAUTHORIZED, "Un-Authorized"), ) work_employee = models.ForeignKey('CEmployees', on_delete=models.CASCADE,) work_start_time = models.DateTimeField() work_end_time = models.DateTimeField(null=True) work_duration = models.IntegerField(null=True) work_entry_type = models.CharField(max_length=2,choices=WORK_ENTRY_TYPES) work_entry_status = models.CharField(max_length=2, choices=WORK_ENTRY_STATUSES, default=WORK_ENTRY_STATUSES[1][0]) If you look closely at the work_entry_status, it's a choice CharField that will contain the status of the entry (UNAUTHORIZED by default). I want to create a Payroll model that will check for all the rows in the CWorkAttendance model and check their work_entry_status fields to see if they are Authorized, which is what I want to learn how … -
How to integrate a python script to run when starting a Django project
I'm working on a Platform that uses Django and DjangorestFreamwork, so this platform is used to monitor the state of some sensors which sends data to the computer, so now i have the data in the computer i want to create a python file to read the data from the computer and store it in MySQL database that Django will read and show to the user I have two questions : - Can i make django read from the file save the data in the database and show it in the user interface ? if not How could i make a script to run in the background when i start the project ? -
Websocket gives error 500 once deployed but works on dev
I'm trying to deploy a django app using django-channels. When I run the server in a dev environment, it works perfectly. But when deployed, the websocket crash with an error 500. I use django 2.2.2, channels 2.2.0 and asgiref 3.1.4, on a linux debian stretch 9.9 VPS, with python 3.6 (compiled myself because not available on stretch) and nginx engine. I followed for deployment tutorials on https://djangodeployment.readthedocs.io/en/latest/01-getting-started.html and for the channels i tried to adapt the page https://channels.readthedocs.io/en/latest/deploying.html but mostly https://avilpage.com/2018/05/deploying-scaling-django-channels.html I'm quite noob to redis and all these things, at first I had redis working on port 6379, but it was with the main user of the system I used to do some tests in a dev environment, not the user for the django app. So I did another command to run docker on port 6479 for the django app user, which seemed to work. Then I had 404 error but it was because of nginx not configured properly for websocket. Now, I have the 500 error. here is the traceback of django when I try to open the websocket: [2019-08-19 12:54:46,857] ERROR: Exception inside application: Connection has been closed by server File "/opt/knightools/venv/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return … -
What's the model query of a raw SQL
I working on some kind of pricelist, with prices changing over time. I'm facing problems with retrieval of latest price for each product. My models are as follows: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Product(models.Model): id = models.PositiveIntegerField(primary_key=True, validators=[MinValueValidator(10000), MaxValueValidator(99999)]) name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return f'[{self.id}] {self.name}' class ProductPart(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE, null=False) price = models.DecimalField(decimal_places=2, max_digits=7, null=False) date_created = models.DateTimeField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True) I have a raw SQL variant of this, but can't figure out how to turn it into a Django Query. The raw query is: select pp.id as product_id, pp.name as product_name, ppp.price as price from pricelist_Product as pp inner join pricelist_ProductPart as ppp on pp.id=ppp.product_id where (pp.id, ppp.id) in ( select pp.product_id, max(pp.id) from pricelist_ProductPart as pp group by pp.product_id ) Help me, please.