Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Searchable Dropdown for many to many field in django model form
How can I Create a Searchable Dropdown for many to many fields in Django model form? I tried using django-searchable-select but this is not available for django 3.0 Can somebody help me ????? -
Create DRF request object programmatically
I'm building a chat application using DRF & Channels. Since sockets are not reliable and as a fall-back, channels themselves recommend to use APIs as a fallback. I've built the APIs, now trying to use the same Views/Viewset to integrate with the socket events too. class InboxViewset(viewsets.ModelViewSet): serializer_class = InboxSerializer queryset = Inbox.objects.all() The idea is my different socket events would be ViewName_Method, for eg:- InboxViewset_list. So, whenever the Django channel consumer instance receives an event with event_type as InboxViewset_list, I would initialize the view and return the same JSON response returned by it. view = InboxViewset() return view.list() Hence following the DRY and reusability principles. Now, for this to happen I would need to create DRF request object. I tried exploring that but could figure it out. This is what I tried. from django.http import HttpRequest from rest_framework.request import Request djrequest = HttpRequest() user = User.objects.first() djrequest.user = user djrequest.query_params = {} djrequest.META['SERVER_NAME'] = '127.0.0.1' djrequest.META['SERVER_PORT'] = '80' request = Request(request=drequest) view = InboxViewset(request=request) view.list(request=request) How can I replicate creating a DRF request programmatically? -
Flutter sending a post request to a Django API with a file as the body
I have a Django API where a user is able to upload a file through a post request with the following body: { "file": *attached file* } In Django, the file is gathered from the request with request.FILES['file'] The request has to be sent from flutter (dart) code. I have tried a few ways, this is the function from my latest attempt which shows an error - because the "file" is not in the correct format. static void uploadProfilePhoto(File file, String fileId) async { Uint8List fileBytes = file.readAsBytesSync(); var response = http.post( globals.baseURL() + "/upload/", //headers: {"Content-Type": "application/json"}, body: { "file":base64Encode(fileBytes) } ).then((v)=>print("v: "+v.body)); } Any idea in what format the "file" should be sent from flutter? Else is there any other method which might work? Thank you in advance. -
Python object response in development is different of production response
I already use a code that call an API request and from nothing this broken my code. I tried to check what happening, my object response does not have a valid json. The instruction that I use is: def get_tickers(self, symbols): """Get tickers.""" data = {"symbols": symbols} return self.session.get("%s/public/ticker" % self.url, params=data).json() This work well until broken for nothing. I use the same Dockerfile in Prod environment and Dev environment to prevent some differences that could be showing In dev (Mac OS) my code still working and returns me this response: [{'symbol': 'ETHBTC', 'ask': '0.034707', 'bid': '0.034705', 'last': '0.034699', 'low': '0.034477', 'high': '0.035257', 'open': '0.035083', 'volume': '89442.2126', 'volumeQuote': '3117.3903987376', 'timestamp': '2020-09-19T16:04:57.968Z'}, {'symbol': 'BTCUSD', 'ask': '11084.95', 'bid': '11084.14', 'last': '11086.54', 'low': '10813.93', 'high': '11177.98', 'open': '10890.52', 'volume': '18086.71200', 'volumeQuote': '198275586.9755433', 'timestamp': '2020-09-19T16:04:58.020Z'}] In Prod this result is not a valid json, I know that single quotes is not a valid json, but, my questions is: Why in dev this working and prod not? I using python 3.8. Same dockerfile, same versions, same code, same base. Anyone already get this error? -
Instead having a base.html in global templates directory , template does not exist error is coming
I am not able to extend base.html inside templates folder in app 'todo'. base.html is present inside templates folder in main directory. -
two problem in config ssh collectstatic and nginx
hello i have two problem one is small the other is large in the ssh project Django 1-collectstatic gives an error 0 static files copied to 'home/name/nameprojects/staticfiles', 162 unmodified, 666 post-processed. 2-i try to disable apache to configure nginx nginx does not want to install correctly -
Trying to print zip column from the database using rest api
Error saying that too many values to unpack (expected 2). models.py @api_view(["GET"]) def zipcodes(request): tasks= ZipCodes.objects.get('zip') if request.method == "GET": serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) -
Django comment replies
I have a problem with implementing replies to comments. models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=False, null=False, max_length=500, verbose_name='Treść') date_of_create = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=True) comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='replies') views.py class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): if request.method == 'POST': new_comment = Comment.objects.create( author = self.request.user, post = self.object, comment = self.request.GET.get('name'), content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) else: return self.form_invalid(form) I think I am close, but I dont know how to indicate id of the comment I want to reply to. I tried something like comment = self.request.GET.get('name') because I tried something like below in form. I have implemented Jsonresponse with ajax and when i try to post reply it gives "comment" : "null" so it doesn't "catch" it. Have you guys any ideas to resolve this? Thanks in advance. <form action="" method="POST" id="commentForm" name="{{ comment.id }}"> {% csrf_token %} {{ form|crispy }} <button type="submit" id="commentBtn">Wyślij</button> </form> -
Is there a way in Django to create a product model where some fields will be created directly in the admin views?
For a school project, I want to create a Django app similar to Woocommerce. What I mean by that is I want the site owner/admin to be able to add his own product attributes. Instead of creating classes for each type of product, I just wanted a simple Product class which would have attributes common to all products such as price and sku and a way for the admin to add custom attributes. I'll give you an example: let's say you just sell T-shirts on your e-commerce shop. It's easy, you create a field "size" with choices "S", "M" or "L" and another field "color" with different color choices. Now, imagine you create an e-commerce Django app which is supposed to work for different kinds of vendors. One will maybe sell cars, another house furniture, who knows? You want the store vendor admins to be able to create their own product attributes. Now you can't create a model with all possible fields like color, manufacturer, horsepower, height, ... because you would have too many fields for one model and you would certainly forget some. I thought I could create 3 classes: Product, ProductAttribute, ProductAttributeValue and play with Foreign and ManyToMany … -
elastic bean stalk, django, and wsgipath
I am finding issue with my WSGIPath in my django elasticbeanstalk deployment. my .ebextensions folder is in root, my django.config file contains the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: shofidecksite.wsgi:application now there are a few things what the code should be where shofidecksite is. I have tried the following: shofidecksite which is the name of the django project shofidecksite again, which is the elasticbeanstalk application name shofi-env which is the environment name I keep getting the error: ERROR Your WSGIPath refers to a file that does not exist. and I am having a very hard time figuring out what it wants from me. Can anyone add some light to this please -
Django AWS Elastic Beanstalk- How to create a cron job
I have deployed my django project on AWS. Now i want to create a cron job to send emails. Almost all the answers on net are somewhat different i no of them seem to be working for me. So please can some tell me a latest and best way to create a cron job. -
How to say Cloudinary to load media files to media/ folder in Django?
My settings: INSTALLED_APPS = [ ... 'cloudinary' ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': '...', 'API_KEY': '...', 'API_SECRET': '...', } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' I looked to the cloudinary cloudinary_storage.storage.MediaCloudinaryStorage class and discovered that it has TAG property which takes value from MEDIA_TAG setting which is by default = 'media'. But anyway all my media files are saved to the root. What should I do to save it to the 'media/' filder? -
Urlpatterns in django are not redirecting(why are responses not diplaying?)
**I created this but when I try to run the server, it only shows the django website, its not a problem in firewall either, I have turned it off ** from django.contrib import admin from django.urls import path from django.http import HttpResponse def home(request): return HttpResponse('home') def contact(request): return HttpResponse('contact') urlpatterns = [ path('admin/', admin.site.urls), path('', home), path('about/', contact), ] **I also added it to apps** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', -
how can i know that email is real email or not using django framework
I built an email sender by using the Django framework but the logic that I built it accepted any email whatever is real email or not !! # Sending Email View def send_email(request): if request.method == 'POST': form = SubscribeForm(request.POST or None, request.FILES or None) if form.is_valid(): message = form.cleaned_data['body'] subject = form.cleaned_data['subject'] recipient_list = request.POST['to_email'] email = EmailMessage(subject, message, EMAIL_HOST_USER, [recipient_list]) email.send(fail_silently=False) messages.success(request, f'email sent to {recipient_list} successfully.') return redirect('/') else: form = SubscribeForm() context = { 'form': form, } return render(request, 'index.html', context) **Settings.py** EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #<<===========================================================================>> EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587'enter code here EMAIL_HOST_USER = 'MyAccount@gmail.com' EMAIL_HOST_PASSWORD = 'MyPassword' EMAIL_USE_TLS = True -
Django ckeditor Image compression to Jpeg and image resize
Hi can anyone suggest me a way, I'm trying to do couple of things i'm using RichTextUploadingField in model, can anyone please help me with this: Compress django ckeditor uploaded image to jpeg to save disk space. For this i found CKEDITOR_FORCE_JPEG_COMPRESSION setting on django-ckeditor github page but it is throwing me error: NameError:name 'CKEDITOR_FORCE_JPEG_COMPRESSION' is not defined I want to set default django ckeditor uploaded image size suppose if i wupload 1000px image it should automatically converted into 600 or 500px without impacting the image quality or if possible image resize option like we do in word drag and resize. Ckeditor settings config: Ckeditor config: CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_FORCE_JPEG_COMPRESSION = True CKEDITOR_CONFIGS = { 'default': { 'width': '100%', 'height': 600, 'contentsCss': 'img {max-width: 100%;height: auto! important;}', 'toolbar': 'Custom', 'toolbar_Custom': [ [ 'Bold', 'Italic', 'Underline' ], [ 'Font', 'FontSize', 'TextColor', 'BGColor', 'Find', 'Replace', '-', 'SpellChecker' ], [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'Table', 'TableTools' ], [ 'Link', 'Unlink' ], [ 'RemoveFormat', 'Source', 'Smiley', 'Image', 'Youtube', 'Preview' ] ], }, } -
Django import export, get() returned more than one
Please help me to find a solution to this error, whene using django-import-export here is my code : Models : class ChartOfAccounts(models.Model): code = models.CharField('code plan comptable', max_length=20, unique=True) name = models.CharField('plan comptable', max_length=100) def __str__(self): return self.code class Company(models.Model): code = models.CharField('code société', max_length=20, unique=True) name = models.CharField('société', max_length=100) addr = models.CharField('adresse', max_length=100, blank=True, null=True) chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable') def __str__(self): return self.code class GLAccount(models.Model): class Meta: unique_together = (('code', 'chart_of_accounts'),) code = models.CharField('code compte comptable', max_length=10) chart_of_accounts = models.ForeignKey(ChartOfAccounts, on_delete=models.CASCADE, verbose_name='code plan comptable') name = models.CharField('compte comptable', max_length=100, help_text='text descriptif du compte comptable') def __str__(self): return f'{self.code}, {self.chart_of_accounts}' class CompanyAccount(models.Model): company = models.ForeignKey(Company, verbose_name='code société', on_delete=models.CASCADE) gl_account = models.ForeignKey(GLAccount, verbose_name='compte comptable', on_delete=models.CASCADE) Resources : class CompanyAccountResource(ModelResource): class Meta: model = models.CompanyAccount fields = ('company', 'gl_account',) exclude = ('id',) import_id_fields = ('company', 'gl_account',) skip_unchanged = False report_skipped = False # fields company = Field( column_name=Meta.model._meta.get_field('company').verbose_name, attribute='company', widget=ForeignKeyWidget(models.Company, field='code') ) gl_account = Field( column_name=Meta.model._meta.get_field('gl_account').verbose_name, attribute='gl_account', widget=ForeignKeyWidget(models.GLAccount, field='code') ) def get_export_order(self): export_fields = ['company', 'gl_account', ] return export_fields My data is : Company model data here ChatOfAccounts model data here GLAccount model data here CompanyAccountResource Excel canvas to import data the problem : a GLAccount code may apear … -
Productpage with Django and bootstrap For loop
I am making a productpage with Django and bootstrap. I am getting stuck when I want to iterate a for loop for multiple items. In my code I begin with {{% for iten in items %}} and end with {{endfor}}, but I need line in between for example elsif or elseend. So: {{% for item in items %}} Item 1 {{some code}} item 2 {{endfor}} <div class="row featured__filter"> {% for item in items %} <div class="col-lg-3 col-md-4 col-sm-6 mix {{ item.get_category_display }}"> <div class="featured__item"> <div class="featured__item__pic set-bg" data-setbg="{% static 'img/featured/dash1.png' %}"> <ul class="featured__item__pic__hover"> <li><a href="#"><i class="fas fa-search"></i></a></li> <li><a href="#"><i class="fa fa-shopping-cart"></i></a></li> </ul> </div> <div class="featured__item__text"> <h6><a href="#">{{item.title}}</a></h6> <h5>${{item.price}}</h5> </div> </div> </div> <div class="col-lg-3 col-md-4 col-sm-6 mix {{ item.get_category_display }}"> <div class="featured__item"> <div class="featured__item__pic set-bg" data-setbg="{% static 'img/featured/dash2.png' %}"> <ul class="featured__item__pic__hover"> <li><a href="#"><i class="fas fa-search"></i></a></li> <li><a href="#"><i class="fa fa-shopping-cart"></i></a></li> </ul> </div> <div class="featured__item__text"> <h6><a href="#">**{{item.title}}**</a></h6> <h5>${{item.price}}</h5> </div> </div> </div>{% endfor %} -
Django csrf_exempt decorator doesn't work
I am using django version 3.1.1 and python 3.8.2 the decorator @csrf_exempt over a view function: #settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #urls.py urlpatterns = [ path('func/', views.func) ] #views.py @csrf_exempt def func(request: HttpRequest) -> JsonResponse: return JsonResponse(dict(success=True)) each time I send a request from javascript to this view: POST func/ I receive Forbidden (CSRF token missing or incorrect.) HTTP/1.1" 403 Thanks -
Get string from TextChoices class in Django
class Foo(models.Model): class Bar(models.TextChoices): CODE_A = 'A', "special code A" CODE_B = 'B', "not so special code B" bar = models.CharField(max_length=1, choices=Bar.choices) The text choices look like tuples but they aren't: print(Foo.Bar.CODE_A[1]) Gives "IndexError: string index out of range". I was expecting to get "special code A". How do I access the code string programmatically from a view, not from within a template and not just the code constant? -
SyntaxError: invalid syntax on lib/python3.8/site-packages/sql_server/pyodbc/base.py django deploy on Linux
** Preface (Testing HyperV Virtual Server with os: Ubuntu Server 20.04.1 on local Windows PC) ** I am having problems deploying my Django app (using Python 3.8.2) on a Ubuntu Server 20.04.1 LTS that uses MS SQL Server as its database. No issues reverting back to 'ENGINE': 'django.db.backends.sqlite3' on Linux but I have to be honest, it is frustrating. I already had to downgrade to Django==3.0 to get my app working on my local windows pc but the 2 migrations I did proves that I am missing something and I hope someone can give me a hand. Any help is appreciated. My PC Working settings.py file (currently running on windows with Sql Server 2019 Express DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'mdm_db', 'USER': 'AAA', 'PASSWORD': 'AAA', 'HOST': 'localhost\\SQLEXPRESS', 'PORT': '', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', # 'driver': 'ODBC Driver 13 for SQL Server ', -> port 1433? }, }, } installed components: pip freeze asgiref==3.2.10 Django==3.0 django-mssql-backend==2.8.1 pyodbc==4.0.30 pytz==2020.1 sql-server.pyodbc==1.0 sqlparse==0.3.1 Ubuntu Server (also tried using ODBC and installing the latest version https://docs.microsoft.com/it-it/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'mdm_db', 'USER': 'mdmuser', 'PASSWORD': 'mdmuser', 'HOST': 'localhost\\SQLEXPRESS', 'PORT': '', 'OPTIONS': { #'driver': 'SQL Server … -
Editing form field __init__
class BotForm(UserForm): def __init__(self, *args, **kwargs): super(BotForm, self).__init__(*args, **kwargs) del self.fields['q2'] Question: How to redefine form fields not by deleting existing ones, but to specify which ones to show only? Any ideas? -
Django filter data of foreign key table and primary key table
I have these two models class Upload(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=50) class Text(models.Model): texts=models.CharField(max_length=500,null=True,blank=True) upload_text=models.ForeignKey(Upload, blank=True, null=True, on_delete = models.CASCADE) What I want is to get texts from Text when I filter name from Upload. So I want name, email and texts displayed. I know this question has been asked previously and I am also doing the same, but getting error. I have tried this data=Text.objects.filter(upload__name__icontains=query) But it give me an error Cannot resolve keyword 'upload' into field. Choices are: id, texts, upload_text, upload_text_id I have also tried this. data=Upload.objects.filter(name__icontains=query) data1=Text.objects.filter(upload_text__in=data) But I am unable to display both at the same time in jinja2 template. {% for q,t in zip(query_key,query_res) %} {{ t.texts }} {{ q.name }} | {{q.email}} -
How Can I render the Hosptal?
How to show the Hospital here? (https://ibb.co/Xkn58yK) blood/models from django.db import models class Patient(models.Model): patient_id = models.CharField(max_length= 1000, null= True) first_name = models.CharField(max_length = 50, null = True) last_name = models.CharField(max_length= 50, null = True) address = models.CharField(max_length=100, null = True, blank=True) phone_number = models.CharField(max_length=50, null= True, blank=True) date_created = models.DateTimeField(auto_now_add = True, null = True, blank=True) hospitals = models.ManyToManyField(Hospital) BLOOD_TYPE = ( ('O+','O+'), ('O-','O-'), ('A+','A+'), ('A-','A-'), ('B+','B+'), ('B-','B-'), ('AB+','AB+'), ('AB-','AB-'), ) patient_blood = models.CharField(max_length=5, null = True , choices=BLOOD_TYPE) def __str__(self): return '{} {} {} {}' .format(self.first_name, self.last_name, "-", self.patient_id) class Hospital(models.Model): hospital = models.CharField(max_length=100, null=True) address = models.CharField(max_length=100, null = True, blank=True) phone_number = models.CharField(max_length=50, null= True, blank=True) def __str__(self): return self.hospital views.py blood/views from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import * def PatientPage(request): patients = Patient.objects.all() hospitals = Hospital.objects.all() context = { 'patients':patients, 'hospitals':hospitals, } return render(request, 'blood/patients.html', context) I can query the rest, only the hospital left {% for id in patients %} <tr> <td>{{id.hospitals}}</td> </tr> {% endfor %} This is the HTML section, I listed the rest, but I can't do the ManyToManyField. The only problem is how can I show the hospital chosen by the patient I am just … -
Multiple blocks in Django
I have a page that shows articles and event dates. I have the code set up for blok content working for the article, but I can't figure out how to make the second block of content appear on the page. These are my models: class NewsLetter(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) class Event(models.Model): name = models.CharField(max_length=100) date = models.CharField(max_length=30) location = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name And this is the code for the second block of content I am trying to show: {% block events %} <div class="w-full bg-white shadow flex flex-col my-4 p-6"> <p class="text-xl font-bold pb-3">Events Calendar</p> <hr> {% for event in object_list %} {{ event.title }} {% endfor %} <a href="#" class="w-full bg-green-600 text-white font-bold text-sm uppercase rounded hover:bg-green-500 flex items-center justify-center px-2 py-3 mt-4"> Sign Up </a> </div> {% endblock %} The solution has to be simple, but I can't see it in the Django docs. Can someone please help. And please remember, the answer to a similar question posted 3 years ago may not work today - so please don't send me to some … -
Django : two users in rating form instance
I got a simple question. I don't understand how I get for rate_form.instance.sugar the sugargroup.seller. As RateSugar is related to Sugargroup I could normally do it. Bu I don't find the answer... Only user (which is consumer) can post the form. That's why I've used self.request.user views.py def form_valide(self, rate_form): if rate_form.is_valid(): rate_form.instance.relationto = self.object ##rate_form.instance.sugar = self.object.seller -> I need to change this to get the SELLER rate_form.instance.user = self.request.user rate_form.save() return super(CheckoutDetail, self).form_valid(rate_form) else: return super(CheckoutDetail, self).form_invalid(rate_form) models.py class Ratesugar(models.Model): relationto = models.OneToOneField(Sugargroup,on_delete=models.CASCADE, blank=True, null=True, related_name="ratesugar_relationto") sugar = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='ratesugar_sugar') user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='ratesugar_cooker') ... class Sugargroup(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_consumer", blank=True, null=True) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sugargroup_seller")