Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Celery cannot connect to RabbitMQ server
I am trying to run celery and it is unable to connect to the RabbitMQ server even though I have correctly set the user, vhost and assigned the appropriate tags celery -A proj worker -l info The above command returns the error [2021-09-28 18:05:37,649: ERROR/MainProcess] consumer: Cannot connect to amqp://test:**@12:5672//: timed out. Trying again in 2.00 seconds... (1/100) I have initialized the celery app as follows app = Celery('proj', broker=f'amqp://test:test@12#4@localhost/test_vhost') I believe this is not working because the password test@12#4 has the special characters @ and # in it. How do I get this to work without changing the password. -
Django filter two records and update both at once?
I need to filter two data's and then update each data with different value ! How to do that at once ? x = Tasks.objects.filter(employee=[person1]) y = Tasks.objects.filter(employee=[person2]) Basically am updating count, for instance lets say i have a model named "Employee" and he is assigned to tasks with model named "Task". And whenever admin adds employees to a task - the employee gets to see the count of total task. With this said, i have managed to update the count by "1" when tasks gets added and managed to updated the count by "-1" when its get deleted, but my problem is when tasks gets updated or edited or assigned to another employee ! Now am updating the task using: x.update(total_task=F('total_task') + 1) and again y.update(total_task=F('total_task') - 1) From the above, first i filter each separately and then update separately ! How to combine this in a single query ? -
I am not able to submit the form and put the data in Database in a django website
I am fairly new to jquerry, infact just started learning and using it. I went through some of the questions but none talks about the issue I am facing so here it goes. I have created a website in django. In it i basically make a invoice and put that data into a sql server db and then fetch that data and render it to another html template and then print it from there. earlier i wasnt using a jquerry in the html. that time it worked all fine. now i decided that i will use the jquerry to append rows instead of having a fixed amount of rows. when i started using that it started giving trouble. now my input tag thats set on submit is not submitting the form, or thats what i think is happening. Can someone please help me out here. the following contains my part of the view which is working on this, the html and the urls file. views.py def invoice(request): if request.method == "POST": name_client = request.POST.get('client_name') address_client = request.POST.get('client_address') name_company = request.POST.get('company_name') address_company = request.POST.get('company_address') vessel_name = request.POST.get('vessel_name') po = request.POST.get('po') date = request.POST.get('date') item1 = request.POST.get('product1') cost1 = int(request.POST.get('cost1')) gst1 = … -
django debug toolbar uploaded badly
just starting using Django (first project) and I wanted to install the Django Debug Toolbar. I did exactly as the installation guide in the documentation here said: Django Debug Toolbar Docs- Installation For some reason the page loads like this: The html file that is loaded is a simple but legit one and ill add it here: <html> <body> {% if name %} <h1>Hello {{name}}</h1> {% else %} <h1>Hello World</h1> {% endif %} </body> BTW: Removing the if statements is not working either, also not working on both chrome and firefox. Thanks for the help :) -
Django image is uploaded to server but after showing 500 error without saving image information to db
In my settings `Debug = False Allowed_Host = ['my given host'] STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/images/" MEDIA_ROOT = os.path.join(BASE_DIR, "static/images") in Project Url urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in /etc/nginx/conf.d location /static/ { root /home/pijush/website/ecomerce; } location /images/ { # media files, uploaded by users client_max_body_size 100M; root /home/pijush/website/ecomerce; # ending slash is required } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; }` static files are serving perfectly. When Debug is True in localhost image is uploading and saving image info in model, working perfectly but in production after uploading image its showing 500 error. this is my gunicorn status log POST HTTP/1.0" 500 145 "https://nobann.com/profile/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" -
Why is unique=True not enforced when using create()?
I have a model with a unique charfield: class EmailTemplate(models.Model): name = models.CharField('Name', max_length=255, help_text=_("e.g: 'welcome_email'"), unique=True) When I create 2 models with the same name in Django's admin interface, I get the expected error: Email Template with this Name already exists.. However, if I do this programmatically I do not: >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > What am I missing? I thought unique was a db-level constraint? -
Get all values from queryset using templates
I am trying to retrieve all the queryset data (names and amount) using templates. views.py def get_expense(request): #expenses = list(Expense.objects.values()) expenses = Expense.objects.values('name' , 'amount') if request.method == 'POST': form = ExpenseForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() #print(driver_text) print(type(expenses)) return render(request, 'thanks.html', {'expenses':expenses}) #JsonResponse(expenses, safe=False) # else: form = ExpenseForm() return render(request, 'index.html',{'form':form}) thanks.html: {{ expenses }} I am trying to get all those queryset data listed but instead I am getting: <QuerySet [{'name': 'Home Rent', 'amount': 8000.0}, {'name': 'hjvhjvhv', 'amount': 73.0}, {'name': 'tes', 'amount': 23.0}, {'name': 'dddd', 'amount': 34.0}, {'name': 'qqqqqqqq', 'amount': 56.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'hjvhjvhv', 'amount': 67.0}, '...(remaining elements truncated)...']> I need only the name and amount listed instead of the whole queryset. -
ValueError: Cannot assign "'x'": "x.x" must be a "x" instance
I am trying to create some comments on a venue in my web app but I am mot sure why I am getting this error when I try and pass a venue's id through to make a new comment object models: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=15000) [...] class VenueComments(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=10000) views def add_venue_comment(request): if request.method == "POST": comment = request.POST.get('comment') venue = request.POST.get('venue_id') new_obj = VenueComments() new_obj.venue = venue new_obj.user = request.user new_obj.comment = comment new_obj.save() return JsonResponse([ new_obj.comment, new_obj.user ], safe=False)