Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decoding error when uploading file from Flutter frontend to Django backend
I would like to upload an image from flutter frontend to a python (django) server. I've been trying to debug this for longer than I'd like to admit. There are no resources online which show how to handle uploading a file from Flutter to Django backend. The backend is receiving the file, but I'm getting a UTF-8 decoding error when the file is being saved to local storage. This is the specific error I get when I try to upload an image: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. This is the file information as it is received by the backend: {'file': <_io.BytesIO object at 0x7fe121a44f50>, '_name': 'tempProfilePic.jpg', 'size': 311489, 'content_type': 'application/octet-stream', 'charset': None, 'content_type_extra': {}, 'field_name': 'file'} Below is my frontend code: if (_imageFile != null) { var stream = http.ByteStream(DelegatingStream.typed(_imageFile.openRead())); var length = await _imageFile.length(); var multipartFile = http.MultipartFile('file', stream, length, filename: basename(_imageFile.path)); request.files.add(multipartFile); } request.fields['token'] = token var response = await request.send(); _imageFile is a File variable which contains a .png image saved in storage. The file is sent without any error. Below is my backend code: models.py class userData(models.Model): profilePic = models.FileField(upload_to='documents/') token = models.CharField() And the view element which … -
i used the virtualenv venv command after installing django in my desired folder faced an error how to resolve this
D:\django>virtualenv venv Using base prefix'c:\users\admin\programs\python\python37' New python executable in D:\django\venv\Scripts\python.exe ERROR:the executable D:\django\venv\Scripts\python.exe is not functioning it tells the program cant start bcz VCRUNTIME140.dll is missing from my computer how do i reinstall and fix this problem -
django doesn't work with mongoengine, restframwork
i'm developing django restframework webpage using mongodb. I used sample source link from https://leadwithoutatitle.wordpress.com/2018/03/21/how-to-setup-django-django-rest-framework-mongo/ and this source worked well in my office django env. but when I run this source in my home, I doesn't work with this error enter image description here my settings.py part DATABASES = { 'default': { 'ENGINE': '', } } from mongoengine import connect MONGO_DATABASE_NAME = 'djangoDB' MONGO_HOST = '127.0.0.1' MONGO_PORT = 27017 connect(MONGO_DATABASE_NAME, host=MONGO_HOST, port=MONGO_PORT) and my pc django env. is like below. mongodb 4.2.0(win 64) python 3.7.3(64bit) Django 2.2.3 django-rest-framework-mongoengine 3.4.0 djangorestframework 3.10.3 mongoengine 0.18.2 -
Django can't find the static files
I just started a new project and currently Django can't find the static files. I'm using Django==2.2.6 The static files are located in an app called "website". This is the file structure. https://i.imgur.com/AnPACop.png This is from the settings: STATIC_URL = '/static/' -
How can I access to request.header in post_delete of models.signals
In post_delete of models.signals, I want send a request to other server to notify about this action, but I have a problem when I try to get some info from request.headers(ex: clientId send from client), please help me about this problem Thank you. -
class has no 'objects' member
so im new in django and im trying to make a small market. i made a product app. this is the inside codes: this is for views.py: from django.shortcuts import render from django.http import HttpResponse from products.models import product def index(request): Products = product.objects.all() return render(request, 'index.html', {'products': Products}) def new(request): return HttpResponse('New Product') this is for models.py: from django.db import models class product(models.Model): name = models.CharField(max_length=150) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) i also made a template folder and put this in it for experiment: <h1>Products</h1> <ul> {% for product in Products %} <li>{{ product.name }}</li> {% endfor %} </ul> and some other usual codes. but i get a error for this part: product.objects.all() please help me! thanks -
what does "verbose_name", "verbose_name_plural" , "index_together" do?
I am exploring a github project , but could understand what "verbose_name", "verbose_name_plural" , "index_together" doing? class Meta: verbose_name = "Payable To Person" verbose_name_plural = "Payable To Persons" index_together = ["organization", "status"], -
invalid: Syntax of transaction amount is incorrect. Should contain digits up to two decimal points
views.py 'MID': 'kdwQnP13817196283144', 'ORDER_ID': str(order.id), 'TXN_AMOUNT': str(Order.get_total_cost), 'CUST_ID': (order.email), 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL':'http://127.0.0.1:8000/payment/handleRequest/', models.py class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) get_total_cost = models.DecimalField(max_digits=10, decimal_places=2) phone = models.CharField(max_length=10, default="") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) https://www.facebook.com/photo.php?fbid=526521448115167&set=a.526521514781827&type=3&theater -
JS: alert input value from programatically generated input classes
I'm using Django as Backend. In my template I'm generating input fields for each item, and for now I'm just trying to alert the values in this fields when user clicks a link: Agregar al Carrito. Right now, it only works for only 1 of the three items. This is somehow illogic, as the logic is the same for all the items. It should work for all or for none, but not for some yes and not for others. Codepen: https://codepen.io/ogonzales/pen/YzzzYdd Code: <div class="container-fluid mt-3"> <div class="row justify-content-center"> {% for unitary_product in object_list %} <div class="col-auto mb-3"> <div class="card" style="width: 18rem;"> <a class="btn" data-toggle="modal" href="#FullImage{{ unitary_product.slug }}"> <img class="card-img-top" src="{{ unitary_product.image.url }}" alt="Card image cap" width="100" height="200"> </a> <div class="card-body"> <h5 class="card-title">{{ unitary_product.name }}</h5> <p class="card-text">Tamaño: {{ unitary_product.size }}</p> <p class="card-text"><b>Precio: S/ {{ unitary_product.price }}</b></p> <label for="tentacles"><b>Cantidad: </b></label> <input type="number" class="unitary_product_quantity_for_{{ unitary_product.slug }}" name="unitary_product_quantity_for_{{ unitary_product.slug }}" value="{{ unitary_product.quantity }}"> <a class="margin-top10 btn btn-azul text-white btn-block agregar-unitary-product-btn-for-{{ unitary_product.slug }}">Agregar al carrito</a> </div> <div class="card-footer"> <small class="text-muted">Creado el: {{ unitary_product.created }}</small> </div> </div> <!-- ### AJAX TO SEND QUANTITY --> <script> function get_unitary_product_quantity_for_{{ unitary_product.slug }}() { var unitary_product_quantity_for_{{ unitary_product.slug }} = $('.unitary_product_quantity_for_{{ unitary_product.slug }}').val(); alert(unitary_product_quantity_for_{{ unitary_product.slug }}); return unitary_product_quantity_for_{{ unitary_product.slug }}; // … -
how to make a django virtual environment using cmd or powershell?
As you can see the terminal in pycharm easily lays the foundation for creating a django project. but in powershell(cmd either) I see this.... so how should i run the command to make it work in powershell or cmd either ? is there any other way to make me able (not to be confined in pycharm terminal) to do the same with powershell and cmd ? -
How to get to another page after saving form by CreateView
I wan't to get to order_list page after adding new order. Was trying both reverse and reverse_lazy method also just to set page adres value to success_url directly like success_url = 'orders/order_list' or sucess url = 'order_list' but it always returns me Http 405 error. views.py django.shortcuts import render from django.urls import reverse_lazy from django.views import View from django.views.generic import ListView, DetailView, CreateView from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin from .models import Order from .forms import CreateOrder from django.contrib.auth.decorators import login_required # Create your views here. class OrderCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): login_url = '/login_required' permission_required = 'orders.add-order' model = Order success_url = reverse_lazy('orders:order_list') fields = ['airport', 'direction', 'adress', 'client', 'telephone', 'flight_number', 'plane', 'pick_up', 'gate', 'driver'] urls.py from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from orders.views import OrderCreateView, OrderListView, AboutView, LoginRequiredView urlpatterns = [ path('admin/', admin.site.urls), path('add_order/', OrderCreateView.as_view(template_name="orders/add_order.html"), name="add_order"), path('order_list/', OrderListView.as_view(), name="order_list"), path('login/', auth_views.LoginView.as_view(template_name="pages/login.html"), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name="pages/logout.html"), name="logout"), path('about/', AboutView.as_view(), name="about"), path('login_required/', LoginRequiredView.as_view(), name='login_required') ] add_order.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="container" style="width: 40%; height: 80%;"> <div class="page header"> <h1>Add new order</h1> </div> <form action="/order_list/" method="post"> {% csrf_token %} … -
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: m
You have 8 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): myapp3. Run 'python manage.py migrate' to apply them. class STUDENTMARKSHEETDATA(models.Model): username=models.CharField(max_length=100,unique=True) dof=models.DateTimeField(max_length=100) reg_no=models.IntegerField() graph_theory=models.CharField(max_length=100) autometa_theory=models.CharField(max_length=100) data_mining=models.CharField(max_length=100) dsp=models.CharField(max_length=100) networking=models.CharField(max_length=100) computer_graphics=models.CharField(max_length=100) grade_S=models.CharField(max_length=100) grade_A=models.CharField(max_length=100) grade_B=models.CharField(max_length=100) grade_C=models.CharField(max_length=100) grade_D=models.CharField(max_length=100) grade_E=models.CharField(max_length=100) grade_U=models.CharField(max_length=100) code_962=models.IntegerField() code_302=models.IntegerField() code_303=models.IntegerField() code_903=models.IntegerField() code_301=models.IntegerField() code_304=models.IntegerField() branch_cse=models.CharField(max_length=100,default='00000') # gender=models.CharField(max_length=100) # degree=models.CharField(max_length=100, unique='aaaaa') def str(self): return self.username -
Connect to local mysql database from django app docker
I'm trying to dockerize my Django app with Docker, but having some trouble connecting with the mysql database since i'm not really experienced with Docker. I have a couple questions: I have installed mysql and set up the database locally on my computer, do i have to use a mysql image and create a db service in my docker-compose too ? Shouldn't Django connect to mysql normally like it did when it wasn't dockerized ? If a database is hosted on a server then is mysql installed on that server ? Do i have to use a mysql image to connect to the database ? Here is my docker-compose.yml: version: '3.7' services: web: build: ./appchat command: python appchat/manage.py runserver ports: - 8000:8000 - "3306" network_mode: "host" And here is the database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'root', 'NAME': 'company', 'PORT': '3306', } } Here is the error when i ran docker-compose file: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Any help would be appreciated. Thank you. -
What's the best way to mock a Django User?
I'm trying to instantiate a User instance through a Mock. That mock instance is being passed to another model Profile where I'm checking for any validation errors when a cleaning method is called. However I'm getting: AttributeError: Mock object has no attribute '_state' There is this previous post: How to mock users and requests in django. Nevertheless, I want to avoid any database calls. What can be done differently so that a Mock will in this case? #models.py class Profile(models.Model): hobby = "Hobbyist" develop = "Developer" coding_level = ( (hobby, hobby), (develop, develop) ) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) birth = models.DateField(verbose_name="Date Of Birth") coding_level = models.CharField( verbose_name="Experience", max_length=20, choices=coding_level, default=hobby, blank=False ) bio = models.TextField( verbose_name="User Bio", validators=[MinValueValidator(10)] ) github = models.URLField( verbose_name="GitHub link", validators=[check_submitted_link], unique=True ) avatar = models.ImageField(upload_to="images/%Y/%m/%d/") #test_models.py class TestProfile__001(SimpleTestCase): def setUp(self): self.test_user = Mock( spec=User, username="test_username", email="test@email.com" ) self.profile_data = { 'user': self.test_user, 'birth': '2019-10-07', 'coding_level': 'hobby', 'bio': "", 'github': "http://www.test.com", 'avatar': "image.txt" } def test_create_profile_fail(self): with self.assertRaises(ValidationError): test_profile = Profile(**self.profile_data) test_profile.clean_fields() -
RuntimeError: Conflicting 'product_product_options' models in application 'catalogue': on Oscar 2
I am using Django==2.2.6 And django-oscar==2.0.2. Trying to custom the Oscar models but every its not working... The error is .. File "/home/dipto/env/oscar/lib/python3.6/site-packages/django/db/models/base.py", line 316, in new new_class._meta.apps.register_model(new_class._meta.app_label, new_class) File "/home/dipto/env/oscar/lib/python3.6/site-packages/django/apps/registry.py", line 229, in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'product_product_options' models in application 'catalogue': and . Following this.... Created a App with the name of "catalogue" Added it as Django app to INSTALLED_APPS Added a models.py and admin.py In catalogue app models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): Test_URL = models.URLField() from oscar.apps.catalogue.models import * In catalogue app init.py default_app_config = 'catalogue.apps.CatalogueConfig' In catalogue app apps.py from django.apps import AppConfig class CatalogueConfig(AppConfig): name = 'catalogue' label= 'shop mane' -
How to override custom model clean method if a modelform does not include some fields of the model?
I have this model: class Exam(Model): student = OneToOneField(Student, on_delete=CASCADE) has_taken_exam = BooleanField(default=False,) score = FloatField(choices=SCORE_CHOICES, null=True, blank=True, exam_date = DateField(null=True, blank=True, ) non_empty_fields = \ { 'score': 'please enter your score', 'exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_taken_exam: for field_name, field_error in self.non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) and have this modelform class ExamForm(ModelForm): class Meta: model = Exam exclude = ('student', 'exam_date', ) when I submit this form in template, I get the below error: ValueError at / 'ExamForm' has no field named 'exam_date'. and During handling of the above exception ({'score': ['please enter your score'], 'exam_date': ['please specify your exam date']}), another exception occurred: The error happens in my view where I am validating the form. My database logic is such that I need to have an exam_date field and it should be mandatory to fill if has_taken_exam is checked. However, in ExamForm, for business reasons, I do not need the exam_date. How can I tell ExamForm to turn a blind eye to the exam_date, as I am not saving the modelform instance? -
ImportError: cannot import name 'views' from '__main__' in django
i am new at webdev i make simple webapp but trying from one day. but this issue not solved my urls.py file enter code here from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home') enter code here (test) C:\Users\abc\projects\amar>C:/Users/abc/envs/test/Scripts/python.exe c:/Users/abc/projects/amar/f1/urls.py Traceback (most recent call last): File "c:/Users/abc/projects/amar/f1/urls.py", line 3, in <module> from . import views ImportError: cannot import name 'views' from '__main__' (c:/Users/abc/projects/amar/f1/urls.py) in views.py- enter code here from django.shortcuts import render home(request): return render(request,'home.html') enter code here and in settings.py template i also mention path- enter code here 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], -
JSONField show specific field in template
i have a Rank class and it has a JSONField field and example value is {"Playoff": 10, "Tournament": 15} models.py class Rank(models.Model): ... json=JSONField(default=dict) class Game(models.Model): ... status=models.ForeignKey(Status...) now i want to show exact matching field's value so for example, game.gamestatus.name is Tournament and i want to show json.Tournament value like {{ t.json.{{game.status.name}} }} (that's wrong i know) How can i do ? what should you suggest to me -
How to iterate through the newly selected objects in a ManyToManyField in the save method of a model?
I know that there's no way I'm the first to ask this question, but I cannot find the answer so please don't eat me. If I have a model with a field that is a ManyToManyField; I know that I can get the selected objects prior to the save but this isn't helpful if the selected objects have changed. models.py class AddOn(models.Model): name = models.CharField(max_length=100) class Invoice(models.Model): additional_options = models.ManyToManyField(AddOn) def save(self, *args, **kwargs): # this prints the objects that were selected prior to the save. # this isn't helpful if the selected objects have changed. print(self.additional_options.all()) Is there a better way to do this than using the post_save signal? -
Django not sending correct json response
I have set up a simple project and when a post request is made, it is expected to return a response depending on what value the user entered. I am testing my api logic in postman. At the moment, no matter what value I enter, the same json response is sent back. This is not the expected logic. views.py: def function(request): if request.method == 'POST': if request.POST.get("number") == 1: print("Number is 1") return JsonResponse({'message':'Number is 1'}) else: print("Number is not 1") return JsonResponse({'message':'Number is not 1'}) Even if the value of number is equal to 1, the message: Number is not 1, is returned. Thank You. -
Where my media files goes? Django + Heroku + MySQL
First of all, I have no idea what I should do here. I think I viewed all things about this problem. I have builded Django app with MySQL as DB (ClearDB MySQL heroku addon), and deployed it to heroku. Site works fine until I want add some items in DB. I have library-like app, so, it contains not only text, but images too. Uploading comes from admin panel and creates in media root folder with book name. (see my github repo bellow for more info). All CSS and JS files works great, but idk where my images goes. I think i missded something about what happend with media when you deploy Django app to heroku. GitHub -
Mixing of insert queries on threads in django
Have developed a django site in which some scraping code is running. I noticed a problem that when two scraping code run parallel (in different threads), the insert queries to django orm model are getting mixed up e.g in one thread if i have a value of a=1,b=1 and in the other i have the value of a=2,b=2 the value saved in the database is sometimes (1 out of 1000 and gets worse when threads increase) a=1,b=2. Have checked the values before being sent to the model.save() method, the values are fine but get distorted after that. I am using django 2.2 and for integrating mongodb have used djongo. Also to support elasticsearch index i am using django elasticsearch dsl. Dont know on which step the query is getting distorted. Also on each thread, asynchronous threading is being used. A sample of my script is : from project.views import start_new_thread @start_new_thread def site(site,loop): try: import pytz from urllib import parse from bs4 import BeautifulSoup import re from project.models import thread,post from datetime import datetime from .sentiment_analysis import calculate_sentiment import aiohttp import asyncio import async_timeout href=[] tthread=[] link=set() author={} async def fetch(session, url): async with async_timeout.timeout(30): async with session.get(url) as response: … -
Page not found (404) in django 2
I'm working in my blog project for learning the django But my urls doesn't work correctly when i create post my post created successfully and save in my database and I can see my post card in my blog But when I click the post card for show detials of post getting this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/post/2019/10/5/testing-urls-design/ Raised by: Blog.views.post this is part of my models for blog app : models.py class Post(models.Model): image = models.ImageField(upload_to='Posts_image') title = models.CharField(max_length=256) slug = models.SlugField(max_length=256,null=True,blank=True) content = HTMLField('Content') date = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField(category) tags = TaggableManager() publish = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): kwargs = { 'year':self.date.year, 'month':self.date.month, 'day':self.date.day, 'slug':self.slug, } return reverse('blog:post-detail', kwargs=kwargs) This part for create slug in models.py def create_slug(instance, new_slug=None): slug = slugify(instance.title, allow_unicode=True) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(slug_generator, sender=Post) after this part you see my views.py def post(request, year, month,day, slug): post = get_object_or_404(Post, date__year=year, date__month=month, date__day=day, slug=slug) comment_form = CommentForm(request.POST or None) new_comment = … -
ForeignKey to abstract model
I have an abstract Product model, and I wanted it to be able to hold more than one image, so I decided to make another Image model and have a ForeignKey to Product, however I quickly realised that's not possible. The reason I decided to go for abstract base model is performance gains since every child model is in its own table. Having a different Image model for each subclass sounds bad to me, since there will be more than 20 subclasses. class Product(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False) class Meta: abstract = True class Book(Product): author = models.CharField(max_length=50) publisher = models.CharField(max_length=50) class Shoes(Product): colour = models.CharField(max_length=50) size = models.CharField(max_length=50) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to=get_image_path, blank=True, null=True) How can I overcome the issue? -
Django REST Framework: error when testing POST request with list
I have a test view: @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) def test_view(request): return Response(request.data) It is registered in urls.py: urlpatterns = [ path('api/test/', test_view) ] When I try to POST [{"a": 1}, {"a": 2}] manually through the REST Frameworks UI, everything works fine. However, if I write a test for it, an unexpected error occurs. Here is the test from rest_framework.test import APITestCase class ViewTest(APITestCase): def test_it(self): response = self.client.post('/api/test/', [{"a": 1}, {"a": 2}]) print(response) which produces the following error: Traceback (most recent call last): File "C:\development\HeedView\backend\clients\api\tests.py", line 13, in test_it response = self.client.post('/api/test/', [{"a":1}, {"a": 2}]) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 300, in post path, data=data, format=format, content_type=content_type, **extra) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 212, in post data, content_type = self._encode_data(data, format, content_type) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 184, in _encode_data ret = renderer.render(data) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\renderers.py", line 921, in render return encode_multipart(self.BOUNDARY, data) File "C:\development\HeedView\venv\lib\site-packages\django\test\client.py", line 194, in encode_multipart for (key, value) in data.items(): AttributeError: 'list' object has no attribute 'items' How to explain this behavior?