Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels in docker compose error `not found: /ws/`?
When I access ws://domain.com/ws/ from my machine it runs just fine but when I try to access it from docker- compose upI got that error not found: /ws/ I tried to change host configuration in channels layers in the settings but nothing changed also i tried to change refis and Channels versions -
Django, sending email
I'm trying to make a feedback form on my site. my settings.py DEFAULT_FROM_EMAIL = '****@****.**' EMAIL_HOST = '*****' EMAIL_PORT = 465 EMAIL_HOST_USER = DEFAULT_FROM_EMAIL EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' my form is simple and I don't thing that mistake is in that file, but I think I should show it my forms.py: class SuggestionForm(forms.Form): email = forms.EmailField(label='', initial='Ваш Email', required=True) subject = forms.CharField(label='', initial='Тема вашего сообщения', required=True) message = forms.CharField(label='', initial='Сообщение для администрации сайта', widget=forms.Textarea, required=True) and my views.py def suggestion_view(request): if request.method == 'GET': form = SuggestionForm() elif request.method == 'POST': form = SuggestionForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] mess = form.cleaned_data['message'] try: send_mail(subject=f'{subject} от {email}', message=mess, from_email=DEFAULT_FROM_EMAIL, recipient_list=['saw.danil@yandex.ru'], fail_silently=False, auth_user=DEFAULT_FROM_EMAIL, auth_password=EMAIL_HOST_PASSWORD) except BadHeaderError: return HttpResponse('Ошибка в теме письма') return redirect('success') else: return HttpResponse('Неверный запрос') return render(request, 'main/suggestion.html', {'form': form}) I have no idea why this is not working and I'll be grateful for any help. -
Working with formulas in Django using Javascript
I am getting the formula from a csv file. Suppose, the formula is score = x * 5 + y. Now I'm getting x and y value from the user. Any idea how should i proceed? I want to calculate the score. I'm using Django framework and want to calculate the score using JS. -
How to split a menu within a wagtail model?
I'm trying to create a navigation menu, that when the number of objects within the menu is even puts an image between the two halves of the menu. Here is the code that I tried to use within my menu model and templates to create the effect. """Splitting the menu in half for the frontend.""" @property def is_even(self): if (self.objects.count() % 2) == 0: return True else: return False @property def find_halves(self): first_half = self.objects[0:self.objects.count()/2] second_half = self.objects[self.objects.count()/2:self.objects.count()] return first_half, second_half <nav class="main-nav"> {% image navigation.logo fill-115x115 as logo %} <ul class="nav-links"> {% if navigation.is_even %} {% for item in navigation.menu_items.first_half.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> {% for item in navigation.menu_items.second_half.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} {% else %} <img src="{{ logo.url }}" alt="CCCR Logo" class="logo"> {% for item in navigation.menu_items.all %} <li><a href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a></li> {% endfor %} {% endif %} </ul> </nav> However, when I run the code it goes to the else statement even … -
How to inject HTML code with static file reference to Django template
I have a simple use case in which I need to dynamically add rows to a table in my HTML template. I am using the following javascript code to add this on a button click: function add_row(){ row_html = '<tr><td><img src="path/to/my/file.png"></td></tr>' $('#table-id').append(row_html); } The only problem is that the image is not being found. I have also tried using Django template language, doesn't work. One solution is defining the src in the script tag in my HTML template like in this question. However I am not sure this is the optimal approach. What is the correct approach to solve this problem? -
No module named 'asgiref.base_layer'
When starting my server (python manage.py run server) I get the following error. File "/Users/thomasallen/PycharmProjects/Channels_and_Signals/venv/lib/python3.9/site-packages/asgi_redis/core.py", line 19, in from asgiref.base_layer import BaseChannelLayer ModuleNotFoundError: No module named 'asgiref.base_layer' The offending line 19 in .../core.py is from asgiref.base_layer import BaseChannelLayer The packages I have installed are: Django 3.2.4 channels 3.0.3 channels-redid 3.2.0 aspired 3.3.4 asgi-redis 1.1.0 I'm not sure where the mismatch is. -
UpdateView not filling datalists html input and other fields
please i need you help. I have an UpdateView wich update every field correctly except that field that are filled via "datalist" html5, like "cliente", "fecha" and "isin". the question is, ¿how can i fill that information like the others fields?.what do i am doing wrong? Could you give me some guide about that? thanks in advance! views.py class ordenes_updatea_orden(UpdateView): model = rfi_tsox form_class = IngresoOrdenesRFIModelForm template_name = template_name = 'ordenes/rfi-ingreso-ordenes-modelform.html' success_url = reverse_lazy('listado_ordenes') Modelform class IngresoOrdenesRFIModelForm(ModelForm): def __init__(self,*args, **kwargs): super(IngresoOrdenesRFIModelForm,self).__init__(*args, **kwargs) self.fields['fecha_ingreso'].widget.attrs = {'class':'form-control','type':'date'} self.fields['orden_tipo'].widget.attrs = {'class':'form-control'} self.fields['nominales'].widget.attrs = {'class':'form-control'} self.fields['precio'].widget.attrs = {'class':'form-control'} self.fields['papel'].widget.attrs = {'class':'form-control'} self.fields['rating'].widget.attrs = {'class':'form-control'} self.fields['duracion'].widget.attrs = {'class':'form-control'} self.fields['payment_rank'].widget.attrs = {'class':'form-control'} self.fields['ytm'].widget.attrs = {'class':'form-control'} self.fields['sector'].widget.attrs = {'class':'form-control'} self.fields['notas'].widget.attrs = {'class':'form-control'} self.fields['pais'].widget.attrs = {'class':'form-control'} self.fields['sector'].widget.attrs = {'class':'form-control'} self.fields['cliente'].widget.attrs = {'class':'form-control'} cliente = forms.ChoiceField(choices = [(x.fondo,x.fondo) for x in clientes_rfi.objects.all()]) fecha_ingreso = forms.DateField(widget=forms.DateInput(attrs={'class':'form-control','type':'date'}),initial = datetime.date.today) orden_tipo = forms.ChoiceField(choices = [('cliente compra','cliente compra'),('cliente vende','cliente vende')]) isin = forms.ChoiceField(choices=listado_isin(),required=False) papel = forms.CharField(required=False) rating = forms.MultipleChoiceField(choices = [('Todos','Todos'),('IG','IG'),('HY','HY')],initial='Todos',required=False) duracion = forms.MultipleChoiceField(choices=[('Toda la curva','Toda la curva'),('x<=3','x<=3'),('3<x<=5','3<x<=5'),('x>5','x>5')],initial='Toda la curva',required=False) nominales = forms.CharField(required=False) sector = forms.MultipleChoiceField(choices=lista_sector(),initial='Todos',required=False) precio = forms.CharField(required=False) payment_rank = forms.MultipleChoiceField(choices=lista_paymentRank(),initial='Todos',required=False) ytm = forms.MultipleChoiceField(choices=[('Todos','Todos'),('0 a 100','0 a 100'),('101 a 200','101 a 200'),('201 a 300','201 a 300'),('301 a 400','301 a 400'),('sobre 400','sobre 400')],initial='Todos',required=False) … -
Error when hiding django secret_key in miniconda environment
I'm a total newbie and I'm trying to do this project this is my first time, and it's almost done. I tried every method mentioned in this SO thread to move secret key from settings. In every method i got some kind of error, even from this official django doc mathod. I couldn't find where I'm making mistake. When the secret key is inside the settings.py, everything is working super smooth. But I need to push my code in git, so i have to hide it from settings.py. Right now im adding the details when i tried using django-environ, to keep secret key outside of settings.py. im putting the contents inside the root project folder. im using miniconda: 4.10.1. here is my requirement.txt. # platform: linux-64 _libgcc_mutex=0.1=main _openmp_mutex=4.5=1_gnu appdirs=1.4.4=py_0 asgiref=3.3.4=pyhd3eb1b0_0 attrs=21.2.0=pyhd3eb1b0_0 black=19.10b0=py_0 ca-certificates=2021.5.30=ha878542_0 certifi=2021.5.30=py39hf3d152e_0 click=8.0.1=pyhd3eb1b0_0 django=3.2.4=pyhd3eb1b0_0 django-environ=0.4.5=py_1 importlib-metadata=3.10.0=py39h06a4308_0 krb5=1.17.1=h173b8e3_0 ld_impl_linux-64=2.35.1=h7274673_9 libedit=3.1.20210216=h27cfd23_1 libffi=3.3=he6710b0_2 libgcc-ng=9.3.0=h5101ec6_17 libgomp=9.3.0=h5101ec6_17 libpq=12.2=h20c2e04_0 libstdcxx-ng=9.3.0=hd4cf53a_17 mypy_extensions=0.4.1=py39h06a4308_0 ncurses=6.2=he6710b0_1 openssl=1.1.1k=h7f98852_0 pathspec=0.7.0=py_0 pip=21.1.2=py39h06a4308_0 psycopg2=2.8.6=py39h3c74f83_1 python=3.9.5=h12debd9_4 python_abi=3.9=1_cp39 pytz=2021.1=pyhd3eb1b0_0 readline=8.1=h27cfd23_0 regex=2021.4.4=py39h27cfd23_0 setuptools=52.0.0=py39h06a4308_0 six=1.16.0=pyh6c4a22f_0 sqlite=3.35.4=hdfb4753_0 sqlparse=0.4.1=py_0 tk=8.6.10=hbc83047_0 toml=0.10.2=pyhd3eb1b0_0 typed-ast=1.4.2=py39h27cfd23_1 typing_extensions=3.7.4.3=pyha847dfd_0 tzdata=2020f=h52ac0ba_0 wheel=0.36.2=pyhd3eb1b0_0 xz=5.2.5=h7b6447c_0 zipp=3.4.1=pyhd3eb1b0_0 zlib=1.2.11=h7b6447c_3 settings.py import os import environ from pathlib import Path env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # Build paths inside the … -
Custom, user-definable "wildcard" constants in SQL database search -- possible?
My client is making database searches using a django webapp that I've written. The query sends a regex search to the database and outputs the results. Because the regex searches can be pretty long and unintuitive, the client has asked for certain custom "wildcards" to be created for the regex searches. For example. Ω := [^aeiou] (all non-vowels) etc. This could be achieved with a simple permanent string substitution in the query, something like query = query.replace("Ω", "[^aeiou]") for all the elements in the substitution list. This seems like it should be safe, but I'm not really sure. He has also asked that it be possible for the user to define custom wildcards for their searches on the fly. So that there would be some other input box where a user could define ∫ := some other regex And to store them you might create a model class RegexWildcard(models.Model): symbol = ... replacement = ... I'm personally a bit wary of this, because it does not seem to add a whole lot of functionality, but does seem to add a lot of complexity and potential problems to the code. Clients can now write their queries to a db. Can they … -
'SafeString' object has no attribute 'get'
I want to render string to a template and I think I misunderstand something. Here is my code : context = { 'order': order, 'ordered_items': ordered_items, 'change': change, } return render_to_string('order/receipt.html', context) And I use them like this: <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: {{ order.code }} </span> <br> <br> <span>Order time: {{ order.created }}</span> <br> <br> <span>Cashier: {{ order.waiter }}</span> <br> <span>---------------------------------------</span> <div class="section4"> <div> <table> <thead> <tr> <th width="110">Product name</th> <th width="80">Unit price</th> <th width="30">Quantity</th> </tr> </thead> <tbody> {% for item in ordered_items %} <tr> <td>{{ item.food.title.tm }}</td> <td>{{ item.food_size.price }}</td> <td>{{ item.quantity }}</td> </tr> {% endfor %} </tbody> </table> </div> <br> <span>---------------------------------------</span> <br> <div class="total"> <span>Total : {{ order.total_cost }}</span> <br><br> <span>Paid : {{ order.paid }} </span> <br><br> <span>Change : {{ change }} </span> </div> <br> <span>---------------------------------------</span> </div> <div class="section5"> <span>Thank you for your patronage! </span> </div> </div> </div> I'm going to use this html template to print a receipt via thermal printer. And also I want to know more about render_to_string method, I read the docs but can't understand well. -
Byte Range Request: Flask vs Django - HTML Video not showing on Iphone
The web server I am using is PythonAnywhere. They do not support byte range requests, so my video is not showing up on the Iphone when using Django. Their recommendation is to go through AWS (Amazon S3), by hosting the videos there (they support byte range requests). I am only looking to serve static video files, and they said that if that is the case, there is a workaround with Flask, so that the video could be hosted by PythonAnywhere and not routed to AWS. It has to do with HTTP 206 (Partial Content) request. My question is, why can Flask do this but Django cannot? Am I missing something? -
How to save an image from my DOM to backend in django?
I am building a web app using django, now one part of it is a small image editor which i created using Fabric.js, in which the user can upload an image(completely js code, not connected with the backend), and do some editing, and upload the resulting image, only thus time, it has to be stored in my MEDIA of django app, i just have no idea how to get the last step done, i.e., how do i get an image which is available only in my DOM(document object model) at that instance and save it to my backend -
how to write svg code to a file and save It in media folder in Django?
I have a function that generates a barcode as svg code. I need to display this svg in an HTML PDF template. but unfortunately inline svg doesn't work. so as a workaround I need to write this code into a file and save it in the media folder so I can access it by tag in the HTML PDF template. Below is the function that generates the barcode: def barcode_number(self): number = self.get_real_instance().number svg_code = generate('code39', str(number).zfill(20), pil=True) code = svg_code.decode("utf-8") ## here I want to write code into barcode.svg file safe_html = mark_safe(svg_code) return safe_html How can I write this code to a svg file and save it in '/media/uploads' ? Thank you -
Unable to update/delete related model in the save() method of a model
I have two Django models: from django.db import models class Policy(models.Model): status = models.IntegerField() def save(self, *args, **kwargs): quote = self.documents.get(document_type=DocumentType.quote) if self.status = "X": quote.delete() elif self.status == "Y": new_quote_content = create_new_quote() quote.s3_file.save(quote.name, File(new_quote_content)) super().save(*args, *kwargs) class Document(models.Model): policy = models.ForeignKey( to=Policy, null=True, blank=True, on_delete=models.CASCADE, related_name="documents", ) s3_file = models.FileField( storage=S3Storage(aws_s3_bucket_name="policy-documents"), upload_to=get_document_s3_key, max_length=255, ) I want to delete/update the document when the policy status is updated and I've overriden the save() method in Policy to do it. However, neither the doc deletion nor the doc's FieldFile update works in the save() method. If I move them to outside the save() method, everything works. Does someone understand what's the issue here? -
Object of type ImageForm is not JSON serializable
I wanted to post image processing from views to celery, but it shows me a JSON-related problem "Object of type ImageForm is not JSON serializable" Here the code from models.py class ImageModel(models.Model): title = models.CharField(max_length=20, null=True) sec_title = models.CharField(max_length=20, null=True) img = models.ImageField(upload_to='upload_p/', blank=False) slug = models.SlugField(max_length=250, null=True) def delete(self, *args, **kwargs): self.img.delete() super().delete(*args, **kwargs) forms.py class ImageForm(forms.ModelForm): class Meta: model = ImageModel fields = ('title', 'img', 'sec_title') views.py def upload_image(request): if request.method == 'POST': form_w = ImageForm(request.POST, request.FILES) if form_w.is_valid(): water_mark.delay(form_w) else: form = ImageForm() return render(request, 'Luki/upload_img.html', { 'form': form, }) tasks.py @shared_task def water_mark(form_w): instance = form_w.save(commit=False) cd = form_w.cleaned_data['img'] if instance.img: im = Image.open(instance.img) width, height = im.size draw = ImageDraw.Draw(im) text = "TEST WATERMARK" font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) # calculate the x,y coordinates of the text margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) thumb_io = BytesIO() print('BYTES IO: ', thumb_io) im.save(thumb_io, im.format, quality=100) instance.img.save(str(cd), ContentFile(thumb_io.getvalue()), save=False) instance.save() return redirect('Luki:gallery') Of course, all the libraries are imported and the code from the views without celera is executed and it looks like this. This works so that the … -
Running sever but throwing an "Exception has occured" eccured. Django python
this server breaks when I enter my login details and this is where the system breaks. -
Unable to deploy Django app to heroku using heroku local
Novice here. Trying to deploy my Django app to Heroku and I get an Unable to connect from the Firefox browser (I tried Chrome as well with similar results). I'm having a lot of trouble troubleshooting where exactly the problem is? Heroku local? Gunicorn? Browser Firewall? Django Settings? What I have done. Added the django_heroku import to settings.py Tried to ensure My browser(Firefox) is not blocking pop-ups etc. Firefox -> settings-> Privacy and security -> permissions-> Uncheck Block pop-up windows Ensured my app works on with just gunicorn I run gunicorn project3.wsgi in my terminal (project3 is the directory for my wsgi file) which works I have the same command in my Procfile, uppercase 'P' (web: gunicorn project3.wsgi). However when I run the command 'heroku local' The browser opens up on clicking the link, but I get an error. Any assistance would be appreciated. I am running commands using windows WSL -
Server Response Time is Much Longer Than Expected
I have an Django application which runs on my localhost currently. Some of the pages take much longer time, so for debugging reasons I calculated the time spend in one of the class based views with this simple code: class DiscoverView(LoginRequiredMixin, ListView): model = MyModel template_name = "app1/discover.html" context_object_name = 'influencers' # not necessary, default is object_list def get_context_data(self, **kwargs): start_time = time.time() # ... # Some tasks which I tought they are the reasons of long response time # ... print(time.time() - start_time, "seconds took to complete...") return context After the experiments I saw that this view takes 0.01 seconds to complete, while the page is loading in nearly ~5 seconds. For further debugging I dig into Chrome Dev Toools. There in network tab 'Finish' time of the page is 5.86 seconds. I also runned Lighthouse test, which says that servers initial response time is ~2 seconds. I can't understand why this 0.01 seconds becomes 2 seconds, I also used django-debug-toolbar in order to inspect database query times, which are not that long. My application is also living on production (Heroku), the loading times are much worse there of course but I feel like I need to fix that … -
Django Postgres - violates foreign key constraint (deleting post with comments)
I just implemented a comment feature into my blog app. The issue I am facing is if I try to delete a blog post that has comments I get the postgres error If I understand this error correctly I cant delete the post because the comment is referencing the post id. To solve this issue I figured I would just add on_delete=models.CASCADE to the model. Unfortunately this did not resolve the issue. I was under the impression that with the CASCADE it would delete the entire model if the FK was deleted. the two models. class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default='default.jpg', upload_to='hero_car_image') aspiration = models.CharField(max_length=55, choices=ASPIRATION) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) manufacture = models.ForeignKey(Manufactures, on_delete=models.CASCADE) model = models.ForeignKey(Models, on_delete=models.CASCADE) class Comment(models.Model): comment = models.TextField() created_on = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) -
Change the score value of all users in a single query to 100 (one hundred)
class CUser(User): score = models.IntegerField() Change the score value of all users in a single query to 100 (one hundred) -
django ContentType select model and instance
I have 3 models in my geometry app: Square_section, T_section, Double_T_section I want to create a model: beam with 2 fields one to select the model in my geometry app and another field to select an instance from a list of all instances of that specific model, will something like this work? : from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class beam (models.Model): slug = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type') def __str__(self): return self.slug -
Django Dictionary/Tuple iteration
I am working on a project for school, and am having a lot of trouble with Templates in Django. My code is below, the first block is Python in a function, bear in mind I removed a lot for easy viewing. amounts = [('None ',), ('1 1/2 oz',), ('1 oz',), ('1/2 oz',), ('1/2 ml ',), ('15 ml',), ('35 ml',), ('splash',), ('6 splashes',), ('10 dashes',), ('25 ml',), ('3 slices',)] data = { 'amounts': amounts, 'ingredients': ingredients, } amount1 = request.GET.get('amount1') print(amount1) return render(request, 'addcocktail.html', {'data': data}) This block is my HTML file: <select name="amount1" id="amount1"> {% for key, value in data.items %} {% if key == 'amounts' %} {% for amount in value %} <option value = {{amount}}> {{ amount.0 }}</option> {% endfor %} {% endif %} {% endfor %} </select> When select 1 oz on the website, amount1 is printed as: 1 which is the first half of the string in the tuple: '1 oz'. I was wondering if anyone knew what the problem here is. -
How can I add additional data to a Django DeleteView POST request?
I'm deleting an item from my template and need to add some extra data, which I tried to do by adding a hidden input field: <form action="{% url 'MyDeleteView' pk=object.id %}"method=POST> {% csrf_token %} <input type="hidden" value="some value"> ... </form> How can I access this hidden input value in MyDeleteView? I tried accessing it in my request.POST but it's not there. def delete(self, request, *args, **kwargs): print(request.POST) # No hidden input value Or is there another way? -
How to create specific view?
models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) students = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py class CreateStudent(LoginRequiredMixin, CreateView): # … def form_valid(self, form): self.object = form.save(commit=False) self.object.save() for student in form.cleaned_data['name']: connect = Connect() connect.student = self.object connect.course = Course.objects.get(name='math') connect.save() return super(ModelFormMixin, self).form_valid(form) How to create view , using this view user must be able to specify which instances of model Course are used for default relation when no relation to Course was chosen by the user. Using this view user must be able to select or unselect some instances of model Course as a default ones. By “default Course“ it is meant that when user creates or some other service creates instance of model Student and saves it to database these default B are used to create matching relations between that instance of Student and these “default” instances of Course. hmp -
Is there any other chances to resolve this issue
Admin Login Error : DJANGO I have created a django super user for admin. I have added AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) in settings.py file but when I enter the same credentials it is showing the below erro: ** django admin showing username and password incorrect.both fields are case insensitive **