Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validate a django form with multiple fields
I have a django form with multiple fields and I need to validate the form..reading this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms it works with one field but not work in my case. My forms.py: class mopa(forms.Form): idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 ) causale = forms.CharField(label="Causale Pagamento *", required=True) imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True) quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True) my views.py: def paga(request): # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = mopa(request.POST) print('form: ', form.data) #return a dictionary # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required idcarr = form.cleaned_data['idcarrellosorgente'] caus = form.cleaned_data['causale'] imp_u = form.cleaned_data['imp_unitario'] qta = form.cleaned_data['quantita_item'] dictmopa={} dictmopa['id_carr']=idcarr dictmopa['ente']=cod_ente dictmopa.save() # redirect to a new URL: return HttpResponseRedirect(reverse('viewsdati/') ) # If this is a GET (or any other method) create the default form. else: form = mopa() return render(request, 'paga.html', {'form': form}) and my template: <div class> <form action="" method="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit" /> </form> </div> So, how can I … -
Add and remove rows from a formset within a form
I have a Django formset within a form that is build using django-crispy-forms and bootstrap 4.0.0-alpha.6. It looks like so: {% block content %} <div> <h1 class="text-center">Create New Activity</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} {{ activitykeycharacteristics_formset|crispy }} <hr> <button class="primaryAction btn btn-primary pull-right ml-1" type="submit">{% trans "Submit" %}</button> <a class="btn btn-secondary pull-right" href="{{ request.META.HTTP_REFERER }}" role="button">{% trans "Cancel" %}</a> </form> </div> <div class="col"></div> </div> </div> {% endblock content %} What I have been trying to do is include add and delete buttons so that I can add or delete forms from the formset. At the moment it renders with one form in the formset and so only an add button should be seen, but once there is more than one a delete button should also be seen. I'm pretty sure the best way to do this is to use jQuery to add and remove the forms but I haven't been able to get this to work properly. I thought that I had the add button working using Dave's answer in this SO question. But I couldn't get it to correctly update the indices of the inputs. I couldn't get … -
Django round to 2 decimal places if there are decimals else round to no decimal places
please can you point me in the right direction. Given the number 1.555, I want the result 1.56 Given 1.500, I want 1.5 Given 1,000 I want 1 Are there any existing filters that can do this? I know that I can write my own, I'll do that if there isn't a built solution already. -
Update three-level nested django model using serializer
I am trying to update one of my models (which is a nested model - three level actually as you can see below) and I am getting the following error: AssertionError: The .update() method does not support writable nestedfields by default. Write an explicit .update() method for serializer SystemSettingsSerializer, or set read_only=True on nested serializer fields. All day I have been reading about nested models and nested serializers, trying to add update and create methods setting fields as read_only=True but no matter what I did, it just didn't work :( :( These are my models: class SystemSettings(models.Model): # ... some fields class Components(models.Model): settings = models.ForeignKey(SystemSettings, related_name="Components") class SysComponent(models.Model): class Meta: abstarct = True index = models.PositiveIntegerField(primery_key=True) is_active = models.BooleanField(default=False) component = NotImplemented class Foo(SysComponent): component = models.ForeignKey(Components, related_name="Foo") class Bar(SysComponent): component = models.ForeignKey(Components, related_name="Bar") task_id = models.PositiveIntegerField(default=0) and serializers: class SystemSettingsSerializer(ModelSerializer): Components = ComponentsSerializer(many=True) class Meta: model = SystemSettings fields = [# some fields, Components] class ComponentsSerializer(ModelSerializer): Foo = FooSerializer(many=True) Bar = BarSerializer(many=True) class Meta: model = Components fields = ['Foo', 'Bar'] class FooSerializer(ModelSerializer): class Meta: model = Foo class BarSerializer(ModelSerializer): class Meta: model = Bar My logic is the following: I am fetching the SystemSettings via GET and … -
Wagtail document links downloading instead of displaying as a page
It seems that the default configuration for Wagtail CMS is to have links to documents trigger an automatic download of the document instead of displaying the document in the browser. Is there a simple way to change this configuration? -
Optimizing a Django `.exists()` query
I have a .exists() query in an app I am writing. I want to optimize it. The current ORM expression yields SQL that looks like this: SELECT DISTINCT (1) AS "a", "the_model"."id", ... snip every single column on the_model FROM "the_model" WHERE ( ...snip criteria... LIMIT 1 The explain plan looks like this: Limit (cost=176.60..176.63 rows=1 width=223) -> Unique (cost=176.60..177.40 rows=29 width=223) -> Sort (cost=176.60..176.67 rows=29 width=223) Sort Key: id, ...SNIP... -> Index Scan using ...SNIP... on ...SNIP... (cost=0.43..175.89 rows=29 width=223) Index Cond: (user_id = 6) Filter: ...SNIP... If I manually modify the above SQL and remove the individual table columns so it looks like this: SELECT DISTINCT (1) AS "a", FROM "the_model" WHERE ( ...snip criteria... LIMIT 1 the explain plan shows a couple fewer steps, which is great. Limit (cost=0.43..175.89 rows=1 width=4) -> Unique (cost=0.43..175.89 rows=1 width=4) -> Index Scan using ...SNIP... on ...SNIP... (cost=0.43..175.89 rows=29 width=4) Index Cond: (user_id = 6) Filter: ...SNIP... I can go further by removing the DISTINCT keyword from the query, thus yielding an even shallower execution plan, although the cost saving here is minor: Limit (cost=0.43..6.48 rows=1 width=4) -> Index Scan using ..SNIP... on ..SNIP... (cost=0.43..175.89 rows=29 width=4) Index Cond: (user_id = … -
How to store datetime and input timezone offset in Django
I have a Django model with a timestamp field and need to store the timestamp including the timezone offset. The model data is stored in a PostgreSQL database and the offset is lost when retrieving it from the database (because PostgreSQL stores all timestamps in UTC). To achieve this I have added a field to the model that stores the offset (in minutes) and a property that combines the timestamp and offset when reading / extracts the offset from the timestamp when writing: from django.db import models class FooModel(models.Model): client_timestamp = models.DateTimeField() client_utc_offset = models.IntegerField(default=0) @property def client_timestamp_with_offset(self): return timezone.localtime(self.client_timestamp, timezone.get_fixed_timezone(self.client_utc_offset)) @client_timestamp_with_offset.setter def client_timestamp_with_offset(self, value): self.client_timestamp = value self.client_utc_offset = value.tzinfo.utcoffset(value).total_seconds() // 60 This works, but is not ideal. For instance, it's not possible to use this property when creating an instance directly i.e.: FooModel.objects.create(client_timestamp_with_offset=...) doesnt work. It's also not possible to use this property in forms/Django's admin. So I'm looking for a better solution. I've been looking into custom fields/descriptors, but I'm not sure how to use those tools to do it properly. -
JSONField serializes as json for POST, but string for GET
There is likely a very simple problem with my code, but I've been slamming my head against this problem for a couple days and can't make any headway. Important Packages: Django==1.11.3 django-cors-headers==2.1.0 djangorestframework==3.7.0 drf-nested-routers==0.90.0 psycopg2==2.7.3 pycparser==2.18 Here is what is happening: I create a model via an AJAX call My server correctly serializes the brainstorm_data field as a json object. Now I navigate my user to the next page and fetch the current model For some reason, brainstorm_data is now be returned as a string. Anytime I call a GET request on this resource I always get a string representation of the JSON object. Here is the code associated: models.py from django.contrib.postgres.fields import JSONField class Adventure(TimeStampedModel, models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) world = models.ForeignKey(World) theme = models.ForeignKey(Theme, default=1) brainstorm_data = JSONField() image_src = models.CharField(max_length=400, null=True, blank=True) sentence_summary = models.TextField(null=True, blank=True) paragraph_summary = models.TextField(null=True, blank=True) page_summary = models.TextField(null=True, blank=True) outline_complete = models.BooleanField(default=False) brainstorm_complete = models.BooleanField(default=False) private = models.BooleanField(default=False) def __str__(self): return self.name views.py class MyAdventuresViewSet(viewsets.ModelViewSet): queryset = Adventure.objects.all() serializer_class = AdventureSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return Adventure.objects.filter(user=self.request.user) def create(self, request, *args, **kwargs): user = self.request.user world = World.objects.filter(user=user).first() if not world: world = World.objects.create(name='My World', user=user, description="This is … -
In Django, how do I save a file that has been uploaded in memory as an email attachment?
I am building an email gateway for our clients and need to be able to attach the files they upload to the email. I am using EmailMultiAlternatives to send the email and a FileField for the upload. The problem happens when I try to connect the two. I have the following logic in my view. if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): ... email = EmailMultiAlternatives(...) email.attach(request.FILES['image']) else: form = MyForm() This results in "No exception message supplied" and the following values in debug: content: None filename: <InMemoryUploadedFile: ImageFile.png (image/png)> mimetype: None So it looks like for some reason, there is no file content. Not sure what's going on here. Examples in the docs save the file to a model, but there is no model to save the file to here. Ideally, I would just like to pass the file content directly to the attach method and send it on. Any ideas on how to make this work? -
values show up correctly in view, but not template
I have the following view, which shows up correctly in the print report details: def profile(request): owner = User.objects.get (formattedusername='request.user.formattedusername') reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername).values('report_name') print(reportdetail) args = {'user':owner, 'applicationaccess':reportdetail} return render(request, 'accounts/profile.html', args) However, it's not getting passed to my template correctly. I'm new to Django so I'm going to assume there is something wrong the part of my template passing the report name. <h2>Current Access Application List</h2> <ul> {{reportdetail.report_name}} <li>Application Name: {% for app in reportdetail %} <input type="checkbox" name="report_name" value="{{ app.report_name }}" /> {{ reportdetail.report_name }}<br /> {% endfor %} </li> </ul> -
Django delete records missing after syncing
I have a Django table that syncs data with a external API. When data is added / updated there is no problem with the sync but how can I detect data has been deleted and remove it from the Django table. For the record during each sync I am dealing with a lot of data. -
Unable to display user input in django
I am new to Django and trying to display user input text. I tried multiple things but nothing has worked so far. Advice/help needed! Here are my files: models.py from django.db import models class Post(models.Model): message = models.TextField(max_length=4000) def __unicode__(self): return self.title views.py from .models import Post from django.core.exceptions import * def index(request): return render('index.html') def result(request): p = request.POST['message'] return render_to_response('result.html', {'message': p}, context_instance=RequestContext(request)) index.html <!DOCTYPE html> <head> <title>Index page</title> </head> <body> <div id="header">Welcome to index page</div> <div id="content"> <p>Enter your name</p> <form action="/polls/results.html/" method="post" accept-charset="utf-8">{% csrf_token %} <input type="text" name="message"> <input type="submit" value="Send!"> </form> </div> </body> results.html <!DOCTYPE html> <head> <title>Result page</title> </head> <body> <div id="header">Here is the result</div> <div id="content"> <p>Your name is: {{ message }}</p> </div> </body> url.py from django.conf.urls import include, url from django.conf.urls.static import static from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.result, name='results'), ] -
How to setup a remote database only server for my django application
I am planning to separate my SQL database from my Django application server by implementing a remote database server. I also want to create a backup server of the primary database server. I would like to sync my backup database with the primary database when some data is changed in the primary database. So here are my questions. How can I connect my remote database server to my Django application server and also how can I sync my primary and backup database servers.? I'm thinking if there is any way to interconnect Django application server, database server, backup database server via private IP's and block any requests to the database servers via Public IP to avoid potential threats. I tried to connect my remote database by changing database HOST to my private IP and PORT to '3306' in my Django settings file and I'm stuck with django.db.utils.OperationalError: Can't connect to MySQL server I am using amazon-ec2 ubuntu 16.04 for all my servers -
Django, using the same view depending on if its a GET or an AJAX POST method
So I am using the same view in Django to do two things, depending on if the request is a GET or a POST method. The GET method is simply to render the page when the user requests it, and the POST is when I use ajax to send information from the frontend, to the view so that i can process it and save it in the database. Here is the Javascript/Ajax: var url = window.location.pathname; $.ajax({ url: url, data: { 'vals': vals }, dataType: 'json', success: function (data) { //On sunccess } }); The window.location.pathname contains the review_id in it and looks like: /reviews/*ID*/add_questions/ This is my Django View: def add_questions(request, review_id = None): #print('yes') if request.method == 'GET': try: review = ReviewBlock.objects.get(pk = review_id) args = {'review': review} return render(request, 'add_questions.html', args) except ObjectDoesNotExist: return HttpResponseNotFound('<h1>Page not found</h1>') elif request.method == 'POST': print(review_id) As you can see, I have a print statement to see if the ajax call is working, however, it never prints it in the console. -
Is there any way convert Django model queryset to json or json string in template?
I want to combine react (or vue) with django template, but I don't want to change the backend to restful api. So I wonder is there any way convert Django model queryset to json or json string in template, so that I can fetch the data from dom used in jsx or vue. -
Django build a DRF frontend page
I've made an API, and it works fine as API: view.py class TestView(viewsets.ModelViewSet): """ test rest""" queryset = models.Pippo.objects.all() serializer_class = PippoSerializer renderer_classes = (JSONRenderer,) template_name = 'pippo_app/test.html' url.py app_name = 'pippo_app' router = routers.DefaultRouter() router.register(r'ertest', views.PippoView) now I need an HMTL frontend to this API: class Manage(TemplateView): """test HTML frontend """ template_name = 'label_app/label_MAN_form.html' def get_context_data(self, **kwargs): context = super(Manage, self).get_context_data(**kwargs) context['prova'] = serializers.PippoSerializer() return context with this template.html {{prova}} I can see data form serializer. This is the correct approach? Are there better way without setup a frontend framework as angular, to manage the web frontend inside django? -
how to fetch youtube search videos from python Django using API's?
urls.py urlpatterns = [ url(r'^search/$',views.search, name='search'), url(r'^get_videos/$',views.get_videos, name='get_videos'), ] views.py def search(request): return render(request,'search.html') def get_videos(): if request.method == 'POST': Api_key = "my key here" #i have key search_list_url = "https://www.googleapis.com/youtube/v3/search" #what is the code to be added? return render(request,'display.html') Template <form action="/get_videos/" method="post">{% csrf_token %} <h1>Search for Top Youtube Videos Here</h1> <input type="text" id="search" placeholder="search here" required="required" /> <button type="submit">Search</button> </form> Basically i want to fetch youtube results for queried keyword through my template seach button only through Api (not through beautiful Soup), i know how to do it through scarpy, but need help regarding API , TIA. -
Selecting foreign keys in Django REST Framework's Browsable API
I have a simple ForeignKey relationship between two models: class Ticket(models.Model): description = models.CharField(max_length=1000) created_by = models.ForeignKey(User, related_name="created_ticket") class User(models.Model): username = models.CharField(max_length=64, unique=True, primary_key=True) email = models.CharField(max_length=255) I have a serialiser for each, with the user serialized within the ticket as a nested serialiser. What I would ideally like is in an update view of Tickets on the Browsable API, being able to choose from a dropdown list of extant users, and when entering a username and an e-mail, the application should check if users exist with those parameters, and if so, assign them to the ticket, and if not, raise a validation error (the validation part I got working, the rest... not so much). So far, I've tried to follow overriding the update/create methods, but when I enter a code, the application always tries to create a new object, then complains that an object with the same username (the pkey) already exists. I have tried getting some sense out of the documentation on the subject, but with not much luck. -
How to make a condition with string on Django 1.9 with tags?
I wanted to know how to make a condition work with a string from the Django 1.9 template. What happens is that when I do a condition with integers, it works perfectly, but when I do a condition with a string, it does not work anymore. I do not know if I have any errors in the syntax. {% if caso.status == "Anulado" %} <a class="btn btn-primary btmargeniz" href="/historico-casos/{{caso.acciones}}" title="Detalle del caso"><i class="fa fa-file-text fa-lg"></i></a> {% else %} <a class="btn btn-primary btmargeniz" href="/historico-casos/{{caso.acciones}}" title="Detalle del caso"><i class="fa fa-file-text fa-lg"></i></a> <a class="btn btn-success btmargeniz" data-caso="{{caso.acciones}}" onclick="carga_datos(this)" data-toggle="modal" data-target="#agregar_dealer_caso" title="Agregar Dealers al Caso"><i class="fa fa-thumb-tack fa-lg"></i></a> <a class="btn btn-warning btmargeniz" onclick="carga_datos(this)" title="Anular Caso" data-toggle="modal" data-target="#ModalAnularCaso" data-caso="{{caso.acciones}}"><i class="glyphicon glyphicon-flash fa-lg"></i></a> {% endif %} -
Celery tasks should be queued on worker getting lost
I am using django-celery 3.2 and celery 3.1.25. I have added below settings - CELERY_TASK_ACKS_LATE = True task_reject_on_worker_lost = True The application results in below error and fails to load if I use celery 4.x with django-celery 3.2 ImportError: No module named vine.five Steps to reproduce Trigger some tasks, and get their pids from logs. I kill a worker(pid) at random using kill command. Expected behavior The task should come back to the queue and picked up by same or other worker. Actual behavior The task is getting lost. -
Django:Getting List of values from query set
I have the following query country=employees.objects.filter(manager_id__emp_id=111).values('emp_loc').distinct() I get Output as <QuerySet [{'emp_loc': 'IND'}, {'emp_loc': 'MLA'}]> But I need list ['IND','MLA'] How Can I do it? -
Django stacktrace not informative
When I have a bug in Django, the stacktrace usually showed only Django's internal files, not my application files (usually view.py,..) that caused the bug. How can I make Django show me the full stacktrace? -
Slug in Django URL
I need your help. I working on my own project. And I need show single news from news list.I do next steps: in model: class Notice(models.Model): notice_header = models.CharField(max_length=150, verbose_name="Notice header", blank=False) notice_content = RichTextField(verbose_name="Notice content") notice_publish_date = models.DateField(verbose_name="Publish date", default=date.today) notice_slug = models.CharField(max_length=50, verbose_name="Notice URL", blank=False, default="#", unique=True) #SEO Data seo_page_title = models.CharField(max_length=150, verbose_name="SEO Page Title", blank=True) seo_page_description = models.TextField(verbose_name="SEO Page Description", blank=True) seo_page_keywords = models.TextField(verbose_name="SEO Keywords", blank=True) class Meta: verbose_name = "Notice" verbose_name_plural = "Notice list" def __str__(self): return self.notice_header def __unicode__(self): return self.notice_header In view: from django.shortcuts import render_to_response as rtp from models import * def notice_list(request): notice_articles = Notice.objects.order_by("-id") context = {"NOTICE_LIST": notice_articles} return rtp("notice.html", context) def single_notice(request, alias): current_news = Notice.objects.get(notice_slug=alias) context = {"NOTICE_SINGLE": current_news} return rtp("notice_single.html", context) in urls: url(r'notice/', notice_list), url(r'notice/(?P<alias>[^/]+)', single_notice), I see notice list on the page. But, when I try to select single notice for reading, page reloads and single_notice function doesn't work. notice_slug in database contains chars and numbers. What I doing wrong? best regards, Alex -
How to work with Django-Scheduler and Django Rest Framework?
I am making a booking system. I have a model known as products, so products are created. Now I have create the events and rules for the product as to when and how these product are available for bookings. Like a product might be available from Monday to Friday at 1pm and 4 pm. And I need all these working with Django Rest Framework. This is the Django Scheduler. https://github.com/llazzaro/django-scheduler I am looking for a view something like this. More info about product. Its a marketplace for Activity Providers and the Agents. So I need the functionality of creating a Activity and Supplier(Activity Providers) should be able to mark on which days he is not operation and on which days the price is different, the price will be different also on the basis of the Age of the Traveller. I have integrated the django-scheduler in Django, however it is installed as a separate -
django channels change time format of datetime field
I'm new to django channels and i'm stuck at how to change the format of the datetime field in this particular binding class. class InfoBinding(WebsocketBinding): model =Info stream = "stream" fields = ["time_stamp"] @classmethod def group_names(cls, *args, **kwargs): return ["binding.values"] def has_permission(self, user, action, pk): # print(self.time_stamp) return True