Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when creating todoapp AttributeError: module 'typing' has no attribute 'NoReturn' when installing django
when entering virtual environment and trying to install django error occurs: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\user\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\user\Envs\test\Scripts\pip.exe_main.py", line 4, in File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\main.py", line 9, in from pip._internal.cli.autocompletion import autocomplete File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\autocompletion.py", line 10, in from pip._internal.cli.main_parser import create_main_parser File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\cmdoptions.py", line 23, in from pip._internal.cli.parser import ConfigOptionParser File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\parser.py", line 12, in from pip._internal.configuration import Configuration, ConfigurationError File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\configuration.py", line 27, in from pip.internal.utils.misc import ensure_dir, enum File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\utils\misc.py", line 38, in from pip.vendor.tenacity import retry, stop_after_delay, wait_fixed File "C:\Users\user\Envs\test\lib\site-packages\pip_vendor\tenacity_init.py", line 186, in class RetryError(Exception): File "C:\Users\user\Envs\test\lib\site-packages\pip_vendor\tenacity_init.py", line 193, in RetryError def reraise(self) -> t.NoReturn: AttributeError: module 'typing' has no attribute 'NoReturn' -
Cannot return MVT from Postgis 2.5
I have been trying to make the Postgis extension work with MVT data. I have been reading this article and I have done everything it says (I think) and it still does not work. Old setup Before attempting to support MVT data, we are using Mapnik with Django and we are returning PNG images. Current setup I'm building the following SQL query (using the code in the article) (bounds are dynamically calculated based on the z,x,y values) WITH bounds AS ( SELECT ST_Segmentize(ST_MakeEnvelope(0.0, -40075016.68557839, 20037508.3427892, -20037508.3427892, 3857), 5009377.0856973) AS geom, ST_Segmentize(ST_MakeEnvelope(0.0, -40075016.68557839, 20037508.3427892, -20037508.3427892, 3857), 5009377.0856973)::box2d AS b2d ), mvtgeom AS ( SELECT ST_AsMVTGeom(ST_Transform(t.geom, 3857), bounds.b2d) AS geom, original_address FROM records_addressvalue t, bounds WHERE ST_Intersects(t.geom, ST_Transform(bounds.geom, 3857)) ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom Once I have the query, I run it as follows: from django.db import connection cursor = connection.cursor() cursor.execute(sql) But the problem that it does not return anything! (yes, I have made sure that there points in that range, I have checked this with the old implementation, that it's working). The model I'm querying is this one: from django.contrib.gis.db import models class Address(models.Model): location = models.PointField(blank=True, null=True) # for vectors geom = models.PointField(srid=3857, blank=True, null=True) # for tile server … -
Accessing Images in media/ folder In Django
I'm currently learning about how images are stored in Django. To my understanding, Django stores all the images you upload in in a subdirectory of your site's media/ folder. My question is, let's say I create a website to upload images, where each image corresponds to a unique title (I will define this in my models.py file), like this: from django.db import models # Create your models here. class Post(models.Model): objects = models.Manager() title = models.CharField(max_length=100) cover = models.ImageField(upload_to='images/') def __str__(self): return self.title Then, given the unique title of an image, how can I find the image in the media/ folder that corresponds to it? Are there any websites/sections in the Django documentation that explain this? I've tried searching for some, but haven't been able to find any. Thanks in advance! -
Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance
Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance. File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\santosh\Desktop\desktop\New folder\quizApp\app\views.py", line 153, in LessonSumary Lesson = LessonSummary.objects.create( File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 451, in create obj = self.model(**kwargs) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance. [06/Sep/2021 20:24:07] "POST /createlesson HTTP/1.1" 500 85350 def LessonSumary(request): if request.method == "POST": title = request.POST["title"] content = request.POST["content"] subject = request.POST["subject"] Lesson = LessonSummary.objects.create( Title=title, content=content, subject=subject, user=request.user, ) Lesson.save() context = {"subjects": Subject.objects.all()} return render(request, "Main/lessonSummary.html", context) Models class Subject(models.Model): name = models.CharField(max_length=250, null=True, blank=True) def __str__(self): return self.name class LessonSummary(models.Model): Title = models.CharField(max_length=250) content = models.TextField() subject = models.ForeignKey( Subject, on_delete=models.CASCADE, null=True, blank=True ) user = models.ForeignKey(User, on_delete=models.CASCADE) -
how to render html code which is render from model in template as html
i am creating a blog project for leaarning django right now i am wondering is it possible to write html code in model.textfield and when fetching it in my template it render as html code whole code as paragraph let me exlain you with example i have model class Movie(models.Model): title = models.CharField(max_length=100, blank=False) urltitle = models.SlugField(max_length=100, blank=False, unique=True) info = models.TextField(blank=False,default=None) title_image = models.ImageField(upload_to='movies',blank=False, null=True) image_one = models.ImageField(upload_to='movies',blank=True, null=True) image_two = models.ImageField(upload_to='movies',blank=True, null=True) para_one = models.TextField(blank=True) written_by = models.CharField(max_length=50, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) created = models.DateTimeField(auto_now=True) as you can see in this model I have a text field name para one if I write code in that like Hello World and save it then my template while rendering it it render hello world with h1 heading instead of like this Hello World as paragraph i hope you got it or the or is there any way to do it or with any other field -
postgres showing authentication failed when given correct password
Ok, so I have installed Postgres Database with zeal, and during installation, i was prompted for a password which i entered, now when I try to start psql shell it gives me below mentioned error, but when i start Pgadmin it logs me in fine, No Clue here! Authentication error in CMD psql: error: FATAL: password authentication failed for user "atifs" Now i am trying to push my local Db to Heroku during this process i am asked for a password, and this error again, which password is it asking, because I clearly remember the password and i have given only one that too at the installation, i am close to being frustrated, need help, Thanks in advance Heroku error heroku pg:push postgres DATABASE_URL -a immense-anchorage-56196 » Warning: heroku update available from 7.53.0 to 7.59.0. heroku-cli: Pushing postgres ---> postgresql-opaque-17681 Password: pg_dump: error: connection to database "postgres" failed: FATAL: password authentication failed for user "atifs" pg_restore: error: could not read from input file: end of file ! pg_dump errored with 1 -
Django - How to use django-filters(module) with crispy-forms renderning
I'm new and still learning, I would appreciate your help on this matter. I created a listview, a grid, objects from my db and all. I now want to create a filter bar to select/seek for specific values in my object list by filtering them + have it in crispy. I downloaded both "pip install django-filter (2.4.0)" and django-crispy (forms). I already use crispy to customise forms(mostly Modelforms); I created a search bar that seems to work but the overall design isn't good and I have to make it in bootstrap. For this reason I try to bootstrapify the filter form with crispy, but it doesn't work and a)renders the standard django form; b)error. Doesn't seem to accept crispy. For this reason: Is it possible to do it? Or those modules are not compatible? If yes, what is the best practice to do so? If not, what should I do instead? **HTML** {% extends 'base/base1.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <h3>Log List</h3> <a class="btn btn-outline-info " href="{% url 'home' %}">Back to homepage</a> <hr> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> ****{{ myFilter.form}}**** */tried also {{ myFilter.form|crispy}} {{ myFilter.form.variablefieldhere|as_crispy_field}}** <button class="btn … -
how to filter field values based on other field id of same model in Django
Here i want to filter the all the items of each group let us consider my model as class ItemsList(models.Model): invoice_number = models.IntegerField(blank=True, null=True) class ItemsInvoice(models.Model): items = models.ForeignKey(ItemsList) class StockItems(models.Model): item_invoice = models.ForeignKey(ItemsInvoice, blank=True, null=True) group_id = models.IntegerField(blank=True, null=True) For example let us consider my database values as: item_invoice | group_id 2206 | 1 2207 | 1 2208 | 2 2209 | 3 2210 | 4 2211 | 4 2212 | 4 2213 | 5 Now how can i write my filter statement based on group_id filter item_invoice and based on this item_invoice id's filter the items and based on these items ids filter invoice_number -
How to get google token for oauth2 django?
I'm trying to implement registration via the Django REST Framework Social OAuth2 did everything as in the documentation, but when I try to get an access_token, I get errors either {"error": "access_denied", "error_description": "Your credentials aren't allowed" }, if I manually specify the client_id and secret, but I don't have the google_token itself, tell me how to get it correctly and where? Here is the request itself for getting the token from the documentation: curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token -
how to setup supervisor file to read gunicorn socket
I have the following ubuntu folder structure using django test_app | |__ __ backend / | | wsgi.py | | __ __ settings.py | | |__ __ manage.py | |__ __ env / | |__ __ bin / | |__ __ gunicorn as i am trying to setup supervisor with django, nginx and gunicorn: cd /etc/supervisor/conf.d/ sudo touch gunicorn.conf sudo nano gunicorn.conf then the configuration [program:gunicorn] directory=/home/ubuntu/test_app command=/home/ubuntu/test_app/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/test_app/app.sock backend/wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn i saved and closed the file then sudo supervisorctl reread sudo supervisorctl update now when i check the status of supervisor sudo supervisorctl status i get the following error: guni:gunicorn BACKOFF Exited too quickly (process log may have details) then i checked the logs sudo cat /var/log/gunicorn/gunicorn.err.log File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'backend/wsgi' I am not sure what i am doing wrong here... the path seem correct to me Is there anything that i am missing? -
How to properly design my models for likes?
The requirement is simple. Logged in users can like post and the likes increases by 1. Here I think below models fulfill the requirement but I want the best database design possible. Or there might be other best options also. class Post(models.Model): title = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL) OR class Like(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) -
Solving the view didn't return an HttpResponse object. It returned None instead
I am getting the error below Request Method: POST Request URL: http://127.0.0.1:8000/orders/place_order/ Django Version: 3.1 Exception Type: ValueError Exception Value: The view orders.views.place_order didn't return an HttpResponse object. It returned None instead. if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): print('we are here checking if the form is valid') data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax =tax data.ip = request.META.get('REMOTE_ADDR') data.save() return redirect('checkout') else: return redirect('checkout') This is a snippet of my views.py file -
how to manage messages for invalidate fields of model and invalidate recaptcha?
i have a form page in django project I want the reCaptcha-google validation error message to be different from the validation error fields of the model fields in webpage.html(template). How can I manage the error message in the view or form? translate by translate.google.com ! im sorry :) thank you views.py def home(request): comment_form = myform() if request.method == 'POST': comment_form = myform(data=request.POST) if comment_form.is_valid(): comment_form.save() messages.success(request, 'okkk') else: messages.error(request, 'error') newmyform = myform() context = { 'my': newmyform, } return render(request, 'home.html', context) forms.py from django import forms from captcha.fields import CaptchaField from .models import mymodel class myform(forms.Form): class Meta: captcha = CaptchaField() fields = ['name', ] model = mymodel -
What is the best way to handle uploaded images in Django Rest Framework on production server and how to do it?
I'm relatively new to DRF, and I'm facing a problem where I have to set up many (thousands) of profile images. I need to do it "properly", so I guess uploading raw photos to the server is not the best way to do it. What service/ approach should I use? -
Django forms inheritance doesn't read value from field
I have 2 similars forms so I decide to inherite one form from another and it looks like: class EditModuleForm(forms.Form): category_name = forms.CharField(label='Name', max_length=100) image = forms.ImageField(label='Icon', required=False) def clean_image(self): image = self.cleaned_data.get('image', None) if image: check_image_size(image) class NewCategoryForm(EditModuleForm): category_slug = forms.CharField(label="Slug", max_length=10) field_order = ['category_name', 'category_slug', 'image'] def clean_image(self): super(NewCategoryForm, self).clean_image() and during using NewCategoryForm image is not validated and value is None. Looks like this form can't get value from image field. Could somebody give me a hint what I'm doing wrong? -
Change name when saving multiple files in Django
I am trying to save multiple images at the same time: class Image(models.Model): image = models.ImageField() date = models.DateField(default=now) origin = models.ForeignKey(OriginModel) class ImageCreateView(CreateView): origin_model = None folder_name = 'temp' def form_valid(self, form): self.object = form.save(commit=False) origin_id = self.kwargs['pk'] origin = self.origin_model.objects.get(id=origin_id) date = self.object.date files = self.request.FILES.getlist('image') for f in files: image = f image.name = 'img/{0}/{1}/{2}'.format( self.folder_name, origin_id, f.name) self.model.objects.create(origin=origin, image=image, date=date) return redirect(self.get_redirect_url()) But when it saves the images, it saves them with original name f.name. I understand why it does that, but how do I pass the formatted name to the create method? -
Questions about JavaScript [closed]
I want to become a full stack web dev. I have completed HTML & CSS. Now I want to learn JS. I want to work backend with Python Django. So how much JS I need to learn for only front end? #newbie -
Django query param get stripped if there is (+) sign
Whenever I try to to get my query string parameter everything works but only + sign gets stripped. Here is url file: urlpatterns = [ re_path(r'^forecast/(?P<city>[\w|\W]+)/$', weather_service_api_views.getCurrentWeather)] Here is view File: @api_view(['GET']) def getCurrentWeather(request, city): at = request.GET["at"] print(at) return JsonResponse({"status": "ok"}, status=200) So if I hit the server with this URL: http://192.168.0.5:8282/forecast/Bangladesh/?at=2018-10-14T14:34:40+0100 the output of at is like this: 2018-10-14T14:34:40 0100 Always + sign gets stripped. No other characters get stripped. I have used characters like !, = , - etc. -
Annotating a queryset using ba
Django annotations are really awesome. However I can't figure out how to deal with annotations where several values() are required. Question: I would like to annotate an author_queryset with counts of items in a related m2m. I don't know if I need to use a Subquery or not, however: annotated_queryset = author_queryset.annotate(genre_counts=Subquery(genre_counts)) Returns: SyntaxError: subquery must return only one column I've tried casting the values to a JSONField to get it back in one field, hoping that I could use JSONBagg on it since I'm using postgres and need to filter the result. But that doesn't seem to work. There's some great info here about filtering on these. There's also something for postgres coming soon in the development version called ArraySubQuery() which looks to address this. However, I can't use this feature until it's in a stable release. Desired result I would like to annotate so I could filter based on the annotations, like this: annotated_queryset.filter(genre_counts__scifi__gte=5) Detail I can use dunders to get at a related field, then count like so: # get all the authors with Virginia in their name author_queryset = Author.objects.filter(name__icontains='Virginia') author_queryset.count() # returns: 21 # aggregate the book counts by genre in the Book m2m model … -
How to get value from input and send it as json object to backend in vue 3
I have a questionnaire which shows questions and their answers with vuejs. django will handle the backend. I want to get the question id and answer from the questionnaire and send it to backend as json object. here is my question component: <template> <div> <div v-for="section in sections.slice(sectionStart, sectionEnd)" :key="section.id"> <div v-for="question in section.questions" :key="question.id"> <!-- Single Choice --> <div v-show="question.type === 'Single Choice'" :id="question.id"> <p class="py-4 font-medium leading-8">{{ question.question_text }}</p> <input type="hidden" :value="question.question_text" v-model="question.id"> <div class="flex py-1" v-for="choice in question.choices" :key="choice.id"> <input class="h-5 w-5" type="radio" :name="question.id" v-model="choice.id" :id="choice.id"/> <label class="ml-3" :for="choice.id">{{ choice.text }}</label> </div> </div> <!-- Multiple choice --> <div v-show="question.type === 'Multiple Choice'" :id="question.id"> <p class="py-4 font-medium leading-8">{{ question.question_text }}</p> <div class="flex py-1" v-for="choice in question.choices" :key="choice.id"> <input type="checkbox" class="h-6 w-6" :name="choice.id" :id="choice.id"> <label :for="choice.id" class="ml-3">{{ choice.text }}</label> </div> </div> </div> </div> </div> </template> <script> export default { data() { return { sections: data.sections, } }, props:[ 'sectionStart', 'sectionEnd' ] }; </script> How can I get question id and it's answer and save these value to json object and then send it to backend? -
how to implement sorting in django site
I have a shopping site and I want implement sorting products in my site I know how order_by works but I don't know how to pass arguments through url to check it I use class base view (ListView) my view: class ProductList(ListView): template_name = 'products/store.html' paginate_by = 8 def get_queryset(self): return Product.objects.get_active_products() I use dropdown (with tag a) for finding witch order user want to sort -
Instantiating Models in Django sqlite database
Is there a way to instantiate Django models from what a user enters into a form For example, I want my users to create new settings for different financials. Where they would click a button that will add a couple of models to the database with the settings that they create (this would, in turn, need to create a URL, view, and HTML template's for this model) Example User clicks add set of financials ---> They select a company that the financials would be for --> This, in turn, creates a page called (company name + ' settings') ---> in this settings tab they would have many different settings for multiple financial reports (trial balance, monthly statements, age analysis, etc.) -
How to call multiple functions with one field in django?
I got two function that are calling same file that user have uploaded, but only first function is executed. How do I make to call both functions? I'm not preforming same things on same file, it is impossible to do this all in one function, I have to do it with multiple functions. Any ideas? This is views.py def mmy_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #padnas code qoutput.to_excel(writer, sheet_name=name) html = qoutput.to_html() writer.save() output.seek(0) return render(request, 'list.html', {'table': html}) else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def mmmy_view(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('mmmy-view') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form} return render(request, 'list.html', context) -
I am getting these error a lot in django running on my ubuntu pc
Though i stop the all server still i am getting these error enter image description here -
Django Find Hashtags in String and Replace It by Wrapping It in <a> Tag
The title is kinda long and might be confusing so let me explain. I am making a social media site, and I want to enable hashtags. For example, if a user creates a post like this: Summer is gone. #sad #comeback #summer I want to use python to replace all occurrences of # and word like this: Summer is gone. <a href="http://127.0.0.1:8000/c/sad">#sad</a> <a href="http://127.0.0.1:8000/c/comeback">#comeback</a> <a href="http://127.0.0.1:8000/c/summer">#summer</a> This is what I have so far: def clean_content(self): content = self.cleaned_data.get('content') content = profanity.censor(content) # (Unrelated Code) arr = re.findall(r"@(\w+)", content) replace_ar = [] for hsh in arr: if len(hsh) < 80: if Category.objects.filter(name__iexact=hsh): # Old Category, Added This To Category List (Unrelated Code) replace_ar.append(hsh) else: # New Category, Created Category, Then Added This To Category List (Unrelated Code) replace_ar.append(hsh) else: # Don't do anything, hashtag length too long # No Idea What To Do With replace_ar. Need help here. In the code above I take the html text input and I find all #{{word}}. I then loop through them and I check if a category exists with that name or not. If it does, I just add it to that category, and if it doesn't, I create a category and then add …