Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model TextField display zip code format
In my models.py, I have a zip code field that are in TextField format: class Merged(models.Model): zip_code = models.TextField(db_column='Zip Code', blank=True, null=True) However, there are some invalid zip codes like sagaponack 11962 lindenhurst 11757 I just want to display the 5-digit zip code without any other texts. What I have tried and failed In serializers.py, I tried to apply a RegexField to the zip_code column: class MergedSerializer(serializers.HyperlinkedModelSerializer): zip_code = serializers.RegexField(regex=r'^\d{5}') class Meta: model = Merged fields = '__all__' It did not work. How do I solve this in a way that does not only change how it displays, but also ensures that sorting works properly (i.e. ignore the text part, only sort based on zip codes) -
How to create tags that are different, which are unique to the blogs in django wagtail
Hello I am following this tutorial, https://docs.wagtail.io/en/stable/getting_started/tutorial.html# and I am on the tags portion. Question I have is, how do I create tags thats different for each application. I have two apps, LibBlog and libnewsblog. If i create a tag for Blog called School, I want it to only search Blog. Same thing for Libnews. Right now When I click on the Tag "School" it shows up posts from both LibBlog and LibNewsBlog. -
Django and chart.js - one bar per 'date' in model
I have a model that contains a date and a number. There are multiple inputs from the same date that I want to merge into 1 bar on the chart. How can I show each date only once but add up all of the totalPacks under that date? model: Views: def homepage(request): labels = [] data = [] queryset = DailyCountsModel.objects.order_by('-date') for jobs in queryset: labels.append(jobs.date) data.append(jobs.totalPacks) return render(request,'index.html', { 'labels': labels, 'data': data, }) Currently this chart will show one bar per entry.. I can't think of how I could do this. Any ideas? I'm guessing somehow I would need to check to see how many items they are with the 'date' of 2021-08-23 and add up the 'totalPacks', I'm just not sure how I would do this -
CPanel Slug in Django
I'm new in posting in Stackoverflow. I'm sorry if my English isI'm using CPanel to host my web, but when I try to deploy my web, the route to Technopark and route with format year/month/slug are not working properly, which the page opened is not as expected. Here I attach my script for home/desajono/webdesajono/desajono/views.py : And here is the result if the application is run in the local : 127.0.0.1/technopark: [enter image description here][1] 127.0.0.1/2021/08/pentingnya-olahraga-untuk-menurunkan-risiko-kepara : [enter image description here][2] But if the application is run in hosting, the result is like these pictures : https://desajono.com/technopark : [Technopark Page][3] https://desajono.com/2021/08/pentingnya-olahraga-untuk-menurunkan-risiko-kepara : [Slug Page][4] [1]: https://i.stack.imgur.com/CNq0f.png [2]: https://i.stack.imgur.com/ulGx3.png [3]: https://i.stack.imgur.com/wfRAu.jpg [4]: https://i.stack.imgur.com/JvwIy.jpg And here are some of my important codes that maybe you can use to give suggestion : from django.contrib import admin from django.urls import path, include admin.autodiscover() from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('', include('desajono.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) print("Ini URL di mysite : {}".format(urlpatterns)) home/desajono/webdesajono/desajono/urls.py : from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ url(r'', views.index, name='index'), url(r'^<int:year>/<int:month>/<slug:slug>/', views.see_article, name='article-detail'), url(r'^technopark/', views.open_technopark, name='technopark'), ] print('Ini URL … -
Context data not used when form is invalid
i am creating a view using formview class and using get_context_data to display some information on the test html page alongside the form i error which i am facing is when the form gets invalid i get in get_context_data context['username'] = data['username'] KeyError: 'username' i am not sure why the context data not getting picked up when the form invalidates class TestView(LoginRequiredMixin,FormView): form_class = TestForm template_name = 'test.html' def get_context_data(self, **kwargs): context = super(CredentialsView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: data = TestViewSet.as_view({'get': 'list'})(self.request).data context['username'] = data['username'] context['firstname'] = data['firstname'] context['lastname'] = data['lastname'] context['validstartdate'] = data['validstartdate'] context['validenddate'] = data['validenddate'] return context def form_valid(self, form): password = form.cleaned_data['password'] if form.is_valid(): return self.query_api(password) else: return super(TestView, self).form_valid(form) -
Django and google earth engine not running on heroku
I have deployed Django app with gene map on Heroku Build is successful but got an error : -- error -- Please authorize access to your Earth Engine account by running earth engine authenticate in your command line, and then retry. --- error --- even I have run command on Heroku CLI -- Heroku run earth engine authenticates and authenticated successfully but still got this error I have used this reference -- https://bikeshbade.com.np/tutorials/Detail/?title=Interactive%20web%20mapping%20with%20Django%20and%20Google%20Earth%20Engine&code=15 -
How can I avoid infinite loop when reformatting url hash with Jquery event 'hashchange'
Issue Background I have set up my webpage to use identifiers with prefix #s- to differentiate anchor links from other page identifiers. The window.location.hash changes to hash which moves the frame to the content in focus but also triggers the hashchange listener causing a loop. What I've tried I have it working for whenever the hash has changed but the only instance it does not work is when the same link it pressed (as I use this in the condition to stop the infinite loop). The code for this was: $(window).on('hashchange', function(e) { if ($(location).attr('hash') != last_hash) { manageHash() } }); What I want I'd like to be about to find a condition or method to allow users to select a link to change the hash but also allow them to re-select the same link as many times as they want without causing a loop. JS last_hash = '' function manageHash() { var hash = $(location).attr('hash'); if($('#s-'+hash.substring(1)) != 0 && '#s-'+hash.substring(1) != '#s-' ) { last_hash = hash window.location.hash = '#s-'+hash.substring(1); } } $(window).on('hashchange', function(e) { if ($(location).attr('hash') != last_hash) { manageHash() } }); $(document).ready(function() { manageHash() }) HTML <div class="contentSubSectionContainer contentSubSection" id="s-{{ subsection.slug }}"> <h2 class="contentSubSectionFont1Bold">{{ subsection.sub_section_title }}:</h2> <div … -
how to do if contion check with variable (true or false) inside django template
how to do if contion check with variable (true or false) inside django template <select id="company_id" name="company_id" class="form-control " > <option value="">Select Company {{company_id}}</option> {% for row in brands %} {% if row.id == company_id %} <option value="{{ row.id }}" >{{ row.title }} </option> {% else %} <option value="{{ row.id }}" selected>{{ row.title }} </option> {% endif %} {% endfor %} </select> -
Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format/ speech to text view python
my speech to text view doesn't work and I have the file wav but I got this error Traceback (most recent call last): File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\privet01\Desktop\python projects\projex x\alpha1\appsolve\views.py", line 636, in spechtotext with sr.AudioFile(sound) as source: File "C:\Users\privet01\Desktop\python projects\projex x\myvev\lib\site-packages\speech_recognition\__init__.py", line 236, in __enter__ raise ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format [23/Aug/2021 13:26:44] "POST /spechtotext/ HTTP/1.1" 500 152359 This is my view import speech_recognition as sr from django.core.files.storage import FileSystemStorage def spechtotext(request) : if request.method=='POST': if request.FILES['theFileINEEd'] and '.mp3' in str(request.FILES['theFileINEEd'].name).lower() : myfile = request.FILES['theFileINEEd'] fs = FileSystemStorage('') filename = fs.save(str(request.user)+"speachtotext.WAV", myfile) file_url = fs.url(filename) full_link='http://127.0.0.1:8000'+file_url # changeble to life mode r = sr.Recognizer() print(type(filename)) print('hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh') r = sr.Recognizer() import sys print(sys.version_info) print('qqqqqqqqqqqqqqqqqqqqqqqqq'+str(filename)+'aaaaaaaaaaaaaaaaaaaa') hellow=sr.AudioFile(str(filename)) sound = str(filename) with sr.AudioFile(sound) as source: r.adjust_for_ambient_noise(source) print("Converting Audio To Text ..... ") audio = r.listen(source) try: print("Converted Audio Is : \n" + … -
string parameters passing do not working in dajango
view.py when i test my api with post man ,postman indicate tha this urls do not exist(404 not found) any solution please url postman:localhost:8000/photoByCategory/nature/ @api_view(['GET']) @permission_classes((permissions.IsAuthenticated,)) def photo_by_categorie(request, category=False): if request.method == 'GET': if category: photo_by_cat = Photo.objects.filter(category=category) serializer = PhotoSerializer(photo_by_cat, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py re_path(r'photoByCategory/(?:(?P<category>\d+)/)?$', views.photo_by_categorie, name='photo_by_categorie'), -
Django form choicefield doesn't rendering empty field
I have a form that has a choicefield, choice as follow - TYPE = (('','Select type'), ('college', 'College'), ('university', 'University')) class Form(ModelForm): type = forms.ChoiceField(choices=TYPE) As the document says `` Unless blank=False is set on the field along with a default then a label containing "---------" will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, 'Your String For Display'). Alternatively, you can use an empty string instead of None where this makes sense - such as on a CharField.``` I tried usign '' & None, both doesnt work ! It just shows the 'Select type' and immediately disappears ! Please help -
Django how to make timezone aware CustomTimeField?
from django.db import models class CustomTimeField(models.DateTimeField): .... Goal: I need to store the date in form of datetime but I need this field to return only the hour:minute:second and eliminate the rest. I tied: to handle this in the serializers but I am using three serializers for the same model so it can be overwhelming to do that especially when I tried to use one serializer and override it for each usage. -
Hide all records in Django admin unless a search query is entered
We have a Python-2.7 and Django project (version 1.11) that has lots of models registered on it (Users app, Invitations app, Profiles app, etc...) First thing I'm trying to do is create a group for some users that will have only viewing permissions when they log on to the Django admin and see limited models from the entire list. Second thing is to not have any records shown by default when you enter one of the models you're allowed to view. You must search for something in order for matching records to appear so that only results associated with that user is shown. Is this possible and if yes, how do I implement this? -
How to check user permission in ModelViewSet
I am want to check permission of the user in my ModelViewSet to understand how much data must be given to him? -
Django : Error: 'duplicate key value violates unique constraint'
I have to save images with s3 when creating a new object for my website. I have a code to save my images that I use in my model's save method. When I use the django administration panel, I can easily create my object without any error. But when I try to create my object throught my view, I get this error : Error: 'duplicate key value violates unique constraint « store_shop_pkey »' I think that in my serializer's create method, I try to save my object twice : once for the image and once for the rest of my object's keys. I don't know how to resolve this issue. It works well with PUT method. Here is my code : models.py : class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) # Set a null and blank = True for serializer mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7) message = models.TextField(null=True, blank=True) banner = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): try: """If we want to update""" this = Shop.objects.get(id=self.id) if self.banner: image_resize(self.banner, 300, 300) if this.banner != self.banner: this.banner.delete(save=False) else: this.banner.delete(save=False) except: """If we want to create … -
Hi i want to convert django project to exe format
Hi i want to convert django project to exe format I have converted python file to exe. But don't know about django to exe. Please anyone help me to do this -
E: dpkg was interrupted… run 'sudo dpkg --configure -a'
I was trying to deploy a Django project on AWS Deep Learning AMI (Ubuntu 18.04) Version 48.0. When I try to install packages I get this. "E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem." And when I run 'sudo dpkg --configure -a' nothing happens after this and the terminal get freeze Setting up linux-headers-5.4.0-1055-aws (5.4.0-1055.58~18.04.1) ... /etc/kernel/header_postinst.d/dkms: * dkms: running auto installation service for kernel 5.4.0-1055-aws Kernel preparation unnecessary for this kernel. Skipping... Building module: cleaning build area... 'make' -j32 NV_EXCLUDE_BUILD_MODULES='nvidia-drm ' KERNEL_UNAME=5.4.0-1055-aws IGNORE_CC_MISMATCH='1' modules..... -
How to set VSCode settings, so that an import is possible?
I have cloned a github repo and a project structure of it is a following (There are some files and subfolders in Lib\site-packages, Scripts\ and static\ ): -e_commerce\ --.idea\ --e_commerce_website\ ----.gitignore.txt ----db.slite3 ----manage.py ----requirements.txt ---.idea\ ---.vs\ ----e_commerce\v16\.suo ----ProjectSettings.json ----slnx.sqlite ----VSWorkspaceState.json ---e_commerce_env\ ----Include\ ----Lib\site-packages\ ----Scripts\ ----pyvenv.cfg ---ecom\ ----__pycache__\ ----___init___.py ----asgi.py ----settings.py ----urls.py ----wsgi.py ---static\ ---store\ ----__pycache__\ ----migrations\ ----templates\ ----___init__.py ----admin.py ----apps.py ----models.py ----tests.py ----urls.py ----views.py For example, in apps.py (and other files) an error occurs: Import "django.apps" could not be resolved from sourcePylance. ... which shows because of the line: from django.apps import AppConfig I have created an environment e_commerce_env which works successfully when I run the server from cmd / powershell. I checked where django is installed when being inside the env, and it turns out that the path is equal to: c:\users\user\desktop\e_commerce\e_commerce_website\e_commerce_env\lib\site-packages Should I set this path somewhere in VSCode to make it work? -
Media files don't preview - Django
I have a problem with media files. I read everything on Net and tried all offered solutions but nothing works. This is settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"static") STATICFILES_DIRS = (os.path.join(BASE_DIR, './myapp/static/'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is urls.py: urlpatterns = [ path('application/admin/', admin.site.urls), path('application/accounts/', include('django.contrib.auth.urls')), path('application/', include('myapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is part of template where image needs to show: {% if word.image %} <img src="{{ word.image.url }}" alt="img" class="wordImg"> {% else %} <p class="wordPar">No image to preview</p> {% endif %} Everything seems fine to me but obviously there is a mistake, because image cannot preview. I get this: image cannot preview Thanks for help! -
How do I filter in URL a serializer when it's nested in another serializer In Django?
I'm creating an API that has nested data like in the picture Now how to search nested data in URL here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) Here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'param'] and here's my view for the api class RobotViewSet(viewsets.ModelViewSet): queryset = Robot.objects.all() serializer_class = RobotSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = ['robot', 'JenkinJobName__jenkinsBuildNumber'] authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] in the API URL if I want to search a particular robot then using this URL URL/?robot=robotname I'm able to search that particular robot. But how can I search particular nested data using URL? using my view I'm getting search filters like this But that is not performing any Search. how to achieve that search and what is wrong with my code can … -
IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id
Hi everybody :) I try to add a profile user in my application.The goal is to create a profile in the same time that we create an account. But This error come : IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id I don't understand what is the probleme with my code because I have follow a youtube tutorial where this code works.. here is my code : views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import UserForm, ProfileForm # Create your views here. def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) profile_form= ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save(commit=False) profile = profile_form.save(commit=False) profile.user = user user.save() profile.save() return redirect('account:login') else: form = UserCreationForm() profile_form = ProfileForm() context = { 'form' : form , 'profile': profile_form, } return render(request, 'accounts/register.html', context) models.py : from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') birthday = models.DateField() mail = models.EmailField(max_length=254, null = True, blank = True) def __str__(self): return self.user.username forms.py : from django import forms from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from .models import Profile class LoginForm(AuthenticationForm): … -
ClientConnectorCertificateError
I get an error. What is the reason for this error. I try to catch data from the api with an async function and it comes this error. ClientConnectorCertificateError at / Cannot connect to host swapi.dev:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)')] async def index(request): start_time = time.time() url = 'https://swapi.dev/api/starships/9/' async with aiohttp.ClientSession() as client: task = asyncio.ensure_future(fetch(client, url)) results = await asyncio.gather(task) total = time.time() - start_time print(total) return render(request, 'index.html', {'results':results }) -
Search multiple tags at same time
I am building a small Social Media App. I am making a features of searching multiple posts using multiple tags like :- first_post , second_post. AND It will retrieve all the posts which are associated with searched tags. When i search one tag then it is working fine BUT When i search two tags then it is not working ( showing nothing ). models.py class UserPost(models.Model): post_creater = models.ForeignKey(User, on_delete=models.CASCADE) tags = TaggableManager() body = models.CharField(max_length=30,default='') views.py def search_posts(request): search_it = request.GET.get('q') items = '' if search_it: items = UserPost.objects.filter(tags__name__icontains=search_it) context = {'items': items} return render(request, 'search_posts.html', context) When i search just one item like post_1 then it is showing all the posts BUT When i search two tags like :- post_1 , post_2 then it is showing nothing. I also tried using split method :- search_it = search_it.split('+') BUT it is still showing blank. I will really appreciated your Help. Thanks -
Django: Why i m getting 404 when i try to delete an object from my database?
i have an uploads model and i want to be able to delete the images, so i wrote a delete request that takes the id of the image however i keep getting 404 not found, i have the same thing and same steps for the files model that i created and it works fine. @api_view(['GET', 'POST','DELETE']) def Upload_list(request): if request.method == 'GET': queryset = Uploads.objects.all() uploads=queryset.filter(owner=request.user) serializer = UploadSerializer(uploads, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) respFile=list(File.objects.filter(id=str(File.objects.latest('created_at')))) serializers=Fileserializers(respFile,read_only=True,many=True) return Response(serializers.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def UploadsDetails(request,pk): try: image=Uploads.objects.get(pk=pk) except Uploads.DoesNotExist: return HttpResponse(status=404) if request.method =='GET': serializers=Fileserializers(image) return JsonResponse(serializers) elif request.method =='DELETE': image.delete() return HttpResponse(status=204) these are the urls: from django.urls import path from .views import Upload_list,login from .views import UploadsDetails urlpatterns=[ path('Uploads/',Upload_list), path('Uploads/<uuid:pk>/',UploadsDetails), path('login/', login) ] -
how can solve out circular import error in django
I have created MeterModel and MeterAbstract in app MeterApp. MeterAbstract have Meter_number and MeterModel have related field of Meter. I used MeterAbstract in BillModel. from MeterApp import MeterModel class BillDetailModel(BillAbstract, MeterAbstract): Bill_Name=models.CharField(max_length=20, null=True, blank=False) . . Now I want to update some field of MeterModel so I override save method to update and use def save(self,*args, **kwargs): meter = MeterModel.objects.filter(meter_number=self.meter_number) But giving error on from MeterApp.models import MeterModel ImportError: cannot import name 'MeterModel' from partially initialized module 'MeterApp.models' (most likely due to a circular import) How can I solved this and use abstract fields to override save method?