Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify django model form field with widget
I want to modify some fields in model form, and i found two methods: First Method: class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bio'].widget.attrs.update({'placeholder': 'Enter your bio here'}) class Meta: model = Profile fields = ['bio'] Second Method: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['bio'] widgets = { 'bio': Textarea(attrs={'placeholder': 'Enter your bio here'}) I just want to know if they are the same? Which is better? Or is there another better way? Thankyou. -
How can I fix "Command errored out with exit status 1" when installing requirements.txt through pip for a django project?
I'm having trouble installing this requirements.txt file for a django project. My project directory looks like this: decker-cms ├── decker_cms │ ├── account │ ├── beanstream │ ├── blog │ ├── [...project stuff] ├── decker │ ├── [...env stuff] When I try to run the following command: pip3 install -r requirements.txt from within the decker_cms directory. I get the following error: ERROR: Command errored out with exit status 1: /Users/userk/decker-cms/decker/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-install-ow_x_27c/reportlab_cb76b6eba8ca413ca98c7cbe92425675/setup.py'"'"'; __file__='"'"'/private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-install-ow_x_27c/reportlab_cb76b6eba8ca413ca98c7cbe92425675/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/1y/pymk85y10l1cfkrh92s3n46h0000gn/T/pip-record-3hnbigmk/install-record.txt --single-version-externally-managed --compile --install-headers /Users/userk/decker-cms/decker/include/site/python3.9/reportlab Check the logs for full command output. I installed the project prerequisites: gif, python, pip3, Postgres 10.10 and npm. How can I go about solving this? -
Send Django Email User Register Confirmation with with custom header name
I want to send Django email confirmation email, it shows the admin added email address (that we configure in settings.py) as the header of the newly arrived email, but I want to change it to something else my personal Header Title, like The Google Team, I want to replace my email as others showing in the picture. https://prnt.sc/1mo2xeo -
Unhandled Rejection (TypeError): Cannot read property 'value' of undefined
I am working on React js with Django Rest API. When I try to submit form data through api, it showing me the error. I think some null values are going to api and I dont know how to check them. I am new to react.js learning from on tutorial.Can anyone please teach me a way to debug this kind of issues. Unhandled Rejection (TypeError): Cannot read property 'value' of undefined 22 | this.setState({ btnMessage: 1 }); 23 | 24 | var apiHandler = new APIHandler(); > 25 | var response = await apiHandler.saveMedicineData( | ^ 26 | event.target.name.value, 27 | event.target.medical_typ.value, 28 | event.target.buy_price.value, Here is my form code: async formSubmit(event) { event.preventDefault(); this.setState({ btnMessage: 1 }); var apiHandler = new APIHandler(); var response = await apiHandler.saveMedicineData( event.target.name.value, event.target.medical_typ.value, event.target.buy_price.value, event.target.sell_price.value, event.target.c_gst.value, event.target.s_gst.value, event.target.batch_no.value, event.target.shelf_no.value, event.target.expire_date.value, event.target.mfg_date.value, event.target.company_id.value, event.target.description.value, event.target.in_stock_total.value, event.target.qty_in_strip.value, this.state.medicinedetails ); this.setState({ btnMessage: 0 }); this.setState({ errorRes: response.data.error }); this.setState({ errorMessage: response.data.message }); this.setState({ sendData: true }); } Below is the Api Handler: async saveMedicineData( name, medical_typ, buy_price, sell_price, c_gst, s_gst, batch_no, shelf_no, expire_date, mfg_date, company_id, description, in_stock_total, qty_in_strip, medicinedetails ) { await this.checkLogin(); //Wait Until Token Get Updated var response = await Axios.post( Config.medicineApiUrl, { name: … -
App level static files loading in Django but not Project Level
My app-level static files are loading but not project level Whenever I try to access static files via localhost/static/css/... I can only access my app-level static files and not project-level. Here is my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static'), os.path.join(BASE_DIR, '/projects/static'), ] Here is the structure of my file directory structure | db.sqlite3 | manage.py | +---portfolio | | asgi.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | +---projects | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---static | | | | | +---css | | | projects.css | | | | | \---img | | test-1.jpg | | test-2.jpg | | test-3.jpg | +---static | +---css | | base-template.css | | | \---js +---templates | base.html | projects.html | project_detail.html -
expected str, bytes or os.PathLike object, not QuerySet
I want to extract the file field from my model , and open the file (file is in .pdf format) . but I got this error : expected str, bytes or os.PathLike object, not QuerySet my models.py is : class FileUpload(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') my views.py is : class PostDetailView(DetailView): context_object_name = "object_list" template_name = "post_detail.html" def get_object(self, *args,**kwargs): request = self.request pk = self.kwargs.get('pk') instance = FileUpload.objects.filter(id = pk) if instance is None: raise Http404("File Does not EXIST") else: pdfFileObj = open(instance, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print(pdfReader.numPages) pageObj = pdfReader.getPage(0) print(pageObj.extractText()) pdfFileObj.close() return instance Right now I am not using any template . Just want to print the file data inside my terminal . Mean when I refresh the page I got this error . -
Django similar url pattern issue
I am working on a products comparison module and have url patterns like below: path('comparison/<slug:slug1>-vs-<slug:slug2>/', views.compare_two_products, name="compare_two_products"), path('comparison/<slug:slug1>-vs-<slug:slug2>-vs-<slug:slug3>/', views.compare_three_products, name="compare_three_products"), The issue is that Django always matches the first pattern and returns 404 when I try to access the second pattern. However if I comment out the first pattern, then it matches the third pattern just fine. I want to get both the patterns working in the format slug-vs-slug-vs-slug. Any suggestions on what I might be doing wrong ? Thanks in advance. -
id1 - 1, id2 - 2, id3 - 2, id4 - 2, id5 - 3 if this is given then the final list will be id1, id4, id5, id3 and id2 python
i have list of data , I need to send that particular order like this: allready taken id need to move for next like that total list i need work (id1-1 ,id2-2 ,id3-2 then id2 moves to id3 and id2 goes for id3) example : id1 - 1, id2 - 2, id3 - 2, id4 - 2, id5 - 3 if this is given then the final list will be id1, id4, id5, id3 and id2 -
Serializing 3 Interconnected Django relational models
I am trying to write a set of serializers for my models. I want the serializer for the deck to spit out the cards that match the decks ID in the CardToDeck Model and then fetch the card matching the card_id in the Card Model models.py from django.db import models # Create your models here. class CardToDeck(models.Model): deck_id = models.ForeignKey("Deck", related_name="card_to_deck", on_delete=models.CASCADE) card_id = models.ForeignKey("Card", related_name="card_to_deck", on_delete=models.CASCADE) class Card(models.Model): id = models.AutoField(primary_key=True) multiverseid = models.IntegerField(unique=True) # Used to fetch the card from the API name = models.CharField(max_length=145) class Deck(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=145) serializers.py: from .models import * from rest_framework import serializers class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ('id', 'name') class CardToDeckSerializer(serializers.ModelSerializer): class Meta: model = CardToDeck fields = ('deck_id', 'card_id') # Serializer for Deck that grabs the nested model references class DeckSerializer(serializers.ModelSerializer): cards = serializers.PrimaryKeyRelatedField(queryset=CardToDeck.objects.all(), many=True) class Meta: model = Deck depth = 2 fields = ('name', 'cards') What I would like the JSON to look like: { "name": "deckNameGoHere", "cards": [{"id":1, "name":"cardNameGoHere", "quantity":3},{"id":2, "name":"cardNameGoHere", "quantity":2}] } I just spent the last 4 hours trying to figure this out and feel quite dumb, any help would be appreciated. I looked into the docks but … -
Why is requiring login on every page my django app on heroku?
I deployed a django web-app on Heroku. It has some views that require login and others that doesn't. If I set DEBUG = False on settings.py and push to Heroku, then all the URLS with the domain of my app require login. For Example: If I try to access to example.herokuapp.com then it will redirect me to example.herokuapp.com/accounts/login/?next=/ which is fine, beacause example.herokuapp.com require login to display If I try to access to example.herokuapp.com/accounts/signup/ then it will redirect me to example.herokuapp.com/accounts/login/?next=/accounts/signup/ which shouldn't happen, because example.herokuapp.com/accounts/signup/ doesn't require login If I try to access to example.herokuapp.com/blablablabla then it will redirect me to https://cafa.herokuapp.com/accounts/login/?next=/blablablabla which isn't right, because example.herokuapp.com/blablablabla is not even an included url in my app. I'm not sure how to fix this and I haven't find anything useful to guide myself to a solution. If it's necessary that I show part of the code I'll be happy to do it if that helps to find a solution. -
I want to implement an otp module when the user clicks on change number in the edit profile section of a django website. How to go about?
I tried implementing this using 2factor api. Created two html files and one for entering number and second for verifying otp. Changed the views and models files accordingly. -
How do i ensure that a django search form is not empty
I have this blog app and i want that when a user goes to /search, they can be able to search and filter blogs by either the author, title, or blog tags. I've already enabled Django-filter and its working, quite alright but when a user does not input a value and hits the search button, it just shows all the items in the database and i don't want that. i want them to get a flash message saying they need to input at least an item. Here is what my code looks like views.py def search(request): form = SearchForm() context = { 'form': form } return render(request, 'blog/search.html', context) def searchResults(request): blogs = BlogPost.objects.all() blog_filter = BlogPostFilter(request.GET, queryset=blogs) blogs = blog_filter.qs for item in request.GET: if request.GET[item] == '': print('sorry') context = { 'blogs': blogs, } return render(request, 'blog/search_results.html', context) forms.py class SearchForm(ModelForm): author = forms.ModelChoiceField( queryset=UserProfile.objects.all(), label='', required=False, ) title = forms.CharField( label="", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Title', 'class': 'form-control'}) ) short_description = forms.CharField( label="", required=False, widget=forms.TextInput(attrs={ 'placeholder': 'Short description', 'class': 'form-control'}) ) category = forms.ModelChoiceField( queryset=Category.objects.all(), label='', required=False, ) class Meta: model = BlogPost fields = '__all__' exclude = ['likes', 'related_image', 'date_added', 'content'] filters.py class BlogPostFilter(django_filters.FilterSet): title = CharFilter(field_name='title', … -
Django: How to authenticate a form in class based views
I am new to Django and I have this idea that when I user enters a room(image of the room) a modal popup ask them for a password of that specific room(as there will be other rooms) before they can get inside and see it's contents and the password is created by the admin in the admin site. Now my problem is I've created a password field on my room model, and I've also created a form for it, but I am having a hard time on how to incorporate it in my views.. I have no idea on how to GET the password that admin created and match it with what the user POST as the password. Could someone help me out? My Room model class Room(models.Model): name = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=32, unique=True, null=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) My form class RoomForm(forms.ModelForm): class Meta: Model = Room fields = ['password'] labels = {"password": "Room Password:"} widgets = { 'password':forms.PasswordInput() } My views class RoomListView(FormView, ListView): context_object_name = 'rooms' model = Room template_name = 'mysite/room_list_view.html' form_class = RoomForm -
Django built-in cache or use Redis in the source?
Well currently I am working at a source of django and found this in docker-compose.yml redis: container_name: cache image: redis:alpine ports: - 6379:6379 I was told that they use redis for saving cache. However, as I research django did have built-in catch from this link https://docs.djangoproject.com/en/3.2/topics/cache/ Since, I am beginner, I wonder what is the trade-off between build redisand use built-in catchof django in term of saving Catch. And if it was your case which one is more preferable. -
Django Object not Saving
I am currently trying to save a Django object. My code looks like this boxscore = BoxScore.objects.create(**defaults) print(defaults) input(boxscore) Here's the output: {'away_first': 0, 'away_second': 6, 'away_third': 7, 'away_fourth': 17, 'away_final': 30, 'home_first': 0, 'home_second': 7, 'home_third': 0, 'home_fourth': 7, 'home_final': 14} BoxScore object (190) However, nothing is showing in Django admin as being saved in the database. Why would this be and how do I fix it? -
How to refresh the tokens stored in the Django Cache which is using Databse as a cache storage
I have tokens stored in the Django Database Cache. I want to periodically refresh the tokens i.e. after every 5 min. Refreshing involves checking the token validity by calling an External service API and deleting all the tokens which are invalid and deleting them from cache. How can this be done? -
Using django-polymorphic type information in query expressions
I have a django model with a couple of subtypes which until now I've been handling explicitly. Each record is uniquely identified by three fields: class Entity: type = CharField(max_length=3) released_at = DateTimeField() number = IntegerField() I use a query expression to combine this into a single string for searching and annotating results: entity_uid_expr = Case( When( number=None, then=Value(None), ), default=Concat( 'type', ExtractYear('released_at'), 'number', output_field=CharField() ), output_field=CharField() ) This has worked well so far but the two subtypes are diverging quite drastically now and it would be easier to handle those as subclasses using the polymorphic model. What I'm trying to do is something like this: class Entity: released_at = DateTimeField() number = IntegerField() class EntityA(Entity): type = 'A' class EntityB(Entity): type = 'B' But this removes the type information from the DB and breaks the query expression. Is it possible to set a field's default based on the polymorphic class? The only other alternative I can think of is hiding it from visibility and autopopulating it with the right value on save. Would that be a viable approach or am I missing something? Thanks! -
How can we integrate call forwarding in our website like Indiamart?
We have a website called RentYug on which people can give or take anything on rent. For this, we are taking contact information like mobile number and some other details of renter (who is giving Something on rent). But we don't want to show the mobile number to everyone. We want to forward the call through us like Indiamart to make this website more safe. Website is developed using React.js and Django. I need to know that so I can integrate this before launch. Website demonstration https://rentyug.netlify.app -
Automatically get the user’s location from the user’s browser instead of hard-coding in django view to filter nearest shop
Am building a simple nearby shops application that lists the shops closest to a user’s location using django and GeoDjango. To list the shops, i want to get a user's location from their browser and then filter the nearest shop for the user instead of hard-coding it. views.py from django.views import generic from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import Distance from .models import Shop longitude = -80.191_788 latitude = 25.761_681 user_location = Point(longitude, latitude, srid=4326) class Home(generic.ListView): model = Shop context_object_name = "shops" queryset = Shop.objects.annotate( distance=Distance("location", user_location) ).order_by("distance")[0:6] template_name = "Home.html" models.py class Shop(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) -
ezhc heatmap.build requires pandas.core.index but it is Pandas.core.index is deprecated
I use ezhc and pandas to generate data for heatmap def industry_heatmap(csv): df = pd.read_csv(csv).set_index('Industry').groupby(level=0).mean() idx, col, data = hc.build.series_heatmap(df) … return idx, col, data return json However as a result of pandas 1.3.1 deprecating pandas.core.index... C:\Users\lib\site-packages\ezhc\build.py, line 338, in series_heatmap return series def series_heatmap(df, *args, **kwargs): idx = df.index col = df.columns assert(isinstance(idx, pd.core.indexe.Index)) … for c in col: assert(df[c].dtype.kind in 'if') dft = df.copy() dft.index = range(len(df.index)) dft.columns = range(len(df.columns)) I get an attribution error module 'pandas.core' has no attribute 'index' Any workaround or alternative for ezhc generating data for for highchart javascript??? thanks in advance -
Django queryset.values_list() except returning a queryset of a foreign key
Given some simple models, including one with a foreign key: class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() If I have an arbitrary queryset of the Entry objects. How can I convert that into a queryset of the associated "blog" objects through the foreign key? If I use a value_list Entry.objects.values_list('blog', flat=True) it's just a list of blog ids, not a Blog queryset that I can do further Blog-related queryset operations on. The only way I can think of is something like this: blog_ids = Entry.objects.values_list('blog', flat=True).distinct() Blog.objects.filter(id__in=blog_ids) But I was hoping for something more straightforward or cleaner. -
Why my queryset changes size after I evaluate it in Django?
I have a simple model: class Expense(models.Model): ... price = models.DecimalField(decimal_places=2, max_digits=6) is_fixed = models.BooleanField(default=False) I'm trying a simple query to group_by and aggregate: >>> from expenses.models import Expense >>> from django.db.models import Sum >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) I expected that qs will have two records: >>> qs.count() 2 But when I evaluate it, it returns nine! >>> len(qs) 9 After the evaluation, count starts to return nine as well: >>> qs.count() 9 To ilustrate even more: >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) >>> qs.count() == len(qs) False >>> len(qs) == qs.count() True >>> qs = Expense.objects.values('is_fixed').annotate(total=Sum('price')) >>> len(qs) == qs.count() True I have no idea what is causing this "anomaly". What do you think it might be? -
Djongo - trying to create a list field
I'm trying to explore Django and djgono for fun. I want to create a document in the db which is similar to the following document: { "title": "Djongo - trying to create a list field", "body": "I cannot do basic programming...epic fail!", "tags": ["django","djongo","list"] } Following is my code: from djongo import models class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField(max_length=1000) tags = models.JSONField() Clearly I am going horribly wrong somewhere. Would be happy if someone pointed me in the right direction. Thanks! -
Has anyone shared a CRSF token between React and Django without running into Forbidden 403?
I've been trying to execute a simple endpoint I made available with Django from my front-end, React. It's a POST request that checks if a URL exists. It's just a demo so I can get familiar with the full stack process. The issue is that any attempts at trying to test this endpoint outside of React, I receive a Forbidden: CSRF token missing or incorrect error log in my Django console, meanwhile inside React I just fail to fetch. Here's what I have: Relevant Code views.py def check_url(request, url): headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"} r = requests.get(url, headers=headers) return HttpResponse(status=r.status_code) component.jsx //django crsf token for api const getCookie = (name) => { var cookieValue = null; if (document.cookie && document.cookie !== "") { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = $.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; //handles making api call with the cookie const APIcall = () => { var csrftoken = getCookie("csrftoken"); fetch("http://127.0.0.1:8000/check_url/", { credentials: "include", method: "POST", mode: "same-origin", headers: { … -
Uploading Image to AWS using Tinymce and Django
I am working with django an Tinymce. I have an issue with uploading image to s3 bucket from the Tinymce textarea. The same code does the uploading perfectly on my local. but when deployed, it doesnt get to upload. @csrf_exempt def upload_image(request): if request.method == "POST": file_obj = request.FILES['file'] file_name_suffix = file_obj.name.split(".")[-1] if file_name_suffix not in ["jpg", "png", "gif", "jpeg", ]: return JsonResponse({"message": "Wrong file format"}) upload_time = timezone.now() path = os.path.join( settings.MEDIA_ROOT, 'tinymce', str(upload_time.year), str(upload_time.month), str(upload_time.day) ) # If there is no such path, create if not os.path.exists(path): os.makedirs(path) file_path = os.path.join(path, file_obj.name) file_url = f'{settings.MEDIA_URL}tinymce/{upload_time.year}/{upload_time.month}/{upload_time.day}/{file_obj.name}' if os.path.exists(file_path): return JsonResponse({ "message": "file already exist", 'location': file_url }) with open(file_path, 'wb+') as f: for chunk in file_obj.chunks(): f.write(chunk) return JsonResponse({ 'message': 'Image uploaded successfully', 'location': file_url }) return JsonResponse({'detail': "Wrong request"})