Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error get object with limit return "\n" in field
Hi! i have a error with get objects messages = Message.objects.filter(trade=1)[:20] messages[19].message "\n" // messages[19].message is really "Hi Venezuela" but return "\n" my field is: message = models.CharField(max_length=200, null=True) -
Django-Cms and Django-shop migration issues
I started creating my website on my own PC using the Django-cms install script then I tried to add a lot of applications such as Django-Helpdesk and others and everything was smooth until I tried to add pieces of djangoSHOP demo project and dependencies to email_auth. Then I started to have report that the migration history was inconsistent and migrations applied out of order. Before adding djangoShop to the installed apps, I just add the following commands to setup the DB: manage.py migrate --run-syncdb --noinput manage.py migrate --noinput and everything was ok. Now, as I'm just starting, I don't have changes to the schema to apply but most of the django apps I try to install have migrations folders with several migrations. I don't want to update an existing schema, I want to create a new one. I'm working from a blank database so do I really need to apply all those migrations ? To me it seems that the default behaviour of running migrations is not compatible with starting from a blank db, I don't understand what to do just initialise the database to just have the required tables created. Did anyone got the same kind of problems ? … -
Embedded django site seems to have a problem with its CSP settings
My django(2.1) app needs to be able to be embedded in an iframe in a partner's website. I'm currently running it on google app engine where I have the following app.yaml settings: handlers: - url: /.* static_dir: static/ secure: always http_headers: Content-Security-Policy: "frame-ancestors 'self' partnersite .com *.partnersite.com www.partnersite.com;" I can now access the login page through the partner site but when I try to log in I get the following error: CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set. The templates have {% csrf_token %} tags. I'm stumped, if anyone has any help or feedback please let me know. -
Add new rows to related model on creation of parent model in Admin
I have models for adding products. The name of the products are in several languages, so I made a on-to-many raltion with a 'Name'-model. This is my models class Product(models.Model): active = models.BooleanField() class ProductName(models.Model): productName = models.CharField(max_length=250) product = models.ForeignKey('Product', on_delete=models.CASCADE) language = models.ForeignKey('Language', on_delete=models.CASCADE) def __str__(self): return self.productName class Language(models.Model): language = models.CharField(max_length=55) languageAbbreviation = models.CharField(max_length=10) def __str__(self): return self.language Now in the admin page of mysite, I want to add product names on creation of a product. I tried some misarable attempt with some thing I found about 'admin.TabularInline'. But I think that is wrong because nothing is working with that. Any suggestion about how to solve this is much appreciated! -
django datetime not validating right
I' using the HTML5 datetime-local input type to try and get some datetime inputs into my database The ModelForm class Meta: looks like the following: class Meta: model = ScheduleEntry fields = ['calendar', 'title', 'start', 'end', 'assets', 'users'] widgets = { 'calendar': forms.Select(attrs={ 'class': 'fom-control chosen-select' }), 'title': forms.TextInput(attrs={ 'class': 'form-control' }), 'start': forms.DateTimeInput(attrs={ 'type':'datetime-local', 'class':'form-control' }, format='%Y-%m-%dT%H:%M'), 'end': forms.DateTimeInput(attrs={ 'type': 'datetime-local', 'class': 'form-control' }, format='%Y-%m-%dT%H:%M'), 'assets': forms.SelectMultiple(attrs={ 'class': 'form-control chosen-select' }), 'users': forms.SelectMultiple(attrs={ 'class': 'form-control chosen-select', }) } I keep failing on form validation and its causing me to pull my hair.This is the documentation page that shows it should work, but it looks like I'm missing something? EDIT FOR CLARIFICATION: The error message is for both start and end and it's Enter a valid date/time -
Setting up Django admin in visual studio
Can anyone help me how to set up the admin page in visual studio? I mean the admin.py page. Which commands should be run. I have tried many methods but none succeeded. thanks Saeed -
Assigning Foreign Key with Django's CreateView
I've been wrestling with this all day. I'm attempting to come up with a solution to save multiple pictures per single form. I feel like I'm on the home stretch, but my issue now is I can't for the life of me get the ForeignKey to auto assign when the form is submitted. The code below is functional in every way other than no FK is applied to the DB record. Any help is greatly appreciated! Models.py from django.db import models class FieldEvaluation(models.Model): "Our default field evaluation form" created_at = models.DateTimeField(auto_now_add=True) order = models.CharField(max_length=50) class FA_Attachments(models.Model): field_evaluation = models.ForeignKey( FieldEvaluation, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='photos') Forms.py from django import forms from .models import FieldEvaluation, FA_Attachments class FieldEvaluationForm(forms.ModelForm): class Meta: model = FieldEvaluation fields = ['order'] # not attachments! attachments = forms.ImageField( widget=forms.ClearableFileInput(attrs={'multiple': True})) Views.py from django.views.generic.edit import CreateView from django.shortcuts import render from .forms import * from .models import * class FieldEvaluationView(CreateView): model = FieldEvaluation form_class = FieldEvaluationForm template_name = 'QA.html' success_url = '?success' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('attachments') if form.is_valid(): for f in files: FA_Attachments.objects.create( image=f) return self.form_valid(form) else: return self.form_invalid(form) -
Django website in an iframe is getting CSRF error on login
My django(2.1) app needs to be able to be embedded in an iframe in a partner's website. I'm currently running it on google app engine where I have the following app.yaml settings: handlers: - url: /.* static_dir: static/ secure: always http_headers: Content-Security-Policy: "frame-ancestors 'self' otherdelta.com *.otherdelta.com www.otherdelta.com;" I can now access the login page through the partner site but when I try to log in I get the following error: CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set. The templates have {% csrf_token %} tags. I'm stumped, if anyone has any help or feedback please let me know. -
Keeping database foreign keys consistent
I am trying to write a django app with a PostgreSQL database. My problem can be reduced to the following minimal example: Organization has 0 ... N workers Worker belongs to an organization Task belongs to an organization is assigned to no-one, or assigned to one worker within the same organization I am unsure of how to design the database in a way that prevents inconsistent state - since both Worker and Task need to have a foreign key pointing to the Organization they belong to, it is possible to end up with an inconsistent state where a worker from organization A is assigned a task from organization B. The only solution I could think of was verifying the constraint in the save method: class Organization(models.Model): name = models.CharField(max_length=255) class Worker(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class Task(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) assigned_to = models.ForeignKey(Worker, null=True, on_delete=models.SET_NULL) def save(self, *args, **kwargs): if self.assigned_to and self.assigned_to.organization != self.organization: raise ValidationError('Task and Worker belong in different Organizations.') return super(Task, self).save(*args, **kwargs Is it possible to create a better solution which still prevents inconsistent state? My own solution doesn't seem like a good one from a database design … -
Why is django not using my custom encoder class?
I have two classes: Website and WordpressWebsite. WordpressWebsite subclasses Website. When an instance of WordpressWebsite is being encoded into JSON, only the attributes of WordpressWebsite are present (and none of the attributes of Website). My goal is to write a custom encoder which will encode a WordpressWebsite as a Website instead. This is what I have so far: from django.core.serializers.json import DjangoJSONEncoder from websites.models import Website class WebsiteEncoder(DjangoJSONEncoder): def default(self, obj): raise Exception() # TEST if isinstance(obj, Website) and hasattr(obj, 'website_ptr'): return super().default(obj.website_ptr) return super().default(obj) I have the following test case: from django.core import serializers from django.test import TestCase from websites.models.wordpress import WordpressWebsite from websites.serialize import WebsiteEncoder class SerializationTest(TestCase): def setUp(self): self.wordpress = WordpressWebsite.objects.create( domain='test.com' ) def test_foo(self): JSONSerializer = serializers.get_serializer("json") json_serializer = JSONSerializer() json_serializer.serialize( WordpressWebsite.objects.all(), cls=WebsiteEncoder ) data = json_serializer.getvalue() print(data) This test case runs fine. It does not raise an exception. Does anyone know why WebsiteEncoder.default is not being invoked? -
How to do a relationship using DRF to another table without foreignKey
I can not do relatioships between two tables without relationships. My models are : class exampleModel(models.Model): quantity = models.IntegerField(blank=False, null=True) comment = models.CharField(max_length=100 , blank=True, null=True) class Meta: db_table = "example" class Logger(models.Model): id_table = models.IntegerField() table = models.CharField(max_length=20 , blank=True, null=True) comment = models.CharField(max_length=100 , blank=True, null=True) action = models.CharField(max_length=100 , blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "logger" I already have filled logger Model, but , I have not be able made the exampleSerializer. My serializers are: class LoggerSerializer(serializers.ModelSerializer): class Meta: db_table = u'logger' model = Logger fields = '__all__' class exampleSerializer(serializers.ModelSerializer): last_log = LoggerSerializer(read_only=True) class Meta: db_table = 'example' model = ExampleModel fields = ( 'id' , 'last_log' , 'quantity') in logger saves : id_table : 'primary key of example', table : 'example' comment : 'custom comment', action : "CRUD" -
How to update queryset with a list of value respectively (ORM)?
I have a queryset that contains 5 instances, and I have a list also contains 5 numbers, I want to be able to update the field position inside the queryset without iterating over it: queryset = Model.objects.all() # 5 instances order = [0,1,3,5,6] queryset.update(position= *order) # doesn't work The expected result would be: instance1.posititon = order[0] instance2.posititon = order[1] instance3.posititon = order[2] instance4.posititon = order[3] instance5.posititon = order[4] -
How to convert user input to datetimefield in django
I need to get a user input and make some changes (convert it to Georgian date with some sort of function) and store it as a DateTimeField. Where that function comes in? -
Is it ok to pass an OrderedDict as a Celery task argument?
I have inside a Django REST Framework's serializer an overridden update method. In this update, as user can send lots of children, I have an asynchronous Celery task process_children, to deal with the kids. class MyModelSerializer(serializers.ModelSerializer): .... @transaction.atomic def update(self, mymodel, validated_data): try: children_data = validated_data.pop('children') transaction.on_commit(lambda: process_children.apply_async( countdown=1, args=[mymodel.id, children_data])) except KeyError: pass ... In the args, there is one argument which is not a json object but an OrderedDict: children_data. The task looks like: @app.task def process_children(mymodel_id, children_data): mymodel = MyModel.objects.get(pk=mymodel_id) children = mymodel.children.all() for child_data in children_data: try: child = children.get(start=child_data['start']) child = populate_child(child, child_data) child.save() except Child.DoesNotExist: create_child(mymodel, child_data) I read that we should only send json (or pickle, yaml, whatever...) args. But this setup seems to work I can even send datetime object (i.e. the start attribute I use in the task to match a stored child with new values sent through the api). So what's happening here? Is everything ok, celery serializes and deserializes OrderedDict like a boss. Or I am crazy and should serialize before invoking the task and deserialize inside the task? -
How to assign value to a variable on Django template through jQuery
I have a Django template file working with a passed value like the below. {% include 'boutique/rating.html' with score=[I want to put value here] %} When I usually put value into the template, I could easily do it by doing like the below. {% for store in stores %} {% include 'boutique/rating.html' with score=store.review_score %} {% endfor %} However, as I get into more complex templates, I need to put the value through jQuery. Is there a way that I can acheive this through jQuery? -
If, elif > too many conditions
I have here several conditions and 'sub-conditions'. It looks quite messy and I wonder if you know a better way to write this code here? def form_valid(self, form): instance = form.instance # Conditions if instance.available_amount <= instance.redeemed_amount: instance.status = Discount.STATUS_NO_MORE_LEFT elif instance.valid_until <= timezone.now(): instance.status = Discount.STATUS_EXPIRED # Conditions to set active elif instance.status == Discount.STATUS_NO_MORE_LEFT: if instance.available_amount > instance.redeemed_amount: instance.status = Discount.STATUS_ACTIVE elif instance.status == Discount.STATUS_EXPIRED: if instance.valid_until > timezone.now(): instance.status = Discount.STATUS_ACTIVE -
DJANGO render new result values from AJAX request to HTML page
in the last days i trying to learn form submission using AJAX and django in backend. I can take successfully form inputs values using AJAX in django views.py (validate_number) (working) follow this example . in this views.py validate_number i calculate NEW sum of numbers and i want this sum value to render back to html page,but i don't know how to do. any idea how to render results from AJAX request back to html page ? here the code html form : <form id="form" action='' data-validate-number-url="{% url 'validate_number' %}" method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="form-group col-md-6"> Select the C Raster Dataset:<br> <select name="CC" class="form-control" id="CC"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> Select the P:<br> <select name="PP" class="form-control" id="PP"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> Select the F:<br> <select name="FF" class="form-control" id="FF"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> </div> <button type="button" class="btn btn-primary next-step1">Save and continue</button> <p>{{sum}}</p> Select the GG:<br> <select name="G" class="form-control" id="GG"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> Select the JJ:<br> <select name="JJ" class="form-control" id="JJ"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> <button type="button" class="btn btn-primary next-step">Save and continue</button> Select the FINAL:<br> <select name="FINAL" class="form-control" id="FINAL"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> <option value="10">ten</option> </select> … -
Django: Integer field that is the count of ManyToMany field
I've got a model with a field countries = models.ManyToManyField(Country, blank=True) I want a new field count = models.IntegerField() that is the count of the countries that also updates when countries are added and removed. I know there is a .count() method, but I'm not sure how to set my count field equal to that. -
Django pass list to form to create Choices
I want to create a ChoiceField on a form that has choices from a list passed to it by a view. from django import forms class OrderForm(forms.Form): product_choices = [] def __init__(self, products=None, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) if products: print(products) choices = enumerate(products) product_name = forms.ChoiceField(label='Product', choices=choices) Not sure how to use the init function to achieve this? -
How to use chart with a Wagtail cms
I need to include custom charts to a streamfield function. As you can find with Tauchart : https://api.taucharts.com/tutorials/5min.html But how is it possible to a user to modify the data from the wagtail admin? I have absolutely no idea on how I can do it… I’m pondering about a form but it’s possible to add a form to a streamfield ? I think yes, I can do it with a link… to an existing form... But that seems hard to make and not a good idea… What do you think about? What is the best practise for you ? Do you have any examples of Taucharts integration into a cms? https://www.taucharts.com -
How to connect Django project with MS SQL server?
I am beginner in Django framework and trying to connect Django project with MS sQL server on my localhost. I have tried a few of libs like pyodbc-azure but it is not working in my case and I am getting the errors. "C:\Program Files\JetBrains\PyCharm 2018.1.5\bin\runnerw.exe" "C:\Program Files (x86)\Python37-32\python.exe" C:/Users/hyaqub/PycharmProjects/SpotDash/manage.py runserver 8000 Unhandled exception in thread started by .wrapper at 0x04A1BD68> Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\site-packages\django_pyodbc\base.py", line 55, in import pyodbc as Database ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\core\management__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, … -
Can't get JSON data from file from local domain URL (Django static file)
I want to load data from a JSON file to use with d3.js I'm using Django and the URL of the the JSON file json_path looks like this:/staticfile/example.json. I'm using the following code to read the data and do things: d3.json(json_path, function(error, data){ // Do stuff with data } Everything works fine if I use the local IP of the server on the browser: 192.168.x.x. However, when I use the local domain foo.com that points to 192.168.x.x, I can't load the data anymore from d3.json(). data is null and I can't understand the content of error. I'm missing something obvious probably related to callbacks or something but I have trouble understanding the big picture. The whole Django server works perfectly same from both 192.168.x.x and from foo.com and everything is local. Any ideas? -
Django Subquery returns only the first element
This is a simplified version of the models: class Toy(models.Model): #generic fields class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): order = models.ForeignKey(Order) toy = models.ForeignKey(Toy) points = models.PositiveSmallIntegerField(default=3) A customer can make multiple orders, to it increases the number of points per toy. This subquery, only returns the first row of OrderItem: class Customer(models.Model): def get_toys_with_points(): order_items = OrderItem(toy=models.OuterRef('pk'), order__customer=self) toys = Toy.objects.annotate( points_sum = models.Sum(Subquery(order_items.values('points'))) ) return toys So, when I pull that into my template: {% for toy in customer.get_toys_with_points %} {{ toy.points_sum }} {% endfor %} I am always getting the value of the first row (even if there are more purchases that would sum up to 25 for example). -
Cross Site Request Forgery protection with Django and websockets
I've successfully created a websocket on my Django(v. 2.0)-powered website using Django channels (v. 2.1.5). Everything is fine but I'm wondering what about CSRF token. Is it needed in case of websockets? Documentation says that it's enough to use OriginValidator to prevent such thread but I'd like to ensure that. I mean, what has happend to CSRF token? Am I just sending data through secure channel without it and backend automagically checks everything? And if that's so then why? And why simple views can't do that? I know it's preety open question but I was not able to find any specific explanation, if anyone has one I'd more than greatful. Cheers! -
Django form ChoiceField from api query
I have a Django form and I want to pass a list to it that might change depending on querying an external api - how do I do this? I have a view that gets a form and a form with a ChoiceField, but how do I pass the ChoiceField a list from outside the form?