Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting NoReverseMatch.Reverse for '{props.url}' not found.Trying to make a link in django with the name being a dynamic value
<a href="{% url '{props.url}' %}"><input type='submit' value='REGISTER' id={props.card_id + '1'}/></a> Im creating a component where in theres a link which has a name which points to one of the items in urlpatterns of urls.py based of the name value which is in props.url. But im unable to put the value in the href of a tag -
Using APScheduler in clock.py on Heroku to call def send_email_reminder from main app
I have an app that tracks users borrowing equipment. In the application I have an app "tool_req". In the views.py file I have a def called "send_email_reminder". I want this to run once a day to send emails to the borrower that the rental period is over. I have installed APScheduler and have a file "clock.py" to run in the background on Heroku. My Procfile looks like this: Procfile.py ... web: gunicorn trydjango.wsgi clock: python clock.py ... When I push the app using the following clock.py file I see the message every 3 minutes in my logs. clock.py from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): print('This job is run every three minutes.') sched.start() So far so good. However, when I put in the code to run the send_email_reminder, i.e.,: clock.py from apscheduler.schedulers.blocking import BlockingScheduler from tool_req.views import send_email_reminder sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): send_email_reminder('request') sched.start() I get this error: app[clock.1]: ModuleNotFoundError: No module named '/app/trydjango/settings' I have tried a lot of things including various combinations of the following in my clock.py file, to no avail. import os from apscheduler.schedulers.blocking import BlockingScheduler from tool_req.views import send_email_reminder from django.contrib.auth.models import User from tools.models import Tool, Literature … -
Django - improve the query consisting many-to-many and foreignKey fields
I want to export a report from the available data into a CSV file. I wrote the following code and it works fine. What do you suggest to improve the query? Models: class shareholder(models.Model): title = models.CharField(max_length=100) code = models.IntegerField(null=False) class Company(models.Model): isin = models.CharField(max_length=20, null=False) cisin = models.CharField(max_length=20) name_fa = models.CharField(max_length=100) name_en = models.CharField(max_length=100) class company_shareholder(models.Model): company = models.ManyToManyField(Company) shareholder = models.ForeignKey(shareholder, on_delete=models.SET_NULL, null=True) share = models.IntegerField(null = True) # TODO: *1000000 percentage = models.DecimalField(max_digits=8, decimal_places=2, null=True) difference = models.DecimalField(max_digits=11, decimal_places=2, null=True) update_datetime = models.DateTimeField(null=True) View: def ExportAllShare(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="shares.csv"' response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response) writer.writerow(['date','company','shareholder title','shareholder code','difference','share']) results = company_shareholder.objects.all() for result in results: row = ( result.update_datetime, result.company.first().name_fa, result.shareholder.title, result.shareholder.code, result.difference, result.share, ) writer.writerow(row) return (response) -
django-channels: keeping track of users in "rooms"
TL;DR - How do I maintain a list of users in each room so that I can send that data to the front-end to display a list of participants in this room. I'm designing a collaborative web application that uses django-channels for websocket communication between the browser and the server. A room can be joined by more than one user and every user should be aware of every other user in the room. How would I go about achieving this using django-channels (v2)? I already went through the documentation and a few example projects available online but none of them have added a similar functionality. I also know about django-channels-presence but the project doesn't seem to be actively maintained so I didn't really bother looking into examples using that. Here's what I've come up with so far: - For every room, I create an object in the database and those objects can keep track of the users that are in the room. So for e.g in the WS consumer's connect() method I could do a get_or_create_room() call and room.add_participant(self.user_name) (or fetch this from the scope) and in the disconnect() method I could remove myself from the room. The problem with … -
the best way to update data users upload
when I create something I call A, then the data on B, C, D has been changed, then I wanna change the data of A, so the B , C, D will change relatively, my solution is before changing A, rollback the data on B, C, D it used to be, then do the same thing as creating A again, is there any better solution for this? -
Is there a java script I can write to switch between the locale files I've created?
so I have this select tag that get the languages from the setting but I don't know how to write if the user choose Spanish get the Spanish file to translate text <label>Language:</label> <select name="language" id="id_language"> {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option> {{ lang.1 }} </option> {% endfor %} </select> <h1>{% trans hello %}</h1> <h2>{% trans 'This is a translation template' %}</h2> -
Django bufsize must be an integer
I am trying to run python code with a click of an html button and have it run a python script. I would prefer to just use a normal button rather than using a form to create a "submit" button (like I have it for my first card I created in index.html), but with the tutorial I followed, that's how it was done and couldn't find a way around it. All I want to do is run a script that I created with a click of a button. I am trying to do it with Django, but cant seem to fix this error. TypeError at /external/ bufsize must be an integer Request Method: POST Request URL: http://127.0.0.1:8002/external/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: bufsize must be an integer Exception Location: C:\Users\12673\anaconda3\lib\subprocess.py in __init__, line 702 Python Executable: C:\Users\12673\anaconda3\python.exe urls: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.urls import path from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.button), url(r'^output',views.output,name="script"), url(r'^external',views.external), ] Views.py from django.shortcuts import render import requests from subprocess import run,PIPE import sys def button(request): return render(request,'index.html') def output(request): data=requests.get("https://regres.in/api/users") print(data.text) … -
How To Use Django Password Reset for Users Password Reset Instead of Admin's only?
I am desiging a website using python django on backend,sites manages different users so how I can enable password reset functionality in that,I have tried django password reset but it seems that it only works for Admin credentials..How to use it for multiple users ? -
Force Django to Run a Test Against A Real, Production Database
I'll start by saying that I understand that in 99.99999% of cases, this should be avoided. I believe I have a valid use case, however. We are a large company with a huge MySQL cluster which houses I-don't-even-know-how-many-millions of records across thousands of tables. We are writing a Django application which accesses 4 schemas in the cluster which amounts to about 100 tables. We are never writing to these tables, only reading from a large cross section of them. I have used Django to machine generate read-only, unmanaged ORM classes for these tables and it is working beautifully in practise. All I want is one test which hits a REST endpoint and checks if it answers 200 OK. I need no tests beyond that because in 6 months we are moving away from this data source entirely. We don't have write access to this data. The amount of security and administrative effort we would need to go through in order to be able to change a single byte of data in the cluster would represent weeks of meetings and discussion, and then we'd be rejected. If we wrote code to add, update, or delete data from this source, it would … -
Django ConnectionAbortedError
So I am trying to solve api issue. I am making request to django backend using axios from my frontend application. They are running on seperate domains. My django app is running in a virtual environment. If I make a request using postman I will get my response no problem but if I make request using my front end application I get the following error. Traceback (most recent call last): File "c:\laragon\bin\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\laragon\bin\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\laragon\bin\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\laragon\bin\python\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine This is the axios method axios.get('http://mybackend/api/oauth') .then(response => { context.commit('CONNECTION', response) console.log(response) resolve(response) }).catch(error => { console.log(error) reject(error) }) and this is my method for returning my response urls.py urlpatterns = [ path('api/oauth', oauth, name='oauth') ] api.py @api_view(['GET']) def oauth(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT ) data = auth_client.get_authorization_url([Scopes.ACCOUNTING]) request.session['state'] = auth_client.state_token return Response(data) So for some reason the connection is being closed, before the … -
Unable to save my admin.py changes in my model
I am pretty new to django. I am trying to save my admin.py list_editable changes in my model. I am using 'def clean(self):' in my model for validationError and if there is no validation i need to save my changes. class DashBoard(models.Model): """Dashboard to be used to upload all my items""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length = 255, null = True) tranScription = models.CharField(max_length = 255, null = True) videoUrl = models.CharField(max_length = 255, null = True) audioUrl = models.CharField(max_length = 255, null = True) imageUrl = models.CharField(max_length = 255, null = True) foodQuality = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) ambience = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) cleanliness = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) mediaType = models.CharField(max_length = 255, default ='mp4') date = models.CharField(max_length = 255, default= datetime.today().strftime("%Y-%m-%d")) isUploaded = models.BooleanField(max_length = 255, default = False) def clean(self): if value < 0 or value > 1: raise ValidationError(u'%s is not between 0 and 1' % value) def __str__(self): return self.title -
How to loop through millions of Django model objects without getting an out of range or other error
I have millions of objects in a Postgres database and I need to send data from 200 of them at a time to an API, which will give me additional information (the API can only deal with up to 200 elements at a time). I've tried several strategies. The first strategy ended up with my script getting killed because it used too much memory. This attempt below worked better, but I got the following error: django.db.utils.DataError: bigint out of range. This error happened around when the "start" variable reached 42,000. What is a more efficient way to accomplish this task? Thank you. articles_to_process = Article.objects.all() # This will be in the millions dois = articles_to_process.values_list('doi', flat=True) # These are IDs of articles start = 0 end = 200 # The API to which I will send IDs can only return up to 200 records at a time. number_of_dois = dois.count() times_to_loop = (number_of_dois / 200) + 1 while times_to_loop > 0: times_to_loop = times_to_loop - 1 chunk = dois[start:end] doi_string = ', '.join(chunk) start = start + 200 end = end + 200 [DO API CALL, GET DATA FOR EACH ARTICLE, SAVE THAT DATA TO ARTICLE] -
Exception Type: NoReverseMatch - Django
after researching for hours I cannot get rid of this error, I hope someone can help me. Models: class Puja(models.Model): seller = models.OneToOneField(Seller, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True) title = models.CharField(max_length=100) video = models.FileField(blank=True) photo = models.ImageField(blank=True) published_date = models.DateTimeField("Published: ",default=timezone.now()) bidding_end = models.DateTimeField() starting_price = models.IntegerField(default=1) #slug = models.SlugField(null=True) def __str__(self): return str(self.title) #def get_absolute_url(self): # return reverse('bidding_list_detail', args=[str(self.id)]) #slug time def get_absolute_url(self): return reverse('bidding_list_detail',args={'id': self.id}) Views: class bidding_list(ListView): model = Puja template_name = 'bidding_templates/bidding_list.html' """return render(request= request, template_name='bidding_templates/bidding_list.html', context = {"Pujas": Puja.objects.all})""" class bidding_list_detail(DetailView): model = Puja template_name = 'bidding_templates/bidding_list_detail.html' urls: path('admin/', admin.site.urls), path("bidding_list/", bidding_list.as_view(), name="bidding_list"), path('<int:pk>', bidding_list_detail.as_view(), name='bidding_list_detail'), admin: class PujaAdmin(admin.ModelAdmin): list_display = ('seller','title','video','photo','published_date','bidding_end','starting_price') admin.site.register(Puja,PujaAdmin) template 1: {% extends 'header.html' %} {% block content %} <h1>Pujas</h1> {% for Puja in object_list %} <!--object_list--> <ul> <li><a href="{{ Puja.get_absolute_url }}"> {{ Puja.title }} </a></li> </ul> {% endfor %} {% endblock %} template 2: {% extends 'header.html' %} {% block content %} <div> <h2>{{ object.title }}</h2> <p>{{ object.seller }}</p> </div> {% endblock %} Note that, whenever I remove <a href="{{ Puja.get_absolute_url }}"> from the first template, the objects "puja" in the model get properly displayed on the template, but I cannot access them. They normally exist on the admin … -
Django/DRF - Serialize Queryset avoiding N+1 problem with SerializerMethodField
I am using this model configuration. class Project(models.Model): name = models.CharField(max_length=64) class Platform(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_platforms") is_deleted = models.BooleanField(default=False) Now, I am getting my queryset using this code. queryset = Project.objects.prefetch_related("project_platforms") I want to serialize this queryset using the following Serializer. class ProjectSerializer(serializers.ModelSerializer): platforms = serializers.SerializerMethodField("_platforms") class Meta: model = Project fields = ["id", "name", "platforms"] def _platforms(self, obj: Project) -> list: platforms = PlatformSerializer(obj.project_platforms.filter(is_deleted=False), many=True).data return platforms Now, even though I have used prefetch_related, when I call the serializer on my queryset, it still causes one query for each project in fetching the platforms for each project. I cannot use platforms = PlatformSerializer(read_only=True, many=True) since the PlatformSerializer is declared below ProjectSerializer. Is there any solution to this? Am I doing something wrong? -
How to preload a video in Django
This is an online experiment program in Django. In the playing page I got: Playing.html <video height="50%" autoplay id="video" {{video_muted|safe}}> <source src="{% static path %}" type="video/mp4"> </video> The videos are just 1-5MB, however, some users' Internet speed is so slow. Sometimes it takes them 2 minutes to load/download a video. Any method I can transfer the videos to users browser first and then in the playing.html, it gets the video from "cache in local browser" instead of the server directly. Thanks in advance. -
Checking in def clean to see if image field has been cleared
Within my def clean function, I've built a check to see if a user has an image, but no body, which is an invalid combination. forms.py def clean(self): cleaned_data = super(ServicesForm, self).clean() body = cleaned_data.get('body ') image = cleaned_data.get('image') if body != None and image == None : self.add_error('image', "You must provide an image if you want to save the post.") This works well upon the creation of the post. The error shows up if the user enters text in the body, but doesn't provide an image. However, if a user goes back to a post where both a body and image have been provided and clicks on 'clear' on the image widget, they are able to save the form with no error being thrown. Due to other reasons, I do not want to set image as a required field on this form. (There is other business logic that controls whether or not an image is required or not). How can I check in def clean() to see if the user has cleared the image? Thanks! -
How to disable loggin in pyppeteer
I'm using pyppeteer to take screenshots of images to a make a pdf but pyppeteer auto logs everything I take a screenshot at and because of server limitations and the logs is written to a file the logs are crashing my server. Is there any way to completely disable loggin? I tried this already: 'logLevel': logging.NOTSET, 'env': {'DEBUG': 'puppeteer:*,-not_this'}, I also tried to disable loggin like this: logging.getLogger('pyppeteer').setLevel(logging.NOTSET) And nothing seems to work. -
Puzzling Warning With FileField In Django Admin
I created the below model to associate a file with another object type called Organization. The _path() function sets the path of the file to {MEDIA_ROOT}/orgs/{NAME OF ASSOCIATED ORG}/{FILENAME}. It also replaces any spaces in the path with underscores. So if I upload the file "Draft1.doc" and associate it with the org named "My High School", the full path should be uploads/orgs/My_High_School/Draft1.doc This is in my settings.py file MEDIA_ROOT ='uploads/' class OrgFile(models.Model): def _path(instance, filename): return F"orgs/{instance.org.name.replace(' ', '_')}/{filename}" file = models.FileField(upload_to=_path) org = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.file.name.split('/')[-1] When I use the Admin to upload and associate a file, the file is created in the correct place on disk and appears to have the correct path and associations in the admin. However when I navigate to the file object in the admin and click on the path labeled currently the "uploads/" portion is not included in the path (which may be OK) but I also get the warning: Org file with ID “9/change/orgs/My_High_School/Draft1.doc” doesn’t exist. Perhaps it was deleted? I have no idea why this happens since everything else looks OK. I assume that the link is supposed to take me to the file. -
Keyboard shortcut for {% %} in VSCode using Django HTML
I am building my first Django app and using the Django templating engine in my html files. I have the html and Django html plugin in VSCode. So far, it autocompletes html elements and colorizes the Django templates. Is there a way to autocomplete {% %} when using the Django HTML language mode in VSCode? -
I want to use my admin part rather then given by django default admin panel how i add my admin in django and also connect with db. its my admin panel
I have two part one of alumni section and another secton is admin section, this is my admin section image. -
Django - urls.py issue
I am developing this platform where a user can log in and take a quiz. The issue is that when I go on "localhost/quiz/quiz/" and then a click on my "choice", for example "data science" it gives me this error: sing the URLconf defined in piattaforma.urls, Django tried these URL patterns, in this order: admin/ [name='homepage'] users/ [name='user_list'] user/<username>/ [name='user_profile'] accounts/ accounts/ quiz/ quiz/ [name='quiz'] quiz/ questions/<choice>/ [name='questions'] quiz/ result/ [name='result'] The current path, quiz/datascience, didn't match any of these. I think the problem is on my urls.py on the questions path but I can't solve it quiz/questions.html {% extends "base.html" %} {% block title%} QUIZ {% endblock %} {% block content%} <form action="./result" method="post"> {% for que in ques %} <div class="row"> <div class="col-md-10"> <h3>{{ forloop.counter }}. {{ que.question }}</h3> </div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optiona }}"> {{ que.optiona }} </h4> </div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optionb }}"> {{ que.optionb }} </h4> </div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3"> <h4> <input type="radio" name="{{ que.id }}" value="{{ que.optionc }}"> {{ que.optionc }} </h4> </div> <div class="col-md-3"> <h4> <input class="form_control" type="radio" name="{{ que.id }}" value="{{ … -
django: drowning in login form/view
I am struggling a lot with my login system. At this point, I have watched so many different things about the topic that I got a bit lost. I have tried using the built-in authentication system but I failed to make it work with django-tenant. At this point, my login view "works" but does not do its job. I am unable to figure out what is going on. Ideally I would like to integrate what I have with Django built in User for a safe and secure authentication system. Model.py class Client(TenantMixin): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, default='') email = models.EmailField(default='') company = models.CharField(max_length=100, default='') password = models.CharField(max_length=100, default='') created_on = models.DateField(auto_now_add=True) class Domain(DomainMixin): pass forms.py class UserLoginForm(forms.Form): email = forms.CharField() password = forms.CharField(widget = forms.PasswordInput) company = forms.CharField() def cleaned_data(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') company = self.cleaned_data.get('company') try: tenant = Client.objects.get(email=email, password=password, company=company) except Client.DoesNotExist: raise forms.ValidationError("User does not exist") if email and password: user = authenticate(username= email, password= password) if not user: raise forms.ValidationError('THIS USER DOES NOT EXIST') if not user.check_password(password): raise forms.ValidationError('incorrect password') if not user.is_active: raise forms.ValidationError('this user is not active') return super(UserLoginForm, self).clean() views.py def login_view(request): form = UserLoginForm(request.POST or None) if … -
Heroku Deployment With MongoDB Error: Connection Refused
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused Hello their, I am having a little bit of trouble trying to deploy my Django site in python. I am getting this error(shown above) when trying to connect with my MongoDB atlas database. I read that I have to whitelist my IP, but when I did it did not work. Here is my views.py file: class Initialize(): def __init__(self, name): self.name = name myclient = pymongo.MongoClient('mongodb+srv://<MY Username>:<My Password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority') global mydb mydb = myclient[f"{self.name}"] global userData userData = mydb["userData"] global authData authData = mydb["auth_user"] global storesCollection storesCollection = mydb["stores"] global mycolPostalCodes mycolPostalCodes = mydb["postalCodes"] When I was running my code before I tried deploying it, the code worked fine. Also, here is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'cluster0', 'HOST' : 'mongodb+srv://<my username>:<my password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority', 'USER': '<my username>', 'PASSWORD': '<my password>', } } Any help would be much appreciated. Thanks. Please message me for more information if needed. -
What is the use of Celery in python?
I am confused in celery.Example i want to load a data file and it takes 10 seconds to load without celery.With celery how will the user be benefited? Will it take same time to load data? -
Refused to display iframe or embed tag in django 3.0 and chrome
I had a django app that used an iframe to display a pdf stored in my local machine, something like this: <embed src="path_to_file.pdf" type="application/pdf"> Everything worked just fine in all supported browsers... Until today. The app suddenly stopped working on Chrome and the console displays the message Refused to display 'path_to_file.pdf' in a frame because it set 'X-Frame-Options' to 'deny'. In other browsers it's still working as usual. I don't know if Chrome just made an update or what changed but it is not working anymore. ¡Any help would be appreciated!