Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django order_by for non english characters
I have a queryset of countries where some of them start with non english characters like "Þ" and "Í", when using order_by they are just shown at the end instead of being sorted properly. This is the result: >>> from someapp.models import Country >>> countries = Country.objects.all().order_by("country") >>> countries <QuerySet [<Country: Bandaríkin>, <Country: Bretland>, <Country: Danmörk>, <Country: Kanada>, <Country: Noregur>, <Country: Svíþjóð>, <Country: Ísland>, <Country: Þýskaland>]> How would I use order_by with a non english alphabet? Here is the model: class Country(models.Model): country = models.CharField(max_length=100, unique=True) def __str__(self): return "%s" % (self.country) class Meta: ordering = ['country'] -
Problems Rotate Image in Django Admin
I am using django 2.2.3 with python 3.6.6. I have a mode that uploads an image into a FileField (because there are images and pdfs). Sometimes the image is rotated and the EXIF data is not always present, so I put together a jQuery (v3.3.1) script to rotate the image in the admin change page, and send the correct rotation back to the server using an ajax call, and then I rotate the image on the file system using PIL 6.1.0. That all works, expect when I refresh the page the image displayed in the django admin is not rotated. If I check on the filesytem, the image is rotated. The jQuery script: (function($) { $(document).ready(function(){ var rotation = 0; var image_source = "" $('#uploaded_image').click(function() { $('#uploaded_image').rotate(rotation + 90); rotation += 90; if (rotation == 360) { rotation = 0; } image_source=$('#uploaded_image').attr('src') }); // Listen for clicking the a save function on the page // and then send the final roation value back to // the server to update the image. $('input[name="_save"]').click(function(){ save_rotation(rotation, image_source); }); $('input[name="_addanother"]').click(function(){ save_rotation(rotation, image_source); }); $('input[name="_continue"]').click(function(){ save_rotation(rotation, image_source); }); // ajax function to send rotation value back to the server function save_rotation(rot, src){ if (rot != … -
Import mongodb dump consistent with Django
I have a new Django App. I import json dump into mongodb using terminal like: mongoimport --db mydb --collection mycollection --file myfile.json The files are well displayed within the admin panel. But when I create a new entry into the mycollection via admin panel, Django gives it an id which already in the mongo json dump. Is there a way to tell Django to be consistent with the database and start incrementing the id from the last entry in the database collection? -
No 'Access-Control-Allow-Origin' header is present on the requested resource?
I solved some similar problems before.But for this time, I really don't know what's problem it is.I have checked all the possible that may rise the problem but still didn't solve it.And all the other api can work very well except this one. The problem is very common like this: Access to XMLHttpRequest at 'https://api.wzy-codify.com/api-app/MRI/' from origin 'https://www.wzy-codify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The frontend is written in Vue.js. The related code just like this: axios.post(this.API.mri_api,param,{headers:{'Content-Type':'multipart/form-data'}}).then((response)=>{ if(Number(response.data.status)===500){ this.$message.error(response.data.msg) } if(Number(response.data.status)===201){ this.$message.success('The upload object already exists') this.mri_data = response.data.data } else{ this.$message.success('Upload success!') this.polling() } }) The backend is supported by Django Rest Framework, and the CORS problem is fixed by using corsheaders The related settings like this: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( '*' ) ALLOWED_HOSTS = ['*'] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) -
Import models.py from parent directory
Why is it so hard to import a module from a parent directory in python. I have this file "upload.py" in my app directory import os import sys from books.models import Books print(Books.objects.all()) This is my app directory format - books __init__.py models.py -uploader __init__.py upload.py So I am trying to import the model into the upload file ad it is logging ModuleNotFoundError: No module named 'books' -
Django many-to-many query dict representation
I have this query campaign_query = Campaign.objects.filter(id__in=campaign_ids).select_related('campaign_manager__name').prefetch_related('products').values( 'id', 'name', 'campaign_manager_id', 'campaign_manager__name', 'products' ) Which is supposed to return a dict representation of my Campaign obj. The problem is that 'products' is a many to many relationship and is only returning the first product, not a list of all of them. Return example: <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': 34}]> What I want <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': [34,35,36]}]> -
Nested Django view with .html inserted using include tag
I would like to know if anyone has any best practice recommendations for what I am trying to do. Which is essentially to render a Django view (from and within an already rendered view) using the include tag so that the html is structured as I would like (it is part of a bootstrap navbar). The .html I would like to have is a sort of dropdown menu. I am currently just rendering the dropdown using the include tag. So it using the same Django view as the rest of the page. And I am doing all the context passing to the main view which is then used also in the included template. I would like to give this dropdown its own Django view so that I only perform certain database queries and other calculations if the dropdown is opened, and also to keep some code separate where possible. It would be nice if someone with experience in this could let me know what they think, and if it even makes sense to try and split this into 2 views. -
How to use Django's RestAPI's update() function in models with swift?
I'm currently trying to link swift and a database (MySQL) using Django's Rest-API Framework. I've already Django and have it connected and it gets Post requests and Get requests fine. I'm just wondering if its possible to lets say, have a user fill in basic login info on one screen (username passcode, etc.) but then later fill in the rest of the information (like name, and address) at a later point and have Django update the row with their information on it. I'm planning to do this by having the user id in a variable (in swift) so it'll edit the row/column by the users id. This is what I have for django as the model and serializer: Serializer: from rest_framework import serializers from .models import Data class CasaSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'first_name', 'last_name', 'email', 'password', 'buyerorseller', 'creditscore', 'min_salary') Model: from django.db import models # Create your models here. class Data(models.Model): first_name = models.CharField(max_length = 50, default="") last_name = models.CharField(max_length = 50, default="") email = models.CharField(max_length = 50, default="", unique=True) password = models.CharField(max_length = 20, default="") buyerorseller = models.CharField(max_length = 6, default="") creditscore = models.IntegerField() min_salary = models.IntegerField() def __str__(self): return(self.last_name, self.first_name) I'm just wondering … -
How to pass the id of one class object to another class object in django views.py
This is for a library management web app, I need to filter a specific book object by it's id and make it as ISSUED when I click on issue button. Here I need to get the specific book that I selected by it's id. How can I implement it? Post.objects.filter(id=self.request.GET.get('id')).update(issued=True) -
My session isn't storing what i'm asking it to store, when I try to view whats in the session an empty list is returned
I am trying to add something to a session by performing a post request via a form, when I try to view what's in the session by going to a page and a empty list is returned (I see this []), I have looked around toher questions and tried adding this request.session.modified = True but it hasn't worked as I thought that the session may not have been saving. Can anyone suggest any possible solutions? Views def cart(request): cartSession = request.session['cart'] context={ 'cartSession': cartSession } return render(request, "OsbourneSpiceWebsite/cart.html", context=context) def menu(request): request.session['cart'] = [] context = { "items": Menu.objects.all(), } return render(request, "OsbourneSpiceWebsite/menu.html", context) def addToCart(request): if request.method == 'POST': request.session.modified = True itemID = request.POST['productId'] getItemFromPost = Menu.objects.get(itemid=itemID) if getItemFromPost is None: return HttpResponse("Error there is no data") cartSession = request.session['cart'] for item in cartSession: if item['Itemname'] == getItemFromPost.itemname: item['Qty'] += 1 break else: cartSession.append({ 'Itemname': getItemFromPost.itemname, 'Itemprice': int(getItemFromPost.itemprice), 'Qty': 1 }) request.session['cart'] = cartSession context = { "cartSession": cartSession } request.session.modified = True return render(request, "OsbourneSpiceWebsite/cart.html", context=context) Form <form action="{% url 'addToCart' %}" method="POST"> {% csrf_token %} <input name="productId" type="hidden" value="{{ item.itemid }}"> <div class="addToCartButtonContainer"> <button aria-label="Add" class="addButton " type="submit">+</button> </div> </form> Cart page (page that should display … -
Error when rebuilding search index in ElasticSearch/Django
When I run ./manage.py search_index --rebuild I get the following error: elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [bodystyle : {type=text}] [model : {type=text}] [carclass : {type=text}] [version : {type=text}]') I have tried to change the version of my elasticsearch. My current version is: $ curl -XGET 'localhost:9200' { "name" : "MOkbeEQ", "cluster_name" : "elasticsearch", "cluster_uuid" : "pF_Z62bBTl-Jq31HSuAhQA", "version" : { "number" : "5.6.8", "build_hash" : "688ecce", "build_date" : "2018-02-16T16:46:30.010Z", "build_snapshot" : false, "lucene_version" : "6.6.1" }, "tagline" : "You Know, for Search" } My documents.py code is as below: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from products.models import Product_Model @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Product_Model # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'model', 'version', 'carclass', 'bodystyle', ] -
How to connect heroku and godaddy correctly?
I am trying to park a django website hosted on heroku on godaddy but unfortunately I am unable to do so correctly. I have tried using heroku domains:add and also followed several tutorials. Project Specification Django website run in heroku free dyno Heroku dns configurations - Heroku DNS Panel GoDaddy dns configurations - GoDaddy DNS Panel I have assigned DNS targets from heroku to godaddy and kept the 'A' type entry default as Heroku does not support it. -
Which is the best python REST framework (preferably async platform) for an API gateway which would frontend the requests to these micro-services?
Are there any evaluations done for the python/async based platform (that is running in production)? Specifically looking at starlette, sanic, falcon or aiohttp? We are having more than a dozen of micro-services that are running in AWS on kubernetes platform. Designing an API gateway which would frontend the requests to these micro-services. We would be hitting close to 10K requests per sec during the peak, and the average trend of about 1k requests per sec during off peak. Flask and Django posed some issues, since most of these calls are inline calls to these micro-services (will be blocked anywhere from 1 to 3 secs range per request/response roundtrip). Would be great to get insights and feedback on the above frameworks. Flask and Django posed some issues, since most of these calls are inline calls to these micro-services (will be blocked anywhere from 1 to 3 secs range per request/response roundtrip) -
I am new in django framework and I dont know how to update data in postgres using django framework , can you give an simple example of how to update?
update data in postgresql using django html -
How can I update a Model field inside DetailView with a button click
I've created a maintenance App that allows the user to create and view the maintenance details. I have a page "maintenance-details.html" where I show all the details of a particular maintenance. Here is my views.py: class MaintenanceDetailView(DetailView): template_name = 'maintenance/maintenance-details.html' model = Maintenance def get_context_data(self, **kwargs): contacts_suppliers = ContactsSupplier.objects.filter(supplier__maintenance=self.object) hora_atual = datetime.datetime.now() context = super().get_context_data(**kwargs) context['contacts_supplier'] = contacts_suppliers context['hora_atual'] = hora_atual return context I have created a button on my template named "Mark as done". My Maintenance model has a BooleandField "done" with the purpose to set the task as done or not. What I'm looking for is the best way to update the model and set the "done" as "True" when the user clicks it. My models.py here: class Maintenance(models.Model): category = models.ForeignKey(SuppliersCategory, models.DO_NOTHING, db_column='Category') # Field name made lowercase. property = models.ForeignKey(Property, models.DO_NOTHING, db_column='Property_Reference') # Field name made lowercase. name = models.CharField(db_column='Name', max_length=25) # Field name made lowercase. created_date = models.DateTimeField(db_column='Date', auto_now_add=True) # Field name made lowercase. staffmember = models.CharField(db_column='StaffMember', max_length=25, blank=True, null=True) # Field name made lowercase. supplier = models.ForeignKey(Suppliers, db_column='Supplier') # Field name made lowercase. description = models.CharField(db_column='Description', max_length=500, blank=True, null=True) # Field name made lowercase. photo = models.ImageField(upload_to='maintenace/', db_column='Photo', blank=True, null=True) # Field name made … -
Why Django CheckConstraint doesn't works on MySQL
When I create one class with constraint like below: constraints = [ models.CheckConstraint( check=models.Q('plan' == 1), name="custom_constraint" ) ] I receive the message: (models.W027) MySQL does not support check constraints. HINT: A constraint won't be created. Silence this warning if you don't care about it. Why Django CheckConstraints works with PostgreSQL and not with MySQL? -
Django: How to apply the built-in password validators?
I like to test the django built-in validators on my registration form. So i added this... settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] forms.py from django.contrib.auth.models import User from django import forms import django.contrib.auth.password_validation as validators class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') # --- check duplicate def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] # --- django built-in validator def pass_validate(self): password = self.cleaned_data('password') try: validators(password, self.instance) except forms.ValidationError as error: self.add_error('password', error) return password views.py <...> def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Set the chosen password new_user.set_password( user_form.cleaned_data['password']) # Save the User object new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) <...> Unfortunately i can still register as a user with passwords like "123". So the min_length does not work. The pass_validate Function in forms.py was an approach, to add the … -
the image uploaded is not stored on the database
i'm creating a 'create an account view ' which the user can store his image, name ,lastname .... on my database the name,lastname... are registred but the image is not stored.why? in models.py: from django.db import models class information(models.Model): name=models.CharField(max_length=50) lastname=models.CharField(max_length=50) email=models.CharField(max_length=50) password=models.CharField(max_length=50) img=models.ImageField(upload_to='media',blank=True) in forms.py: from app1.models import information from django import forms class create_form(forms.ModelForm): class Meta: model=information fields=[ 'name', 'lastname', 'email', 'password', 'img' ] in views.py: def create_view(request,*args,**kwargs): my_form=create_form(request.POST or None) if my_form.is_valid(): my_form.save() print(my_form.cleaned_data['img'])**#########print :None** context={"form":my_form} return render(request,'first create.html',context ) in templates: <main> <section> <form action="" method="Post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="save"/> </form> </section> </main> -
cannot run mange.py runserver after updating to Django 2.2.4 and python 3.7 (toml.py)
When running python manage.py runserver --settings=project.settings_dev I get: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 600, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 585, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 303, in run self.run_loop() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 309, in run_loop next(ticker) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 349, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 365, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 264, in watched_files yield from iter_all_python_module_files() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 131, in iter_modules_and_files if spec.has_location: AttributeError: 'str' object has no attribute 'has_location' This is the function that errors: https://github.com/django/django/blob/master/django/utils/autoreload.py#L131 @functools.lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to … -
First django form is submitted, then second form will open. When second form will be submitted and validated, I wantI first form data to store in db
I am doing user registration with Phone verification using OTP. I have two forms: UserRegisterForm and PhoneOTP form. When user will submit UserRegisterForm then I want to save this form data temporary and then open the PhoneOTP form to take OTP from the user. When this form will submit and validated, then only I will take the UserRegisterForm data and will save to the database. So, how can I access the first form i.e. UserRegisterForm data when PhoneOTP is submitted?? I was trying to use Django Form Wizard. But, I thought that Form wizards are used only if a single form is split into multiple pages. But, in my case, I have two different forms. -
White line between divs
I'm trying to add some css to my site i'm working on, in order to practice django. So, i bumped into some problems with two divs, more precisely with a space or white line between them. If i type simple text, everything is ok and there's no white line. Also, i had an issue with p and other tags, but eventually figured it out and got rid of white line by setting paddings and margins to 0. But what i am supposed to do with these block content - i don't know. <!DOCTYPE html> <html lang="en"> <head> <style> body{ padding: 0px; margin: 0px; } .sidebar{ background-color: red; } .main-content{ background-color: blue; margin: 0; padding: 0; } </style> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="sidebar"> <a href="#">Home</a> <a href="#">Lists</a> <a href="#">Create</a> </div> <div class="main-content"> {% block content %}{% endblock %} </div> </body> </html> So, there's a white line between two divs (.sidebar and .main-content) and i have no idea why would it show up there. I also tried overflow: hidden, but it didn't quite solve the problem. It substituted the white line with padding or something i have no control over, meaning couldn't get rid of it anyways. … -
How to set Django to default None if a database query for a FileField fails? (e.g. a ValueError)
I have to make a series of queries for FileFields linked to a database's entries; for optimal succinctness I figured putting all the queries in a single dictionary, like {"<code>.mml</code> File":musicXMLObject.mmlFile.url,"<code>.m2</code> File":musicXMLObject.m2File.url,"<code>.wav</code> File":musicXMLObject.wavFile.url} would suffice. All of these FileFields have null=True and blank=True set, so it's inevitable that a ValueError will be triggered if it so happens that a database entry doesn't have a file on hand. Is there by chance an option to default failed queries that would otherwise trigger ValueError to instead output None? I know that a quick and easy workaround to this problem would be to simply use if statements, something like if musicXMLObject.mmlFile: //do stuff if musicXMLObject.m2File: //do stuff if musicXMLObject.wavFile: //do stuff but that option isn't nearly as succinct as a single dictionary. Thoughts? -
A way to define recurring with string or json?
I am looking for a way to define recurring with string or json string I need a non-hardcoded way to define recurring, for example, some client want to do some work every two weeks, some want to do it every half month. I cannot hardcode such recurring. Instead I want a way to define for each client in database, something like 'every two weeks, starting 2019-09-01', and then a existing class to parse it and return a well-formed result to use. -
With Django, how can validate input wiht unique_togther for two columns on two different tables?
I'm working on a rest API to track inventory of Laptops and Monitors. Each item is its own table and its own model, and I need away to have an "asset_tag" field unique across both. Both models inherit the "asset_tag" attribute from an abstract class "TaggedItem" as shown in the code. I've done some digging and I I know that the model option unique_together can validate uniqueness across fields in the same table. But I don't know how to get it to reference fields in different tables. from django.db import models class TaggedItem(models.Model) ASSET_TAG = models.CharField(max_length=8) class Meta: abstract = True unique_together = [] # <-- This is the part that isn't working class Laptop(TaggedItem): NOTES = models.CharField(max_length=255, default="") class Monitor(TaggedItem) NOTES = models.CharField(max_length=255, default="") -
Unable to display file pdf in template
I am creating a website where a user can answers few questions and upload PDFs. The upload works, in fact my media/documents folders contains the uploaded PDF files. In addition, if I enter the admin panel and click on the PDF, it opens a new windows containing the PDF. HOWEVER I am not able to create a clickable link that allows the user to visualise the PDF. Basically, in my template, I want the user to click a link and visualise the PDF he has just uploaded. To do so I wrote: templates.html <a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a> settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ main project urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('conditions/', TemplateView.as_view(template_name='conditions.html'), name='conditions'), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('projects/', include('projects.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Thirdquestion(models.Model): third_one = models.TextField() third_two = models.TextField() third_three = models.TextField() third_four = models.TextField() third_five = models.TextField() third_six = models.TextField() third_seven = models.FileField(upload_to='documents/') third_eight = models.TextField() third_nine = models.TextField() third_ten = models.FileField(upload_to='documents/') developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) Now, if the user clicks the link Click here to see the …