Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: cannot delete formset forms (Javascript on the frontend)
I have a basic invoice application and, in the single invoice update view, it is possible to add and remove elements of the invoice. Adding them works, unfortunately it does not in removing them. Even if in the frontend they get removed (via Javascript), the number of TOTAL_FORMS reduces accordingly and formset.cleaned_data shows only the rendered forms, they are still there saved in the model instance. Invoice model: class Invoice(models.Model): class Meta: verbose_name = "invoice" verbose_name_plural = "invoices" def __str__(self): return f"{str(self.date)}-{self.client.name}" def get_absolute_url(self): return reverse("invoice-list") @property def total(self): tot = 0 for el in self.elements.all(): tot += el.price return tot date = models.DateField(auto_now_add=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='clients') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="invoices") Element model: class Element(models.Model): class Meta: verbose_name = "element" verbose_name_plural = "elements" def __str__(self): return self.name name = models.CharField(max_length=200, blank=False, null=False) price = models.IntegerField() invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name="elements") invoice form and element formset: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = ['client'] def __init__(self, *args, **kwargs): userid = kwargs.pop('userid', None) super().__init__(*args, **kwargs) self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user_id=userid)) InlineElementFormsetUpdate = inlineformset_factory(Invoice, Element, fields=('name', 'price'), extra=0, can_delete=True) Invoice UpdateView: def update_formset(request, id): user = request.user invoice = Invoice.objects.get(id=id) elements = invoice.elements.all() invoice_form = InvoiceForm(instance=invoice) if request.method == 'POST': … -
What is parameterized query when django is involved?
I have seen this question being asked What is parameterized query?! but I fully do not understand how it secures web applications from A1 injection! from the OWASP top 10 guide!. I would appreciate it if someone explains in a lay term format and how string formatting further makes web applications secure from the same vulnerability. -
Dynamically change form labels in Django/oTree
I have a form label that I want to have variable content. I expose to my template a variable called outgroup which I want to be included in the formfield label. My current (incorrect) attempt looks like this: {% formfield sent_amount label="How much do you want to send to a "+{{outgroup}} %} But this obviously doesn't work. What is the correct way to get a variable into the label method? -
how to filter dynamically the availables values of a foreign key in a inline definitions according a value of its parent model
I have the below models.py: class Vendor(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Products_by_vendor(models.Model): vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,null=False,blank=False) item = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return str(self.vendor) + ' ' + self.item class Invoice(models.Model): number = models.IntegerField(null=False,blank=False) vendor = models.ForeignKey(Vendor,on_delete=models.PROTECT,null=False,blank=False) def __str__(self): return str(self.number) + ' ' + str(self.vendor) class Invoice_detail(models.Model): invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT,null=False,blank=False) product = models.ForeignKey(Products_by_vendor, on_delete=models.PROTECT, null=False, blank=False) def __str__(self): return self.invoice + ' ' + sel.product And i using the admin site in order to built the CRUD functions needed. So, I have the setup for manage the header model and its related child in a form using inlines feasibility (Invoice and Invoice_detail). The code to admin.py is: class Invoice_detailInline(admin.TabularInline): model = Invoice_detail extra = 0 class EnterInvoice(admin.ModelAdmin): pass inlines = [Invoice_detailInline] admin.site.register(Invoice,EnterInvoice) Then, after added a new line for Invoice_detail model, for the field Invoice_detail.product, I need to show only the products records that belong at vendor entered in the header form In others words, the expected behavior is to filter the content of "list box" widget in functions to the value entered in a field of the parent model. I read the documentation and between several options that i think can be used … -
Image as base64 in django
What is the reason that the image will not work where I have converted the image with this code Is there a way to operate the image def image_as_base64(image_file, format='png'): """ :param `image_file` for the complete path of image. :param `format` is format for image, eg: `png` or `jpg`. """ if not os.path.isfile(image_file): return None encoded_string = '' with open(image_file, 'rb') as img_f: encoded_string = base64.b64encode(img_f.read()) return 'data:image/%s;base64,%s' % (format, encoded_string) print(image_as_base64( photo.image.path)) the output not work: data:image/png;base64,b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSExMVFhUXGR0YFxgYGBobGBcXHhYeGRcYGBoaICggGB4lGx0bIjEjJSkrLi4uHh8zODMtNygtLisBCgoKDg0OGxAQGysmICUtLS0tLS0tLS0tLS0tLS0tLS0tL S0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAFAAEDBAYCB//EAEkQAAIBAgQDBQQJAQQIBAcAAAECEQMhAAQSMQVBUQYTImFxMoGRoQcUI0JSscHR8OEVM2JyU2OCkpOy0v EkQ6KzCBZEc6TC8//EABgBAAMBAQAAAAAAAAAAAAAAAAABAgME/8QAJREAAgICAgMAAgIDAAAAAAAAAAECERIhAzETQVEiYRSBBDJx/9oADAMBAAIRAxEAPwAZw6l3FAVe7B72KrgAmGcEqD41gaSN9RY6ttN46CIr1EqK/wBq9Bx4QdOsJdrRqpqxII0 3UyCDGCXZftRl+4q06zKlUD7N2mGG8apt4pOmwvzk4qjtxTo1DTqMj0pBOkhmOpIcreOZFumOJSbk1ib1SuyRVyzEv31RvYlokQHdgwUiSQsEHaW28JGO9GWqugCwPDqPjB7su+sgNcEBVHKe82kQBeY+lGmtZ6lHLtddKM7AGbXKr7NxNib4ov8ASdUL q31SidJBEliRdm8Jjw+Jzy2AGLXHN+iXNL2FOKU8pVKNUr1qbIRqKqRJZkDSGQgEFVAUWsbnY1eL/wBniitMs4hGAGp7VCgZbhNhUEExteACJr53t1TOWqd1TUVngeJJPsBA83BI0hh/iJPM4IdruOCmtNqVGgyka/ZBT20CkXuQKYX/ACkzyxpHUkmKW 02AuG8PyYzNVBUNSmNKI5LENqg1o7kSSEJCn2ZuTtgxl8rlmosrVagjSviK954hTnTTVOReqswfZU31WF8P7ZMRVY5ehqVO8B0c1rBgI2+/pn8IAxey/HX7tWWlSL1tD1AQY1KSaREEQdYDT+KPLGk3vZnFfDnKNkai6PrFWEZSGKFY01gVaAntd0GsQZ MbHFhsj...... -
How to run django an react project on pycharm?
I have a a complied version of react.js but I am not familiar with react.js. How do i run django project with react.js? -
(Django) Dynamically adding custom form to Inline admin
CONTEXT I'm building my personal website, and wanted to handle database translation. While django-apps already exist for it, I thought it'd be fun and interesting to build my own translation package. I'm currently at the last step, which is showing the Translation instances directly into the object's admin STRUCTURE What you need to know about the database is that I have the following tables/models: My models that have fields which require translations: Job, Type, Article, etc. Language (list of available languages) Item (equivalent to saying "the NAME field from the JOB model, instance 33" Translations (Many to many with Language and Item) As for the relationships that matter to us: Job, Type, and Article all have ForeignKeys to Item Note that they can have SEVERAL ForeignKey (if they have several fields that need translating) Item has a GenericForeignKey to store Job, Type, and Article instances Translation has a ForeignKey to Item WHAT I'M TRYING TO DO In the admin, in the Type (or Job, or Article) detail view, I'd like to directly display the Translation instances related to its object (Type--> Item --> Translation). It's basically like a nested inline, but I only display the last level. That way, I … -
How to flatten JSON before serializing?
Consider following JSON post request: { "a":{ "b": 1, "c": 1 } } my model only has fields for b and c. I need to flatten the JSON and serialize the following: { "b": 1, "c": 2 } I'm using serializers.ModelSerializer class to serialize: class CardTransactionEventSerializer(serializers.ModelSerializer): class Meta: model = CardTransactionEvent fields = [ "a", "b", ] view: class MyListView(generics.ListCreateAPIView): queryset = models.MyModel.objects.all() serializer_class = serializers.MySerializer model: class MyModel(models.Model): a = models.CharField(max_length=20, blank=False, ) b = models.CharField(max_length=10, blank=False, ) I don't care about the a I just need to serialize what is inside of it. Thank you in advance. -
How to pass extra context to Django inline formset template
I have an inline formset that works fine. Now I need to add some additional context data to the inline formset template. It is straightforward to add context data to the parent template, but I do not seem to figure out how to set it to the formset template. The data is fetched from external service, so I want to add it only when needed. Two hacky ways I have identified: templatetags template context processor, which would include a function that would return the value Are there any cleaner ways to do this? -
Django ModelChoice field is set to required=False but is still required in the browser
class One(forms.ModelForm): space = forms.ModelChoiceField(queryset=models.Space.objects.none(), required=False) mode_specific = False class Meta: id_fields = ["name", "description", "space"] def __init__(self, *args, **kwargs): super(One, self).__init__(*args, **kwargs) # this returns false print(self.fields["space"].required) But on the template, the "space" is still required, I'm not sure what the issue is. -
what value should I provide instead of "Confirm" if that is the issue! Or else please help me out about the issue
Well while deleting my 'posts'in 'blog' i got an error stating TemplateDoesNotExist. "Blog/post_confirm_delete.html". Do I have to give the address about the "post_delete" file in the "home" as well? After already linking it to "post_details". Please check the code below. Template post_delete file {% extends 'base.html' %} {% block content %} Delete post <form action="" method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ post.title }}"?</p> <input type="submit" value="Confirm" /> </form> {% endblock content %} views file class BlogDeleteView(DeleteView): model = Post template = 'post_delete.html' success_url = reverse_lazy('home') reverse_lazy is already been impoerted. Linking file "post_detail.html" which contains URL Tags {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> {% endblock content %} MY URLS file all the models are already been imported urlpatterns = ( path('post//delete/', BlogDeleteView.as_view(), name='post_delete'), ) and my model class from django.db import models from django.urls import reverse Create your models here. class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete = models.CASCADE, ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) -
how to redirect the page url when it fails?
I want to redirect the page when it fails, Accessing the page with this works fine http://192.168.0.114:8686/test/1/ http://192.168.0.114:8686/test/2/ but when I try to access this http://192.168.0.114:8686/test it throughs an error, when the error occurs it want the value as "page_no=1" urlpatterns = [ url(r'^', include(router.urls)), url(r'^test/(?P<page_no>\d+)/$', views.test.as_view(), name='test_page'), ] Page not found (404) Request Method: GET Request URL: http://192.168.0.114:8686/test Using the URLconf defined in couponer.urls, Django tried these URL patterns, in this order: ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] admin/ ^ ^^p//$ [name='udemylinks-list'] ^ ^^p\.(?P<format>[a-z0-9]+)/?$ [name='udemylinks-list'] ^ ^^p//(?P<pk>[^/.]+)/$ [name='udemylinks-detail'] ^ ^^p//(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='udemylinks-detail'] ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^pages/(?P<page_no>\d+)/$ [name='Pages'] ^html/(?P<page_no>\d+)/$ [name='index'] ^test/(?P<page_no>\d+)/$ [name='test_page'] The current path, test, didn't match any of these. -
Django - where can I find the output of print() statements in production?
Django - where can I find the output of print() statements in production? I'm using a Digital Ocean droplet, Ubuntu 16.04. I don't see print() output in access.log or error.log files. Is this something I need to set up manually? -
How do I retrieve specific objects from a model related to another model through a foreignkey?
I am building a django app which basically shows newsfeeds (a thematic + a series of news items). Thematics and items are manually entered in the DB through two models. These two models: a 'Feed' model, which describes a newsfeed thematic and a 'Feed_element' model, which describes news items which enter under a specific thematic (a 'feed'). The Feed_element is related to the Feed model through a Foreignkey. I'd like to get the feeds that respond to a criteria (front_feed = True, see attached models code) and the accompanying feed_elements, which I thought I could wove together in the view with a select_related(). But this doesn't work. I cannot figure the view syntax. MODELS # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Feed(models.Model): feed_name = models.CharField(max_length = 200, default = "country_name") feed_current = models.TextField(max_length = 10000, default = "feed_current") feed_country = models.CharField(max_length = 200, default = "feed_country") feed_front = models.BooleanField(default = False) def __str__(self): return self.feed_name class Feed_element(models.Model): parent_feed = models.ForeignKey(Feed, on_delete = models.CASCADE, related_name = "elements") element_date = models.DateField() element_short = models.TextField(max_length = 200, default = "element_short") element_long = models.TextField(max_length = 200, default = "element_long") def __str__(self): return … -
Django geoip2 + Maxmind working locally, but not in production?
I'm able to get a response object and render it to the page locally, but on my live site it doesn't work. I'm using Maxmind's binary database, which is the GeoLite2-City.mmdb file in my project folder. This also works in my website's Ubuntu 16.04 terminal: import geoip2.database reader = geoip2.database.Reader('/home/jake/project-main/project/GeoLite2-City.mmdb') ip = request.META.get('REMOTE_ADDR', None) location_lookup_response = reader.city(ip) print(location_lookup_resonse) However, it doesn't work on the site. Any thoughts here are appreciated. -
django-wiki: why does it have the root article?
I'm new to working with django wiki (and also Django) -- why is the root article in django wiki set up the way it is? Ideally I would like my wiki to have multiple articles at the first level, rather than starting with a single root article. With the way it works currently, I would have to create a root article whose only purpose is to branch out to the real articles. -
Serializing or passing json objects into Ajax
The Json object was returned and I want to extract the data in JavaScript In the sense of how to pass on the loop fields and extract data def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) listing_json = serializers.serialize("json", listing) except Listing.DoesNotExist: raise Http404('places not found!') data = {"listing_json": listing_json} return JsonResponse(data) $.ajax({ url: "/For-Sale-Listing"+"/" + parseInt(data[0]), type: "GET", data: {'Subscription': 1}, success: function(data) { console.log(JSON.parse(data.listing_json)); }, error: function(xhr, status, error) { } }); -
Django - Add extra field to choices
I want to have a choice, with three elements: 1: This will be saved in the database 2: This will be used as a human-readable representation 3: This will be used as an extra information fur humans. (db_value, represantation, description) I tried to add that using a custom widget, but I get this error: ValueError: too many values to unpack (expected 2) from django.forms import widgets This is my code: class ExplainingChoiceWidget(widgets.Select): description = "A choice field, which explains the choices" template_name = "django/forms/widgets/explaining_choice.html" def __init__(self, choices, *args, **kwargs): prepared_choices = [ [choice[0], choice[1]] for choice in choices ] self.choices = prepared_choices print(prepared_choices) super().__init__(choices=prepared_choices, *args, **kwargs) And this is my choices: comment_user_visibility_choices = [ ["public", "Öffentlich", "Dein Vorname und dein Personentyp sind öffentlich sichtbar"], ["limited", "Beschränkt", "Nur dein Personentyp ist öffentlich sichtbar"], ["anonymous", "Anonym", "Der Kommentar zeigt deine Person nicht an"] ] -
Django Channels: add/remove workers dynamically
Django channels adds the concept of channels for things like websockets for real time updates in a browser. The example app in the tutorials demonstrates a chat app where consumers can send data to and from a channels group without any centralized source. But how would this work in a scenario with a data source, i.e. a stocks app? This would be a one-to-many system: a single data source broadcasting data on a channels group with many consumers. In order for this type of system to work, each channels group would require a worker, but from the channels docs it seems that workers must be a static thing, they cannot be dynamically added or removed to channels. Is this type of worker system possible in Django Channels and if so how? -
Persistent MongoDB Connection With Django
I am currently using (or hoping to use) both PostgreSQL and MongoDB for my Django project. When it comes to MongoDB I've been looking at PyMongo to make the connection, and add/edit info using Python. Most likely I will be calling PyMongo in my views.py to read/insert/edit data from MongoDB. For the sake of this question, let's say I have a view called worksheet, which querys some data from MongoDB relevant to the current user. However I would like to maintain a persistent connection to the database so that I do not have to make a new connection every time a user visits the worksheet view. Is there any way I could make a persistent connection so I am not wasting time/resources making new connections to MongoDB every time? Thanks. -
How to display a Python list of strings that contains HTML and JavaScript in a template with JS
I have a python list that contains a list of strings. Those strings contain HTML and JavaScript. Right now, I am using sentences = json.dumps(l) in Django view, then in the template I use {{sentences|safe}}, it works for some strings, but it breaks on the strings that contain lots of HTML and JavaScript. How do I fix this problem? Thank you for your help. I tried JSON.parse(sentences), {{sentences|escapejs}}, {{escape|safe}} # in django view sentences = json.dumps(l) return render(request, 'detail.html', { }) // in template, attempt to pass the jsonified python list to js array var random = {{sentences|safe}}; SyntaxError: "" literal not terminated before end of script 73:78:35396 SyntaxError: unexpected token: identifier 73:78:12 SyntaxError: unexpected token: identifier 73:78:4 SyntaxError: unexpected token: identifier 73:78:20 SyntaxError: unexpected token: identifier 73:78:20 -
Two ways of including an app in INSTALLED_APPS
Say I have an app called polls. What is the difference between including an app in INSTALLED_APPS like this 'polls.apps.PollsConfig' and just specifying the app's name ( 'polls')? The official Django tutorial recommends the former. -
Save Django ModelForm with CheckboxSelectMultiple with no boxes checked
A Django Form using a CheckboxSelectMultiple widget posts back nothing for the field using the CheckboxSelectMultiple widget if no boxes are checked. class AlarmForm(forms.ModelForm): class Meta: model = models.Alarm fields = ['phone_contacts', 'disabled'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user = self.instance.user self.fields["phone_contacts"].widget = forms.widgets.CheckboxSelectMultiple() self.fields['phone_contacts'].queryset = user.phonecontact_set If the user viewing the form checks no checkboxes, the idea is that the model's phonecontact_set field ( a ManyToManyField) should be cleared. Instead, if no boxes are check, that field isn't saved at all. This is apparently because unchecked check boxes include no values in the form POST in the web browser. Still, it seems there must be a way to make Django do this without completely re-implementing the save functionality, but I can't seem to find the Django way to do this.. -
Pycharm can't find Django app 'users' when running tests
I was handed a project which uses Django and Docker, but when I run Django tests Pycharm always seems to have problem finding the users application. Other people in the project have it running without problems but even though we tried to copy their settings, it wouldn't work. I also downgraded to their exact Pycharm version without success. What could be wrong? I have Docker desktop running without any problem. It's able to create containers and all that. I've also included it in Pycharm with success. I've also created an interpreter through Docker-compose with a valid .yml file. This file is my colleagues. I've of course added it as my project interpreter. I've set up a Django test configuration with appropriate interpreter and with an empty target field so that all applications in INSTALLED_APPS are run, as per documentation. Still, the module 'users' cannot be found. Passing in DJANGO_SETTINGS_MODULE=config.settings.local to the test configuration yields the same error. However, when I run from the terminal, all works as expected. What might be the problem here? -
OperationalError at /admin/blogapp/post/220/change/ no such table: blogapp_post_likes?
I've made a django blog app and its working fine. Now I'm trying to add a like feature to the blogs by the users. I added a likes field in my Post model but as soon as I ran the makemigrations and migrations command and went into my django-admin and click on the Post model, I got this -no such table: blogapp_post_likes. I'm learning from this tutorial and he also did the same thing but his migrations worked. I've tried deleting the migrations folder from the project prior to the makemigrations and migration command but its not working. Here's my models.py file- from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import User from datetime import datetime, timedelta from PIL import Image class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) contact = models.CharField(max_length=12,blank=True) image = models.ImageField(upload_to='profile_pictures', default='default.png') description = models.CharField(max_length=100,blank=True,null=True) def __str__(self): return f'{self.user.username}' class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True) likes = models.ManyToManyField(User,related_name='post_likes',blank=True) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('blogapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=100) text = models.TextField(max_length=264) created_date = models.DateTimeField(default=timezone.now) …