Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Perform action when a certain field changes in the django admin
I was wondering how to do something for case like this say I have a model like this class ModelA(models.Model): paid = models.BooleanField(default=False) amount = models.DecimalField() and you want to perform an action like add 1? to amount when the boolean field is checked. not the first save but subsequent save when changing paid field in the admin how would that be done? and signals be use for such? can one do a method like this and add it to signal? def test_stuff_change(instance, sender, *args, **kwargs): if paid == True: #what ever logic and statement goes in here can this be done on change fields? -
Django-Tenants: running script for all tenants
I am currently using Django and django-tenants to build my web app. I want to know if it is possible to open a shell that runs a script on every tenant instead of just one tenant at a time? I have serialized data unique to each tenant, and if I update how my serializer works, I don't want to individually go into each tenant with tenant_command shell and then run the script to update that tenants serialized data. Am I able to run my script from one place and have it do what it needs to do to each tenant? Thank you -
what better to use Django or Flask [on hold]
I had a need to write my own web application for image processing, so that the user could upload, the image on the server was processed, and the result was downloaded. I have some Python code for processing. Through what framework is the easiest way to do this for a beginner, I found Flask and Django? Or is there something else? -
How to do a query set an get all objects and then filter this query set in django
I have a for loop and inside it i am doing each time a query to get client name from another table according to a specific id , it's taking so much time so is their any solution to make it with a less time? My django code : for type in query: ClientName = Clients.values('p_fname').filter(p_id=type.e_c.p_id) dict1 = {'ID': type.e_id, 'DrName': DrName.get('p_fname') , 'Client': ClientName.get('p_fname'), 'Date': type.e_date, 'StartTime': type.e_starttime, 'EndTime': ''} result.append(dict1) -
Django : downloading a file (pdf version or odt version) through radio buttons
I trying to propose to the users of my site to download a document in either pdf or odt version through radio buttons. How can I get and use the value of the radio button chosen by the user to serve the appropriate file. So far, I can only serve one at a time. My current work: models.py class File(models.Model): name = models.CharField(max_length=200) pdf_version = models.FileField() odt_version = models.FileField() def __str__(self): '''String name represents class File''' return self.name urls.py path('files_page/', views.files_page, name='files_page'), path('download_file/<int:file_id>/', views.download_file, name='download_file'), views.py def files_page(request): files = File.objects.all() context = {'files':files} return render (request, 'walk/files_page.html', context) def download_file(request, file_id): #No post request; do nothing if request.method != 'POST': pass else: #fetch the file to download #file = File.objects.get(id=file_id) response = FileResponse(open('/home/me/Desktop/super/media_cdn/tog.pdf', 'rb')) response['Content-Disposition'] = 'attachment; filename="tog.pdf"' return response template {%block content%} {%for file in files %} <p>{{file.name}}</p> <p>{{file.pdf_version}}</p> <p>{{file.csv_version}}</p> <form action="{%url 'walk:download_file' file.id%}" method="POST"> {%csrf_token%} <input type="radio" name="format" value="pdf" checked> pdf <input type="radio" name="format" value="csv"> csv <button name="submit">download</button> </form> {%endfor%} {%endblock content%} Thanks for your time. -
How to query Django LogEntry by content_type name?
I would like to query Django admin's LogEntry records by content_type.name. I have tried this: from django.contrib.admin.models import LogEntry logs = LogEntry.objects.filter(content_type__name='foo') But this results in the error trace of: Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/query.py", line 781, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/query.py", line 799, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1260, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1286, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/opt/sfo/sfo_rcecala/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1211, in build_filter raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) FieldError: Related Field got invalid lookup: name I can do this ... logs = LogEntry.objects.filter(content_type=102) logs.all()[0].content_type.name u'foo' ... so how can I get all the content_type objects that have the name foo? -
Django - email verification without default user class
I have created my custom user model with more fields (ssn,birthdate,country,phone) that are not provided by default user model. How can I send an email verification link to users after signup before making their account active. Thanks -
How can I do a Django Query on a JSONField containing a date?
my hope was I could do something like this: Q(data__result_started__gt = dateutil.parser.parse("5/22/18")) or Q(data__result_started__gt = "2018-5-22") in the first case i get a datetime is not JSON serializable error and in the second case i get 0 results returned. Is there a way to do this? thanks -
Django |add: on PK URL tag
I am trying to get the next PK value using |add:"1" in the HTML template. My question is how do I get it to work? Example if PK is 1 it should be 2 after clicking the link. See code. template <h3> <a href="{% url 'step' task_pk=step.task.pk step_pk=step_id|add:"1" %}">Next Step</a> </h3> models class Task(models.Model): CATEGORIES = ( ('tr', 'Traffic'), ('cr', 'Conversion Rate'), ('br', 'Bounce Rate'), ('ma', 'Marketing'), ('sc', 'Sales Channels'), ('cur', 'Customer Relations'), ) title = models.CharField(max_length=100) description = models.CharField(max_length=300) category = models.CharField(max_length=100, choices=CATEGORIES) created_at = models.DateTimeField(auto_now_add=True) order = models.IntegerField(default=0) id = models.AutoField(primary_key=True) def __str__(self): return self.title class Step(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) order = models.PositiveIntegerField(default=1) title = models.CharField(max_length=100) is_complete = models.BooleanField(default=False) description = models.TextField() id = models.AutoField(primary_key=True) class Meta: ordering = ['order'] unique_together = ("task", "order") def __str__(self): return self.title views def task_step(request, task_pk, step_pk): step = get_object_or_404(Step, task_id=task_pk, pk=step_pk) return render(request, 'totd/task_step.html', {'step': step}) urls urlpatterns = [ re_path(r'(?P<task_pk>\d+)/(?P<step_pk>\d+)/$', views.task_step, name='step'), ] -
app displaying server error 500 on heroku. How do you solve it
I have an application am working on. The repository on Github works fine on a local machine when clone .Endpoints work perfect. WHen I deploy the sam eapp to heroku, the endpoint for reset_password returns500 server error` while the other endpoints work as expected. How can I go about fixing this problem -
Django create a genericForeignKey with SmallUUIDField() id
this is my model that uses Generic Foreign Key im using SmallUUIDField for pos_id and object_id. class POSRecord(models.Model): id = SmallUUIDField(default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID') # FK to a POS integration (e.g., SquareCredentials) pos_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_integration', on_delete=models.CASCADE) pos_id = SmallUUIDField() pos = GenericForeignKey('pos_content_type', 'pos_id') # FK to anything in our system (e.g., Item, ModifierList, Location) object_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_object', on_delete=models.CASCADE) object_id = SmallUUIDField() object = GenericForeignKey('object_content_type', 'object_id') # Raw JSON data from the POS api data = JSONField() on the POSRecord.objects.get_or_create( method im passing the an id that im getting from squareup's api, to the key object_id and im getting E ValueError: bytes is not a 16-char string. i tried to change the the POSRecord model pos_id value to models.PositiveIntegerField() but then got this error. ValueError: invalid literal for int() with base 10: 4JSZ539TSJ5GEIMW43FFNQXF def sync_item(self, square_item): item_content_type = ContentType.objects.get_for_model(Item) square_credential_content_type = ContentType.objects.get_for_model(SquareCredential) print(square_item.id) print(self.credentials.token) # Fetch our opy of the POS data try: record = POSRecord.objects.get_or_create( pos_content_type=square_credential_content_type, pos_id=self.credentials.token, object_content_type=item_content_type, object_id=square_item.id, ) except POSRecord.DoesNotExist: record = POSRecord(pos=self.credentials) # Update our record with the fresh data record.data = square_item print(record) print(record.objects) # Get or instantiate our own version of the object item = record.object if item is None: item = … -
OperationalError at /admin/login/ (1698, "Access denied for user 'root'@'localhost'")
Yes, this is a common question in Stack Overflow but my problem is kinda different! I have a server on Digital Ocean. Os: Ubuntu 18.04 I was trying to host my django project on the apache server with mysql. I have completed the first part but the problem is integrating the mysql. I have installed the mysql and mysqlclient. There is a user root with password in my mysql. I have created a database and gave the following permission. GRANT ALL PRIVILEGES ON urp_test.* TO 'root'@'localhost' identified by 'password_for_root'; The I configured my settings.py file. Here is the db portion: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'urp_test', 'USER': 'root', 'PASSWORD': 'password_for_the_db', 'HOST': 'localhost', 'PORT': '3306', } } Then I did a python manage.py makemigrations, python manage.py migrate, python manage.py createsuperuser. All of them were executed successfully. So when I go login from the admin module, I see the error: OperationalError at /admin/login/ (1698, "Access denied for user 'root'@'localhost'") So, it's definitely a permission error still, isn't it? How can I resolve this error? And also I planned to develop a sign-up module for my normal user. If they sign up, will this permission be accessible to them? Do … -
ForeignKey instance error Exception at Django
I get this error when I register the Personel form; "Exception Value: Cannot assign "5": "db_PERSONEL.db_departman" must be a "db_DEPARTMAN" instance. ". Thanks. departman_app.model.py from django.db import models class db_DEPARTMAN(models.Model): id = models.AutoField(primary_key=True, editable=False) db_departmanAdi = models.CharField(max_length = 50) def __unicode__(self): return u'%s' % (self.db_departmanAdi) personel_app.models.py from django.db import models from departman.models import db_DEPARTMAN class db_PERSONEL(models.Model): id = models.AutoField(primary_key=True, editable=False) db_personelAdi = models.CharField(max_length = 50) db_departmanAdi = models.ForeignKey(db_DEPARTMAN, on_delete=models.DO_NOTHING, related_name="tags") def __unicode__(self): return u'%s' % (self.db_departmanAdi) personel_app.personelform.py from django import forms from personel.models import db_PERSONEL class personelForm(forms.ModelForm): class Meta: model=db_PERSONEL #fields="__all__" fields = [ 'db_personelAdi', 'db_departmanAdi', ] form = personelForm() form.base_fields['db_personelAdi'] = forms.CharField(label='Personel Adı:', max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) form.base_fields['db_departmanAdi'] = forms.IntegerField(label='Deaprtman Adı:', widget=forms.TextInput(attrs={'class': 'form-control'})) -
Why does my python script to populate a Django table with dummy data from another table result in error?
So the title states my objective. Here's the code I wrote to achieve it: #for each cycle in instructional cycles: for cycle in Instructional_Cycle.objects.all(): #for each standard in the currently selected cycle: for standard in cycle.standards.all(): #generate random percentage of correct grade-level students to pass that standard, say between 20 and 90% percent_pass = randint(20,90) #calculate number of total students for that grade-level that percentage represents (percentage times total number of students in that grade) total_students_passing = (percent_pass/100) * Student.objects.filter(grade_level = standard.grade_level).count() already_selected = [] #while length of list of already selected students < total needed while len(already_selected) < total_students_passing: #select a random student out of that grade count = Student.objects.filter(grade_level=standard.grade_level).count() random_student = Student.objects.all()[randint(0, count - 1)] #single random object #if that student isn't in list of already selected students if not random_student.id in already_selected: #create a passing progress report with the end date of that instructional cycle Progress_Report.objects.create(date=cycle.date_finished, student=random_student, standard_mastered=standard, mastery_status=True) #add that student to list of already selected students already_selected.append(random_student.id) This ends with the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: student_progress_progress_report.standard_mastered_id The progress_report table that I'm trying to fill is empty. I can add records to it using the admin interface. So I'm not sure where to look … -
Django admin filter a foreign field based on another field value
In my django app, in admin panel, when i go to add/edit form for my table i have two ForeignKey fields (combo), main_id and Test_id. I would to filter the result contained in test_id field based on previews choise in main_id field selection. In my admin.py i try: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "test_id": kwargs["queryset"] = temp_case.objects.filter(main_id = <here i need the value selected on main_id combo>) return super().formfield_for_foreignkey(db_field, request, **kwargs) but i don't know what i have to write in ''. i try main_id__id, or main_id.id but was not correct. How can i retreive the value of selection in main_id combo and pass it to my method? Thanks in advance Luke -
How to create dynamic method for save in models and save_model in ModelAdmin to get and set current user.
how I save the current user in Models without create one method per model? There's a dynamic way to implement this for all scope? Some like this: class BaseTable(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='%(class)s_createdby', editable=False) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT ,related_name='%(class)s_modifiedby', editable=False) class Meta: abstract = True And I extend the new model to BaseTable class Clients(BaseTable): first_name = models.CharField(max_length=50,verbose_name='Nome') last_name = models.CharField(max_length=50, verbose_name='Sobrenome') My question: everytime I'll need overwrite the save() method in all models: Clients, Invoices, Checkout to set the current user in ModelAdmin or there other way to simplify this proccess? I'm using: admin.py @admin.register(Clients) class ClientsAdmin(admin.ModelAdmin): model = Clients def save_model(self, request, obj, form, change): obj.created_by = request.user obj.modified_by = request.user super().save_model(request, obj, form, change) It's works. But If a had 20 models? I need overwrite one by one all save_model method? Nothing more dynamic? -
How to validate that a string is a valid date in Python
I have a model in Django that has two DateFields, but sometimes they receive wrong dates from the front-end, like '20196-10-23'. Even when it might actually be a valid date (crazy, but legit), python doesn't allow to compare both dates due to this error: TypeError: '>=' not supported between instances of 'datetime.date' and 'str', so I want to use clean() method to verify that both dates are valid ones, but I always get dates wrong, even when they are correct. This is the code for clean() method: def clean(self, *args, **kwargs): try: Reservation.objects.get(booking=self.booking) except: pass else: raise CustomValidation(_('Booking already exists.'), 'booking', status_code=status.HTTP_400_BAD_REQUEST) print("{}/{}".format(self.arrival_date, self.departure_date)) try: datetime.strptime(self.arrival_date, "%Y-%m-%d") except: raise CustomValidation(_('Arrival date must be a valid date.'), 'arrival_date', status_code=status.HTTP_400_BAD_REQUEST) if self.arrival_date >= self.departure_date: raise CustomValidation(_('Departure date must be later than Arrival date.'), 'departure_date', status_code=status.HTTP_400_BAD_REQUEST) elif self.arrival_date <= timezone.datetime.now().date(): if self.id == None: raise CustomValidation(_('Arrival date must be later than today.'), 'arrival_date', status_code=status.HTTP_400_BAD_REQUEST) if self.status == 'CONFIRMED' and self.confirmation is None: raise CustomValidation(_('Must provide a confirmation number.'), 'confirmation', status_code=status.HTTP_400_BAD_REQUEST) I always get an exception, even when the date is correct. -
Django-filter/Django-autocomplete-light - Doesn't show initial Select2Multiple values
I use django-filter for filtering a Article queryset. Article has a field locations: locations = models.ManyToManyField('locations.Location', related_name='articles') I filter Articles by field locations and as a widget, I use django-autocomplete-light widget Select2Multiple. class ArticleFilter(django_filters.FilterSet): from locations.models import Location ... locations = django_filters.ModelMultipleChoiceFilter(method='locations_filter',queryset=Location.objects.all(),label='Lokality') ... class Meta: model = Article fields = ['locations','title','price_lte','price_gte','price_currency' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # HERE I SPECIFY THE DAL WIDGET self.form.fields['locations'].widget = autocomplete.Select2Multiple(url="locations:locations_autocomplete") The filtering works good, autocomplete too: When I click on submit, it shows filtered results correctly, URL querystring contains all filtered attributes including for exmaple locations=45 but it doesn't show the location with id=45 as an initial value for the locations field. The weird thing is that if I remove the widget, I can see that originally, there is initial value: Just Select2 doesn't show it and the value of locations is undefinfed. I use this same approach on raw django.forms and it works correctly. Initials too. Do you know where can be the problem? -
Django : Creating an on-click trigger
My Django website involves displaying number of times a song on the website has been played, if someone could help me out in adding the right trigger that increments a counter each time a click to that webpage hosting the song is encountered, it would be much appreciated. Code written : In models.py class SongPlays(models.Model): songid = models.ForeignKey(Songs, on_delete=models.CASCADE) songhits = models.IntegerField( ? ) In views.py, for another table 'Songs' def detail(request, songid): try: song = Songs.objects.get(pk=songid) except Songs.DoesNotExist: raise Http404("Song does not exist") return render(request, 'music/detail.html', {'song': song} ) -
Generic django admin per client
In my django project, i would like to use Django Admin for multiple organization. So in django urls system, i try to use a system like that : urlpatterns = [ path('<organization>/admin', admin.site.urls) ] With that syntax,on a simple example (default startproject+setup), i got an 'NoReverseMatch' : Reverse for 'logout' with no arguments not found. 1 pattern(s) tried: ['(?P<client>[^/]+)\\/admin\\/logout\\/$'] At the end i try to implement a system like that: Basic auth user (maybe change backend for email) Organization: Organization_User (inherit from basic auth or relationship) Organization_Area (manyTomany with Organization_User) and for urls i don't know if syntax bellow works: www.example.com/admin => admin SuperUser only www.example.com/organization1/admin => Admin for Organization 1 www.example.com/organization2/admin => Admin for Organization 2 I'm asking myself, is it possible to do that only with Django Admin system ? For example, use one Admin and try URL filtering or use AdminSite inheritence Best Regards, -
What is the solution to HTTP_HOST HEADER , RFC 1043/1035 when header is empty?
so usually I see that if you get an HTT_HOST HEADER error you would add the IP to the allowed hosts. In my particular situation it is not providing that ip. [ERROR 2018-10-17 18:36:20,893] base.py [:204] get_response: Invalid HTTP_HOST header: ''. The domain name provided is not valid according to RFC 1034/1035. Traceback (most recent call last): File "/opt/django/www/local/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) Any idea on what I should do? -
Limiting the number of selected answers in the voting / polling application
It seems to me that I am doing a simple voting / polling application(polls like in django tutorial), but I can not figure out how to limit the number of answers a user can choose. Let's say that there are 10 answers to choose and the user can choose max 2. How to achieve something like that? -
Delete checked items from bootstrap html table and PostgreSQL database
I have a html table (bootstrap) with check boxes and a delete button and am trying to delete the selected records from the table as well as the database. Following is the code that have, not really sure what am missing. <h2>{% block title %}Customers{% endblock %}</h2> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.8.1/bootstrap-table.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> <table id="eventsTable" data-toggle="table" data-height="300" data-pagination="true" data-search="true" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-toolbar="#toolbar"> <thead> <tr> <th data-field="state" data-checkbox="true"></th> <th data-field="Name" data-sortable="true">Name</th> <th data-field="Description">Description</th> <th data-field="Comments">Comments</th> </tr> </thead> <tbody> {% for customer in customers %} <tr id="tr-id-2" class="tr-class-2"> <td>{{ store.name }}</td> <td>{{ store.description }}</td> <td>{{ store.comments }}</td> </tr> {% endfor %} </tbody> <button id="deleteRecord">Delete</button> Here I'm gathering the checked checkboxes using check.bs.table <script> var checkedRows = []; $('#eventsTable').on('check.bs.table', function (e, row) { checkedRows.push({id: row.id}); console.log(checkedRows); }); $('#eventsTable').on('uncheck.bs.table', function (e, row) { $.each(checkedRows, function(index, value) { if (value.id === row.id) { checkedRows.splice(index,1); } }); console.log(checkedRows); }); I'm able to print the list of row ID's on the console, however the below code is where I might have done something incorrect ? $(document).ready(function(){ $('#deleteRecord').click(function(){ $("#eventsTable input:checkedRows").each(function(){ $(this).closest('tr').remove(); return false; }) }); }); </script> -
Embed Bokeh server with multiple roots in Django
I have a bokeh app with multiple roots. Inside the bokeh template, I use {{embed(roots.plot1)}} {{embed(roots.plot2)}} # etc to load the plots. This works fine. Now, I'd like to get the plots to load inside a web page I'll be serving from a Django app. Since my plots are generated using Holoviews, the Bokeh server is essential. The bokeh documentation https://github.com/bokeh/bokeh/tree/master/examples has examples of how to autoload all plots from a Bokeh server, and it also has examples of how to embed multiple static plots using components(), but none of these seem to cover this use case. Here's what I've tried: # The following function is a function-based Django view def django_view(request): bokeh_url = 'http://localhost:5006/experiment' roots = {root.name: root for root in session.document.roots} with pull_session(url=bokeh_url) as session: # I was hoping that these will generate separate autoload scripts for each model. # Unfortunately they each embed all the models. script1 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot1']) script2 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot2']) return render(request, "template.html", {"script1": script1, "script2: script2}) Excerpt from template.html: {{ script1 | safe }} {{ script2 | safe }} The result is that each script tag loads all the plots on top of eachother. How can I get each plot … -
Django error using Django Dynamic Scraper; doesn't declare explicit app label
I am using the django dynamic scraper library I followed the steps in the docs but when I come to makemigrations I get this error File "/home/plank223/PycharmProjects/FYP/OpenNews/models.py", line 6, in from dynamic_scraper.models import Scraper, SchedulerRuntime File "/home/plank223/PycharmProjects/FYP/venv/lib/python3.7/site-packages/dynamic_scraper/models.py", line 13, in class ScrapedObjClass(models.Model): File "/home/plank223/PycharmProjects/FYP/venv/lib/python3.7/site-packages/django/db/models/base.py", line 95, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class dynamic_scraper.models.ScrapedObjClass doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I can include the code from my other files if you need it. I just need a fix for this error if possible. Thanks in advance.