Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot query "": Must be "User" instance in Django 3.2
I get this error from below view: from django.shortcuts import render, redirect from movies import models as movies_models from django.contrib.auth import get_user_model User = get_user_model() def playlists_view(request): if (not request.user.is_authenticated) or (not request.user.is_staff): return redirect('Login') playlists = movies_models.PlayList.objects.filter(created_by=request.user).order_by('-id') return render(request, 'cpanel/playlists.html', {'playlists': playlists}) My playlist model is this: from django.db import models class PlayList(models.Model): type = models.PositiveSmallIntegerField(choices=type_choice, default=1, verbose_name='نوع فیلم') category = models.ManyToManyField(Category, related_name='Playlists', verbose_name='دسته بندی و ژانر') name_en = models.CharField(max_length=55, unique=True, verbose_name='نام انگلیسی') name_fa = models.CharField(max_length=55, unique=True, verbose_name='نام فارسی') summary = models.TextField(max_length=1024, verbose_name='خلاصه فیلم') imdb_score = models.FloatField(default=0, verbose_name='IMDB امتیاز') users_score = models.FloatField(default=0, verbose_name='امتیاز کاربران') # seen_number = models.FloatField(default=0, verbose_name='تعداد نفراتی که فیلم را مشاهده کرده اند') publish_status = models.CharField(max_length=55, null=True, blank=True) is_free = models.BooleanField(default=False, verbose_name='رایگان است') visit_times = models.IntegerField(default=0) play_times = models.IntegerField(default=0) year = models.CharField(max_length=4, verbose_name='سال') time = models.CharField(max_length=55, verbose_name='مدت زمان فیلم') tv_pg = models.PositiveSmallIntegerField(choices=tv_pg_choice, default=5, verbose_name='درجه بندی سنی') actor = models.ManyToManyField(Actor, blank=True, verbose_name='بازیگران') director = models.ManyToManyField(Director, blank=True, verbose_name='کارگردان') thumb_image = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر انگشتی فیلم') image_1920x1080 = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر بنر دسکتاپ فیلم') image_600x810 = models.ImageField(null=True, blank=True, editable=True, upload_to=image_path, verbose_name='تصویر بنر موبایل فیلم') country = models.ManyToManyField(Country, verbose_name='کشور') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) users_score_n = models.IntegerField(default=0) users_score_p … -
Unable to perform conditional redirect from a class based view Django
I am trying to redirect a user who has already registered to a different view. here is the code for the views.py However when qs.exists() = true I get an error 'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.' I am a beginner have read the documentation but unable to find where i am going worng. Thanks from django.shortcuts import render, redirect from django.views import View from Lpage.forms import SubscriberEntryForm from Lpage.models import Subscriber class homeview(View): def get(self,request): msg = request.session.get('msg', False) if(msg): del(request.session['msg']) return render(request,'Lpage/index.html') def post(self, request): form = SubscriberEntryForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) qs = Subscriber.objects.filter(email__iexact=obj.email) if qs.exists(): return redirect('messageview') else: obj.save() request.session['msg'] = "msg" return redirect(request.path) def messageview(request): return render(request,'Lpage/messages.html',{}) -
How to does not include default values in calculations in django?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but the problem is that I can't set these both field default=Null cause I am using it in Gig order and views. so I set them as default=timezone.now. but now I want when I calculate average completion time it should not include that fields which are initialized automatically by default. Models.py class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.annotate( _average_completionTime=Avg( ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField()) ) … -
How can i pass an form instance to another form while both are saving Django?
Info: I have a python Django web app where users are allowed to create articles. Each article has multiple files(photos/videos) that are associated with that article. I have three model TemporaryUpload(1), TemporaryUploadChunked(2) and StoredUpload(2). Everything is working fine. first Data is asynchronously uploaded to TemporaryUpload before submitting the form. after hit form submit button data stored into StoredUpload table. This is working perfectly for me! Now What i want to do: When the user hit submit button article is create and files are linked with the article Which files are submited by user into StoredUpload. how can i associate these file with article when user hit submit button? What I have so far: i have ArticleModel/ArticleForm. when the user hit submit button The article created and the files are appended into StoreUpload table it's working fine. But the files are not linked it with an article. i want to link the files with artcle. models.py class TemporaryUpload(models.Model): FILE_DATA = "F" URL = "U" UPLOAD_TYPE_CHOICES = ( (FILE_DATA, "Uploaded file data"), (URL, "Remote file URL"), ) upload_id = models.CharField( primary_key=True, max_length=22, validators=[MinLengthValidator(22)] ) file_id = models.CharField(max_length=22, validators=[MinLengthValidator(22)]) file = models.FileField(storage=storage, upload_to=get_upload_path) upload_name = models.CharField(max_length=512) uploaded = models.DateTimeField(auto_now_add=True) upload_type = models.CharField(max_length=1, choices=UPLOAD_TYPE_CHOICES) … -
I am developing library management system in Django I don't know how should I store the data?Please reply [closed]
I am developing library management system in Django, I didn't want to host the website online ***Now how should I store the data of the website if I didn't host the website I am using a database but how will the librarian run the website as he doesn't know how to run commands like "python manage.py runserver" *** As there any way so that I can create the website for library without hosting online and run the website easily -
How to execute tasks sequentially in celery based on a parameter?
I am currently working on a data polling app in which we have some 600-700 different data sources. We have a client installed at every source location which periodically collects data and sends a CSV file to the server. At server, we receive the CSV and process the data later using celery tasks. We have currently 10 celery workers running on the server which handle one file each simultaneously. Although, we do want this concurrency yet we would also like to implement celery in such a way data files from one source should always be processed sequentially. That means, if the files are from same data source 2nd file should always be processed only after 1st file is completely processed. Does celery provide such an option or I need to build some custom queue management solution? Note: I am currently using Celery with Django. -
Deploying React - django apps on Azure web apps
Locally, I am able to run my django app and react app. I migrated the django app to the azure web apps. My question is, what is best practice regarding connecting the react app to the django app. Should I start another web app instance, or should I try to run both on the same instance? -
Usage of Django models
[This is the django admin page][1] [This is the error that came][2] [Django code][3] Hello, i tried to create products in the admin side of django server using models, i put the picture of what i typed and what error i got , can u help?This is the code i typed in models.py # Create your models here. class Product(models.Model): Name = models.CharField(default='This product is not nameless', max_length=100) price = models.DecimalField(decimal_places=2,max_digits=100) description = models.TextField(default='Hello!') summmary = models.TextField(default='Access level is low') ``` [1]: https://i.stack.imgur.com/P6zcT.png [2]: https://i.stack.imgur.com/hXnDw.png [3]: https://i.stack.imgur.com/bjNNB.png -
Python: Access second parent's instance attribute
I have class which inherits from 2 classes, but in child class instance I cant access second parent's instance attribute, here is my code example class Parent1: def __init__(self): self.a = 'a' class Parent2: def __init__(self): self.b = 'b' class Child(Parent1, Parent2): pass instance = Child() print(instance.a) print(instance.b) # here is error is there actually clean way around?. P.S: What i am actually doing is in django. In views I want to put extra parent class which will add some attributes to the view class instance class ContextMixin: def __init__(self): self.context = { 'data': None, 'message': None } # and in all/some views do like that class LoginView(APIView, ContextMixin): def post(self, request): # use self.context instead of creating each time pass -
How to get the value of a hidden input field in a Django view?
I have a form which has a hidden field like below: <form id = "subscribe" form method = 'POST'> {% csrf_token %} <textarea id = "first_name" type = "text" name = "first_name" rows="3"></textarea> <input id="page_url" name="page_url" value={{ request.build_absolute_uri }}{{ object.get_absolute_url }}> <button type="submit" value = "Subscribe" id = "email_submit">Send</button> </div> </form> I am trying to get the value of the hidden field. Specifically, what I want is the URL of the current webpage. My view function looks like this: def subscribe(request): if request.method == 'POST': firstname = request.POST.get('first_name') pageurl = request.POST.get('page_url') print('page url', pageurl) return HttpResponse("/") As you can see I am trying to get the URL via request.POST.get('page_url') but all I am getting is a None value. I need to get the value of {{ request.build_absolute_uri }}{{ object.get_absolute_url }} instead. -
Docker/Django - How to make sure that all migrations are completed bofor application start?
at my dockerized Django application I have the following bash function at my docker-entrypoint.sh. This basically only checks if the database is available: function check_mariadb { while ! mysqladmin --user=$MYSQL_USER --password=$MYSQL_PASSWORD --host $MYSQL_HOST ping --silent &> /dev/null; do echo "Waiting for MariaDB service to become available" sleep 3 done echo "MariaDB is up and available" } As my application can start in 3 modes (as application, Celery_worker or Celery_beat) I somehow have to make sure that all migration are done before celery starts. Otherwise I'm running into issues that celery is missing one of these tables: django_celery_results_chordcounter django_celery_results_groupresult django_celery_results_taskresult Can somebody give me a hint what might be the best practices to check for open migration in this context? And only let celery start if all migrations are done?!... Would be awesome if this could also be handled in a simple bash function like the one above. Would be awesome If I could do more than just: python manage.py showmigrations | grep '\[ \]' Thanks in advance. -
requests_html + Django "There is no current event loop in thread 'Thread-1'."
Good, I have in Django this configuration in urls.py: urlpatterns = [ path('', views.index), ] and in views.py the index function where I pass through the variable a url, I have with requests_html: def index(request): url = request.GET.get('url') session = HTMLSession() resp = session.get(url) resp.html.render() RuntimeError: There is no current event loop in thread 'Thread-1'. But I get a bug when calling render() and I'm not using threads, any ideas? -
django get the file from temporary_file_path
in my django project user can upload multiple video files. if the extension of these files is .mp4 there is no problem of displaying them in video tag in browser but the problem with .mov files (video tag doesn't support .mov) so i change the extensions of .mov files: # views.py videos = request.FILES.getlist('videos') for v in videos: extension = os.path.splitext(v.temporary_file_path())[1].lower() if extension == '.mov': #change the extension of file mp4_path = os.path.splitext(v.temporary_file_path())[0] + '.mp4' Media.objects.create(user=request.user, videos=file_from_mp4_path) else: Media.objects.create(user=request.user, videos=v) the question is how can i get the file from temporary path and create the Media object -
I want to show some data from another website on my website using react
I have a project to get data from a django webserver and show them in my website using react.js any Idea? -
Django - Retrieve all manytomany field objects related to a specific model
I have my models reviews and news, both having a manytomany relation with Category model. Now I want to get all the categories associated with only one of these two models. For example, to get all categories associated with News model, I tried querying database with News.categories.all() but got AttributeError: 'ManyToManyDescriptor' object has no attribute 'objects'. News Model: class News(models.Model): ... categories = models.ManyToManyField("articles.Category", related_name="news") ... Reviews Model: class Reviews(models.Model): ... categories = models.ManyToManyField("articles.Category", related_name="reviews") ... -
Running Celery Celery as a Service Fails to Read Environment Variables on Ubuntu
I have completed my Django project and was looking to deploy to it. Since the project runs celery, it needed to be a daemonized to run after reboots automatically. I am able to run celery in a cmd line window and since i have setup a bunch of environment variables it is able to detect them all. (vuenv) vue@server:/home/dushyant/server/appdir/app$ celery -A appname worker --loglevel=INFO This is BASE Directory /home/dushyant/server/appdir/app Env Var: SK Exist Env Var: ENV Exist Current Environment is production Env Var: DB_PASS Exist Env Var: DB_PASS Exist This is static Root Directory /home/dushyant/server/appdir/app/static/ This is Media Root /mnt/mediadir/media/ Env Var: SERVER_EMAIL Exist Env Var: SERVER_EMAIL Exist Env Var: EMAIL_PASS Exist [2021-09-28 18:47:32,648: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' -------------- celery@server v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- Linux-5.11.0-27-generic-x86_64-with-glibc2.29 2021-09-28 18:47:32 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: app:0x7fd24f21fa90 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Changed app names and directories … -
Restrict .env file from apache
Let me first explain the requirement, I am hosting a Django project on centos and need to restrict .env from the URL. Sample URL :- https://example.com/.env I get 404 when accessing .env from the browser, but I need 403. When trying with debug enabled I get the below error details Page not found (404) Request Method: GET Request URL: http://example.com/403.shtml Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: ^sitemap\.xml$ ^admin/ ^blogs/ ^comments/ ^ckeditor/ ^list/$ [name='blog'] ^$ [name='recent-blogs'] ^all/$ [name='all'] ^media\/(?P<path>.*)$ The current path, 403.shtml, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Below is my apache configuration ProxyPassMatch ^/static ! ProxyPassMatch ^/media ! ProxyPassMatch ^/.well-known ! Alias /media /home/userdir/dir/dir/dir/media Alias /static /home/userdir/dir/dir/dir/assets Alias /.well-known /home/userdir/public_html/.well-known ProxyPreserveHost On ProxyPass / http://127.0.0.1:9173/ I tried some StackOverflow pages and other, but could not find an accurate solution. Can someone help me here? -
How to enforce uniqueness with NULL values
I have a model with a non-nullable CharField and 2 x nullable CharField: class MyModel(models.Model): name = models.CharField('Name', max_length=255, null=False) title = models.CharField('Title', max_length=255, blank=True) position = models.CharField('Position', max_length=255, blank=True) I want to ensure that name, title, and position are unique together, and so use a UniqueConstraint: def Meta: constraints = [ models.UniqueConstraint( fields=['name', 'title', 'position'], name="unique_name_title_position" ), ] However, if title is None then this constraint fails. Looking into why, this is because you can insert NULL values into columns with the UNIQUE constraint because NULL is the absence of a value, so it is never equal to other NULL values and not considered a duplicate value. This means that it's possible to insert rows that appear to be duplicates if one of the values is NULL. What's the correct way to strictly enforce this uniqueness in Django? -
Python: Django: How to run django app using a python script
I've a python file named "config.py" which actually checks the ip of user and run the django server on that port accordingly. The method I used there was to create a batch file using python and execute it later. import socket import subprocess x = socket.gethostbyname(socket.gethostname()) x = str(x) with open("run.bat", "w") as f: f.write(f'manage.py runserver {x}:0027') subprocess.call([r'run.bat']) But this method is not very effective. I want a way like: import something something.run("manage.py") or something accordingly Kindly Help me doing this -
Django isn't able to send emails but can login into my gmail acc
My Django app is able to log in into my Gmail account, but it is not sending emails. I know it logged in because I tried sending an email to a non-existing email-address and Gmail gave me this error. Even looked in my spam folders but nothing :( However, when I manually send an email, it works properly. This is my SMTP configuration in settings.py settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') I even tried hard-coding and changing the sender's email, but still no result. I wasn't getting this error a few days before, but for some reason it does seem to be working now. By the way, I'm using this for password reset functionality. -
Nginx Config for 2 django applications 2 different endpoints 1 server host
So the problem is I have 1 ip (127.0.0.1 for example) on my server lives 2 different django applications 1. /api 0.0.0.0:8000 2. /data 0.0.0.0:8090 3. / this will go to default pages served up by nodejs I need to figure out the nginx configuration of how to deploy these separate services, each with its own database. when navigating if an endpoint is hit, it will be routed to the appropriate app otherwise it will default to the nodejs app. extra info: when logging into /api/admin/ it gets routed to /admin and fails please take into consideration redirections made by django. I have tried a lot of things including setting Host, or Location This will be a bounty so happy hunting. -
How to use "Order" with prefetch_related to join other table values at once?
class Order(models.Model): user = models.ForeignKey(Account, on_delete=models.DO_NOTHING, related_name='orders') class Invoice(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='invoices') class Flight(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='flights') class Hotel(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='hotels') -
how to decode base64 data into image django - js
im trying to save captured image ( encoding data) into database from canvas , but it only saves a blank image ? here is my code const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const imgFormat = canvas.toDataURL(); docs.value = imgFormat const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} <input type="text" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" width=320 height=240></canvas> <button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button> </form> and here is my views.py with models.py class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py import base64 from django.core.files.base import ContentFile @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': data = request.POST.get('documents') format, imgstr = data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) if data: photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj,'form':images}) i much appreciate your helps , please if you know something about it let me know … -
Factory boy RecursionError: maximum recursion depth exceeded
I have 2 models, django User model and Employee class Employee(TimeStampedModel): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="employees") first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) email = models.EmailField(validators=[email_regex], max_length=255, blank=True) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="employee") 2 factories: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User employee = factory.RelatedFactory( "control_room.tests.factories.EmployeeFactory", factory_related_name='user' ) first_name = fake.first_name() last_name = fake.last_name() username = factory.Sequence(lambda n: "user_%d" % n) email = fake.ascii_email() class EmployeeFactory(factory.django.DjangoModelFactory): class Meta: model = Employee creator = factory.SubFactory(UserFactory) first_name = fake.first_name() last_name = fake.last_name() phone = "+88005553535" email = fake.ascii_email() user = factory.SubFactory(UserFactory) so Employee model has 2 relations to User model (ForeignKey - creator and OneToOneField - user) when I create Factory boy models I get: RecursionError: maximum recursion depth exceeded How do I avoid this error? -
Save multiple objects with same unique value in Django
here's my problem. I have a view where I'm saving a formset of answers, I want it later to be possible to group those answers somehow. I have a couple ideas, for example I can make a model (AnswersGroup) and add a field to my Answer model, which would be foreignkey to AnswersGroup. Then I can create a new AnswersGroup instance in mentioned view and set Answer's AnswersGroup field to created object's pk, but I'm not sure if this is the best way to solve my problem. I also can add an IntegerField to my Answer model and calculate the next value for this field in my view, again, it looks too complicated. Maybe there's some kind of best practice for this kind of problem?