Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In a multi vendor Django Rest API, how do I restrict customers/buyers to only make order(s) from one vendor at a time?
Here are my simplified models This is my custom user model, email is used instead of a username class CustomUser(AbstractUser): id = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True ) email = models.EmailField( _('email address'), unique=True, blank=False ) ... Product App This app is used by sellers to post their products class Product(TimeStampedModel): id = models.UUIDField( default=uuid_lib.uuid4, editable=False, primary_key=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, auto_created=True, related_name='products' ) title = models.CharField( _("Title"), max_length=200 ) category = models.ForeignKey( Category, on_delete=models.CASCADE ) ... Cart App contains two models cart and cart item model class Cart(TimeStampedModel): ... user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name="cart", on_delete=models.CASCADE ) ... class CartItem(TimeStampedModel): ... cart = models.ForeignKey( Cart, related_name="items", on_delete=models.CASCADE, null=True, blank=True ) product = models.ForeignKey( Product, related_name="cart_product", on_delete=models.CASCADE, ) seller = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="cart_seller", on_delete=models.CASCADE, null=True, blank=True ) ... class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ( 'email', ) class CartProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( ... 'user', ... ) class CartSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) items = serializers.StringRelatedField(many=True) class Meta: model = Cart fields = ( 'id', 'user', 'created', 'updated', 'items', ) class CartItemSerializer(serializers.ModelSerializer): product = serializers.StringRelatedField(read_only=True) cart = serializers.StringRelatedField(read_only=False) seller = serializers.StringRelatedField(read_only=False) class Meta: model = CartItem fields = ( 'id', 'cart', 'cart_id', 'product', 'product_id', … -
Compare Django-HTML form input with the elements in a list
I have a list of usernames and I want to compare the form input with the elements of the list. Suppose I have a list, say, listA = ["abc", "def", "ghi"] and the HTML form, <form action="#" class="signin-form"> <div class="form-group mb-3"> <label class="label" for="name">Username</label> <input type="text" class="form-control" placeholder="Username required> </div> <div class="form-group"> <button type="submit" class="form-control btn btn-primary submit">Sign In</button> </div> I want to compare the input from the elements in the list. -
I want to run my else statement in (views.py) but when server is run it automatically go to the if statement?
#views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid: forms.save() print("If statement") return redirect(reverse('home')) else: print("else statement") return render(request,'file/addQuestion.html') def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) #forms.py from django.forms import ModelForm from .models import Question from django.core.exceptions import ValidationError class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" def clean_answer(self): answer = self.cleaned_data['answer'] option1 = self.cleaned_data['option1'] option2 = self.cleaned_data['option2'] option3 = self.cleaned_data['option3'] option4 = self.cleaned_data['option4'] if answer == option1 or answer == option2 or answer == option3 or answer == option4: return answer else: raise ValidationError("Select an answer from the options.") -
Why it doesn't show any data after I add it?
Wokring on a simple To Do application using Django 3.2. In the moment I'm working on one to one relationship which every specific user has his own data(which are the tasks to do in this case) I did that by create a field at models.py user = models.ForeignKey(User, on_delete=CASCADE, null=True) The problem is that when I add a task in the home template it doesn't show up. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class user_active(models.Model): content = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) user = models.ForeignKey(User, on_delete=CASCADE, null=True) def __str__(self): return self.content forms.py from django import forms from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import user_active class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] home.html <div> <form class="felx" action="add_content/" method="POST"> {% csrf_token %} <input class="form-control me-2" type="text" name="content" placeholder="Hey"> <button id="add-btn" class="button" type="submit">Add</button> </form> <table> <thead> {% for all_item in all_items %} <tr> <td>{{ all_item.content }}</td> </tr> {% endfor %} </thead> </table> <a href="{% url 'demo1:login' %}">Logout</a> {% if request.user.is_authenticated %} <p>Hello {{request.user}}</p> {% endif %} … -
Django order by count by date
Good morning! I have tried many things but can't get to order my post by likes and by date. For example, I wish to have a "popular post" page, which contains only posts from today, but order by most liked. Here are my models: Class Post(models.Model): name = models.CharField(max_length=40, default=None, null=False) cover = models.CharField(max_length=100, default=None, null=True, blank=True) content = models.TextField(max_length=2000, default=None, null=False) class VoteDate(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField(default=timezone.now) The closest I came but did not work is this line: hot_today = Post.objects.annotate(count=Count('votedate', filter=Q(votedate__date=datetime.today()))).order_by('count')[:30] Thank you for your help! -
Django social share fb link with 500 internal error header [closed]
I've installed django-social-share and added a social share button to fb. How can the text of the shared link be customized? Right not it is showing Server Error 500 although when you click on the link it actually works fine. I cant seem to find the answer to this problem in the library documentation. The goal is that in stead of "Server Error (500)" there would be the header of the page and a favicon like you'd normally see in shared pages In my template I have added this template tag for the social share {% post_to_facebook "Random text" %} -
Can I specify a custom default value to be used when migrating after adding a new parent class in a Django model?
I am writing a Django app that provides a very simple model called Submittable, which users of the app are supposed to inherit from when they want to use other functionalities of the app. # app1 class Submittable(models.Model): is_submitted = models.BooleanField(default=False) # other methods here # app2 class Paper(Submittable): # some fields However, when I add this as a parent to an already existing model in another app and run makemigrations, I am asked to provide a default value to the new field submittable_ptr_id. The problem is, that I want this field to simply point to a new instance of Submittable but I don't know how to do that. I know, that I could simply edit the migration file created like so: class Migration(migrations.Migration): dependencies = [ # some dependencies ] operations = [ migrations.AddField( model_name='Paper', name='submittable_ptr_id', # here I set default to a function from the Submittable app that just creates a new submittable field=models.OneToOneField(auto_created=True, default=app1.utils.create_submittable, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key =True, serialize=False, to='app1.Submittable'), preserve_default=False ), ] But I want to know if I can specify anything somewhere in app1 that makes this happen automatically? I don't want users of the app to have to make this change themselves and instead, … -
File read issue using python
I am trying to read file(text),used readlines() function but not getting in format like bold,headings,italics in the read file -
Read some products Data from a csv file using python in command line
i have a csv file which have information about all the products so i want to perform some basic functions like You have to show data based on user selection. User will select filters he wants to apply (he can select multiple fields). Also user can select the fields he wants to see like he can select full item or he wants to see only price of item or he wants to see some specific fields as am new to it so kindly help to learn. I have read python basics like its Datastructure , loops, file system Here is the sample Data -
TypeError: Object of type ImageFieldFile is not JSON serializable - django
I'm trying to make post via ajax request and JsonResponse but when i try to upload image to the form and submit it raise this error from server side : TypeError: Object of type ImageFieldFile is not JSON serializable and this error from client side (in the console browser) Uncaught TypeError: Illegal invocation and here is my models.py and my views.py @login_required def create_modelcategory(request): form = ModelCategoryForm() if request.is_ajax() and request.method == 'POST': form = ModelCategoryForm(request.POST,request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.save() data = { 'id':obj.id, 'admin':obj.admin.username, 'category':obj.category.category, 'model':obj.model, 'giga':obj.giga.giga_byte, 'img':obj.image.url, } return JsonResponse({'success':True,'data':data},status=200) else: return JsonResponse({'sucess':False,'error_msg':form.errors},status=400) context = { 'form':form } return render(request,'storage/modelcategory.html',context) and here is my html and jquery-ajax functions is there something i've missed to add ? or if its not right way to save image data into database via ajax and jsonresponse please let me know . I much appreciate your helps .. -
localization bootstrap-Table not displaying as wanted
Im using the following code: Based on the browser language i change up the locale Even if the browser fex is en-US its get defaulted to dutch <script src="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.js"></script> <script src="{% static 'js/bootstrap-table-nl-BE.js'%}"></script> <script src="{% static 'js/bootstrap-table-fr-BE.js'%}"></script> <script> $(document).ready(function() { var userLang = navigator.language || navigator.userLanguage; if (userLang == "fr" || userLang == "fr-FR" || userLang == "fr-BE") { language = "fr-BE" } else { language = "nl-BE" } $("#table").bootstrapTable({ locale : language, }) } ) </script> But even when the browser is in en-US it keeps displaying in French. -
Redirecting after a XMLHttpRequest
I'm drawing on a canvas and then I upload the drawing to a database (Django). I have made this work by creating a Blob and sending a Form with XMLHttpRequest. But once uploaded, how do I navigate to the page that shows this new file? I would like the server to send a redirect, but that doesn't work and apparently that's not how you should do it. But how otherwise? Here's the Javascript: function submitFunction() { canvas = document.getElementById('myCanvas'); var dataURL = canvas.toDataURL("image/jpeg"); form = document.getElementById('myForm'); formData = new FormData(form); blob = dataURItoBlob(dataURL); url = window.location.href; xhr = new XMLHttpRequest(); xhr.open('POST', url, true); formData.set('artwork_img', blob, 'artwork.jpeg'); xhr.send(formData); } And here's the Django View: def create (request, id): artwork = get_object_or_404(Artwork, pk=id) context = {'artwork' : artwork} if request.method == 'POST': form = ArtworkForm2(request.POST, request.FILES) if form.is_valid(): newChild = Artwork() newChild.parent = artwork newChild.artwork_img = form.cleaned_data['artwork_img'] newChild.artwork_title = form.cleaned_data['artwork_title'] newChild.ancestors = artwork.ancestors+1 newChild.save() newChild.updateAncestors() # ---> this is kind of what I'd like to do: return redirect('showwork', newChild.id) else: print(form.errors) else: form = ArtworkForm2() context.update({'form' : form}) return render(request, 'exp/create.html', context) -
Why my 127.0.0.1/800 is not connecting to Django admin database even after migrate 001 initial.py
as I am new to Django. I create a project named as trackback in which I create an app named as projects after successfully creating superuser to my Django admin and migrate my 0001 initial.py database is not connecting. I register my model name inadmin.py too. -
Django - Adding meta table for dynamic table
I would like to create a dynamic table as Person. The extra information depends on user's requirements as key-value. So, I'm looking what is the correct way to do this operation. My codes are: class Person(models.Model): age = models.CharField(..) name = models.CharField(..) class PersonMeta(models.Model): value = models.CharField(max_length=255) key = models.CharField(max_length=255) person = models.ForeignKey(Person, on_delete=models.CASCADE) with this way it works but is this correct way to do that? -
Errors getting started with django-eav2
I'm trying to make a simple app for users to create multiple choice tests for each other, where they can specify which data type should apply to the answer for each question. To this end, I'm trying to get django-eav2 working, following this guide. However, I run into errors as soon as I try to makemigrations. Using eav.register: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) class Answer(models.Model): question = models.ManyToManyField(Question) import eav eav.register(Answer) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get "django.db.utils.OperationalError: no such table: eav_attribute" Using decorators: from django.db import models from django.utils.translation import ugettext as _ from eav.models import Attribute from eav.decorators import register_eav #Dynamic user-specified data types is tricky, see # https://stackoverflow.com/questions/7933596/django-dynamic-model-fields class Question(models.Model): class DataType(models.TextChoices): TEXT = 'TXT', _('Text') INTEGER = 'INT', _('Integer (whole number)') FLOAT = 'FLT', _('Float (number with fractional parts, e.g. 3.14159)') question_text = models.CharField(max_length=400) question_type = models.CharField(max_length=3, choices=DataType.choices, default=DataType.TEXT) @register_eav class Answer(models.Model): question = models.ManyToManyField(Question) Attribute.objects.create(slug='txt_value', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(slug='int_value', datatype=Attribute.TYPE_INT) Attribute.objects.create(slug='flt_value', datatype=Attribute.TYPE_FLOAT) I get … -
After any bug in Django html i get same exception: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128)
Exception inside application: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) File "/venv/lib/python3.6/site-packages/channels/http.py", line 213, in __call__ await self.handle(body) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 150, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 333, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 55, in run result = self.fn(*self.args, **self.kwargs) File "/venv/lib/python3.6/site-packages/asgiref/sync.py", line 169, in thread_handler return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/channels/http.py", line 246, in handle response = self.get_response(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 94, in technical_500_response html = reporter.get_traceback_html() File "/venv/lib/python3.6/site-packages/django/views/debug.py", line 332, in get_traceback_html t = DEBUG_ENGINE.from_string(fh.read()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128) Always get the same exception when i get error in html files (include django admin). Project haven't any cyrillic symbols, only latin. -
Save some fields from one model to another.When i create News I want the title,mainphoto,created and gallery_news fields were saved in the Photo model
When i create News I want the title,mainphoto,created and gallery news fields were saved in the Photo model. I tried to do it by save method in serializers.py, but it did not work.Can someone help me with this problem models.py class News(models.Model): title = models.TextField(blank=True, verbose_name='Название') mainphoto = ThumbnailerImageField(upload_to='images/', null=True, verbose_name='Фото', help_text='Размер фотографии должен быть 1200x550') created = models.DateField(verbose_name='Дата создания') class Meta: verbose_name = 'Новость' verbose_name_plural = 'Новости' ordering = ('-created',) def __str__(self): return str(self.title) class Gallery(models.Model): image = models.ImageField(blank=True, null=True, upload_to='gallery/', verbose_name='Галерея') gallery_news = models.ForeignKey(News, related_name='gallery', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Галерея') class Meta: verbose_name = 'Галерея новостей' verbose_name_plural = 'Галерея новостей' def __str__(self): return str(self.gallery_news) class Photo(models.Model): title = models.CharField(max_length=155, verbose_name='Название') preview = models.ImageField(upload_to='images', null=True, verbose_name='Превью') created = models.DateField(default=timezone.now, verbose_name='Дата мероприятия') class Meta: verbose_name = 'Фото галерею' verbose_name_plural = 'Фото галерея' def __str__(self): return self.title class PhotoGallery(models.Model): image = models.ImageField(blank=True, null=True, upload_to='images/', verbose_name='Галерея') photo_gallery = models.ForeignKey(Photo, related_name='gallery', on_delete=models.CASCADE, null=True, blank=True, verbose_name='Галерея') class Meta: verbose_name = 'Фото галерею' verbose_name_plural = 'Фото галерея' def __str__(self): return str(self.photo_gallery) News.title=Photo.title News.created=Photo.created News.mainphoto=Photo.mainphoto Gallery.gallery_news=PhotoGallery.photo_gallery My serializers.py class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields = ('__all__') class PhotoGallerySerializer(serializers.ModelSerializer): class Meta: model = PhotoGallery fields = '__all__' class NewsSerializer(serializers.ModelSerializer): gallery = GallerySerializer(many=True, read_only=True) created = serializers.DateField(format='%Y-%m-%-d', … -
foreign key problem in postgres' logical replication in django
I configured postgres logical replication between several DBs in my django project to replicate common data like django_content_types, comments etc. from primary db to peripheral DBs. There is no master or slave DBs though, because data from peripheral DBs is also replicated in primary DB. I call it primary because I have some basic data in it. And I use django-viewflow application, so instances of viewflow app are read from primary db. But I have models inherited from django-viewflow's models and they are read from perpheral DBs. The system is like as below: class Process(models.Model): # django-viewflow model, read from primary class SomeProcess(Process): # inherited model, read and written into another DB Also there is a model called Task, that has a foreign key to process and a self-referencing field called "previous" and there is a table called viewflow_task_previous, that has task_ids like this: class Task(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE, verbose_name=_('Process')) previous = models.ManyToManyField('self', symmetrical=False, related_name='leading', verbose_name=_('Previous')) Naturally I use django routers. So the problem is that when task object is created in peripheral DB it is replicated to primary, but viewflow_task_previous table is only read from primary db, so sometimes task data is not in time to replicate to … -
sending data from PLC to a web server http://localhost:8080
Please help!! I have a Programmable Logic Controller (PLC) which can work on ethernet to communicate to other devices over TCP/IP protocol. Now my question is: "Is it possible to receive data into the web server from external device like PLC?? Also, is it possible for the web server to send data over TCP/IP protocol to other controller devices (PLC in this case) ??" Please help me out. This ques has been haunting me since many days. -
Missing required flag in Heroku and Django
I am using Heroku to deploy my simple Django app. But when I try to create the secret command, it gives me an error. The steps are from real python -
Django: help in implementing error reporting
I am trying to implement an error reporting system that directly sends the errors to slack. The steps are like this: My API fails and return a 400 error. The Middleware will check if the response code equals 400 Call the function to send the error message to slack. API: class SomeWorkingAPI(APIView): permission_classes = (AllowAny,) def get(self, request): client = request.query_params.get('client', None) try: #do something except: error_msg = "error occurred in the API" return Response({'message': error_msg}, status=status.HTTP_400_BAD_REQUEST) return Response(result, status=status.HTTP_200_OK) Middleware: def error_reporting(request, error_msg=None): # this is the function that sends the message to my slack channel return 'error reported successfully' class SomeMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_template_response(self, request, response): if response.status_code >= 400: error_reporting(request, error_msg=response['message']) The help I need: I want to send the error message returned from the API (return Response({'message': error_msg}, status=status.HTTP_400_BAD_REQUEST)) to the middleware. How can i achieve that? What i'm doing in middleware (response['message']), is throwing KeyError. Since the middleware has both request and response, it would be great if I can get all the query params and payload from the request. When I'm using request.query_params in the error_reporting function, I'm getting AttributeError: 'WSGIRequest' … -
Hide the (obvious) relation from nested serializer in DRF
Django + rest framework. This seems like it should be a frequent and common issue, but I could not find anything like it, so here I ask: I have a Document and its Items: class DocumentSerializer(ModelSerializer): ... items = ItemsSerializer(many=True, required=False) class Meta: model = Document exclude = () class ItemsSerializer(Serializer): ... class Meta: model = DocumentItem exclude = ('document', ) # hide the ForeignKey as it should be obvious by nesting Expected result for JSON serialized data something like: { "id": 1, "date": "2021-01-01T00:00:00Z", "title": "Test doc", "items": [ {"code": 43, quantity: 3}, {"code": 28, quantity: 15} ] } It should be fairly obvious that the "document" field from ItemsSerializer should be derived from the parent serializer at the time of storage. The field itself being a ForeignKey to Document, of course. However, I can't get past the ValidationError({"document":["This field is required."]}). If I say the field is not required, then save()complains AssertionError: The '.create()' method does not support writable nested fields by default. What is the accepted way of handling relations like this in serializers? -
Why is Exception Value: cursor "_django_curs_140539182187712_sync_1" error generated in Django?
I am getting the below error on Herokuapp site, while the local version of my Django app works just fine. Any help or guidance would be appreciated. (Also, the site was not being recognized earlier, and had to add SITE_ID=1 to my settings.py file) Exception Value: cursor "_django_curs_140539182187712_sync_1" InvalidCursorName at /admin/home/influencers/add/ cursor "_django_curs_140539182187712_sync_1" does not exist Request Method: GET Request URL: http://www.[mysite].com/admin/home/influencers/add/ Django Version: 3.1.13 Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140539182187712_sync_1" does not exist Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py, line 1159, in execute_sql Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/rathee', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '/app/.heroku/python/lib/python3.9/site-packages/odf', '.']``` The error can be viewed here – http://www.manishrathee.com/Article. Many thanks! -
How to know which domain is running? [closed]
I have two servers running only one celery at a time, and I need to know which server is running when running cron classes.Is there any way to find it? -
how to upload image to django and nextJs using formidable
I'm new to NextJs and I have no idea what I'm doing. I tried to upload an image from Postman it worked, but when I tried to use NextJs (send data to /api and then send data to the backend it didn't work), then I tried to use formidable, but I found no answer how to upload the image to Django from NextJs with formidable(I should send it at first to/api because i should send the token too).