Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create seperate POST request for imagefield in DRF
I need to make seperate api for imagefile. How can I acieve this??? models.py class Organization(models.Model): code = models.CharField(max_length=25, null=False, unique=True) name = models.CharField(max_length=100, null=False) location = models.ForeignKey(Location, on_delete=models.RESTRICT) description = models.TextField() total_of_visas = models.IntegerField(null=False, default=0) base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT) logo_filename = models.ImageField(upload_to='uploads/') serializers.py class OrganizationSerializer(serializers.ModelSerializer): location = serializers.CharField(read_only=True, source="location.name") base_currency = serializers.CharField(read_only=True, source="base_currency.currency_master") location_id = serializers.IntegerField(write_only=True, source="location.id") base_currency_id = serializers.IntegerField(write_only=True, source="base_currency.id") class Meta: model = Organization fields = ["id", "name", "location", "mol_number", "corporate_id", "corporate_name", "routing_code", "iban", "description", "total_of_visas", "base_currency", "logo_filename", "location_id", "base_currency_id"] def validate(self, data): content = data.get("content", None) request = self.context['request'] if not request.FILES and not content: raise serializers.ValidationError("Content or an Image must be provided") return data def create(self, validated_data): .... def update(self, instance, validated_data): .... views.py class OrganizationViewSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer lookup_field = 'id' urls.py router = routers.DefaultRouter() router.register('organization', OrganizationViewSet, basename='organization') urlpatterns = [ path('', include(router.urls)), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I don't have idea to make post request for image field from postman?? I am stucing here long time. Any help appreciable,.. -
Django Celery: Clocked task is not running
In a Django app, I have a form that schedules an email to be sent out. It has four fields: name, email, body, send_date. I want to dynamically create a Celery task (email) to run another Celery task at the designated time. I have been able to send out the email at regular intervals (every 30 seconds) based on the form using the following code: schedule, _ = IntervalSchedule.objects.update_or_create(every=30, period=IntervalSchedule.SECONDS) @shared_task(name="schedule_interval_email") def schedule_email_interval(name, email, body, send_date): PeriodicTask.objects.update_or_create( defaults={ "interval": schedule, "task": "email_task" }, name="Send message at interval", args=json.dumps(['name', 'test@test.com', 'body']), ) However, when I have tried to schedule a task to run at a specific time (3 minutes later from the current time) via ClockedSchedule, Celery beat records the tasks and saves all the relevant settings. However, it never actually sends an email. clocked = ClockedSchedule.objects.create(clocked_time=datetime.now() + timedelta(minutes=3)) @shared_task(name="schedule_clock_email") def schedule_email_clocked(name, email, body, send_date): PeriodicTask.objects.create( clocked=clocked, name="Send message at specific date/time", task="email_task", one_off=True, args=json.dumps(['name', 'test@test.com', 'body']), ) I eventually want to dynamically set the clocked field based on the datetime the user enters into the form, so the current code is just trying to test out the way Celery works. I think I'm missing something about how this works, though. … -
Django admin/base.html page override not working
i overridde admin/base.html, changed the order of displaying applications using templatetag, everything works locally, but when I run it from docker, overriding does not work Django==2.2.16 Project structure: my_project/ |-- new_app/ |-- templates/ |-- admin/ |-- base.html settings: TEMPLATE_ROOT = os.path.join(BASE_ROOT, 'templates') TEMPLATE_DIRS = ( TEMPLATE_ROOT, ) INSTALLED_APPS = ( 'django.contrib.admin', ... 'new_app', ) docker-compose: web_app: build: . command: bash -c "python manage.py migrate --no-input && python manage.py collectstatic --no-input && gunicorn invivo.wsgi:application --bind 0.0.0.0:8000 --timeout 600 --workers 3" restart: always volumes: - .:/project - ./static:/static - ./media:/media ports: - 8000:8000 depends_on: - db env_file: - .env -
Tried to use template inheriteance but getting error all the time
I'm trying to inherit index.html and form.html from base.html. But all the time I'm undone. Please give me a solution. I'm learning Django, new in this field. Thanks in advance -
Django ORM, parent and child connecting
Django ORM G'day all, Hope everyone is well. I have two tables I'm looking to join and struggling to join in a particular way. I could easily join them with SQL but rather I would want to do it using Django. Models below; Child: class employee(models.Model): client = models.ForeignKey(client, on_delete=models.CASCADE) mySharePlan_ID = models.CharField(max_length=10, unique=True) payroll_ID = models.CharField(max_length=100) first_name = models.CharField(max_length=155,) middle_name = models.CharField(max_length=155,null=True, blank=True) last_name = models.CharField(max_length=155) TFN = models.IntegerField(null=True,blank=True) subsidary = models.CharField(max_length=155,null=True, blank=True) divison = models.CharField(max_length=155,null=True, blank=True) job_title = models.CharField(max_length=155,null=True, blank=True) tax_rate = models.FloatField(null=True,blank=True) hire_date = models.DateField(null=True,blank=True) terminiaton_date = models.DateField(null=True,blank=True) termination_reason = models.CharField(max_length=155, blank=True) rehire_date = models.DateField(null=True,blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) class Meta: unique_together = ('client', 'payroll_ID',) def __str__(self): full_name = "Payroll ID: " + self.payroll_ID + ", " + self.first_name + " " + self.last_name return full_name Parent: class offer_eligibility(models.Model): offer = models.ForeignKey(offer,on_delete=models.CASCADE) employee = models.ForeignKey(employee,on_delete=models.CASCADE) amount_offered = models.PositiveBigIntegerField() created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) Any employee can have many offers. I'm trying to create a view that shows a list of employees who are in a selected offer and if they have any amount_offered. This requires me to first filter the offer_eligibility by the offer, I have this queryset. … -
Django, How to call Python script outside of views.py or without reloading page
Here is basically what I have been trying to accomplish all day... use input element to pass argument to my python script run python script to pull data from another website (get request) update sql with data output data in elements on same html page I've had some success just using views.py, but I would rather not refresh the page or route to a new page. Maybe there is a way using views.py without causing that to occur? Any solution/example of how to do this would be greatly appreciated! -
Login with Google redairecting on conformation page to continue Django
I am trying to integrate Google Authentication into my login page. I am working in Django. I have added login with Google Button on my login page, but when I click on that button, I am redirecting to accounts/google/login where it's asking for conformation to continue and menu with sign-in and sign-out. But what I want is when I click on the button it should ask for accounts to login instead. This is my login screen: This is what I get on click on the button: this is my button login code in HTML: Login.html: {% if user.is_authenticated %} <p>Welcome, You are logged in as {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}">Login With Google</a> {% endif %} How can I skip this conformation page , it will be glad if anyone can help me out with this thank you. -
style="width: 45px !important" in Django not works
I'm using django to make a web site. When I render<img src="{{ board.writer.profile_photo.url }}" width="45px" height="45px" style="width: 45px !important; border-radius: 50%;"/> this html, the style="width: 45px;" part changes into style="width: 100%. I have no idea why this happens. screenshot from chrome devtool I'm using python3.8, django 4.0.1 on Ubuntu 20.04. -
django custom validators function?
I have a model named X which has a STATUS_CHOICES = ( (STATUS_A, 'A'), (STATUS_B, 'B'), (STATUS_O, 'Other'), ) and the field name status = models.CharField(max_length=48, choices=STATUS_CHOICES) here i am trying to write a custom validator to for a spreadsheet when uploaded to check for the value that should return only the STATUS_CHOICES and any other value it should return error how should i write ? validators.py from app.model import X def validate_A_or_B(value): return value in dict(X.STATUS_CHOICES).values() is this correct? -
How can I use dash_bio 1.0.1 with Python and Django?
I have a website built with Python and the Django web framework. Currently, I pass the Dash applications to the html with Plotly_app but that does not work when I pass in a dashbio.igv. How can I make this functionality work? Attempting to use these examples and pass them to the front end. https://dash.plotly.com/dash-bio/igv Any help is greatly appreciated in advance, thank you. -
How to ensure fetch GET request runs after database updated?
I am having trouble ensuring that my GET request in Javascript runs after my PUT. Sometimes the JSON promise returns with updated data sometimes it does not! It appears to be random. It always displays correctly upon page reload. I am getting a "Fetch failed loading: PUT" error in my console despite the database being updated successfully. I know of await/async but was unclear if this was my solution and if so how I would implement with the correct syntax. Here is my JS: function like(id) { like_button = document.getElementById(`like-button-${id}`); if (like_button.style.backgroundColor == 'white') { fetch(`/like/${id}`, { method:'PUT', body: JSON.stringify({ like: true }) }); like_button.style.backgroundColor = 'red'; } else { fetch(`/like/${id}`, { method:'PUT', body: JSON.stringify({ like: false }) }); like_button.style.backgroundColor = 'white'; } fetch(`/like/${id}`) .then(response => response.json()) .then(post => { like_button.innerHTML = post.likes; }); } In case it is helpful here is my view in views.py: @csrf_exempt def like(request, id): post = Post.objects.get(id=id) user = User.objects.get(username=request.user.username) if request.method == "GET": return JsonResponse(post.serialize(), safe=False) if request.method == "PUT": data = json.loads(request.body) print(data.get("like")) if data.get("like"): post.Likes.add(user) else: post.Likes.remove(user) post.save() return HttpResponse(status=204) Thank you in advance for your help! -
Limiting choices on forms field DJANGO, leaving them as they were?
I have a following problem, and would appreciate some help: the question is on the bottom :) #models.py class Task(models.Model): worker_on_task = models.ForeignKey(User, related_name='task', on_delete=models.CASCADE, blank=True, default=User) #forms.py class ChageTaskStatusForm(forms.ModelForm): STATUSES = ( ('S2', 'In progress'), ('S3', 'Problem with'), ('S4', 'Finished'), ) status = forms.CharField(max_length=25, widget=forms.Select(choices=STATUSES)) class Meta: model = Task fields = ['status'] And most important: def task_details(request, pk): form = ChageTaskStatusForm(request.POST) task = get_object_or_404(Task, pk=pk) worker = get_object_or_404(User, id=request.user.id) if request.method == 'POST': if form.is_valid(): form.save() context = { 'task': task, 'form': form, } return render(request, 'usertask/task_details.html', context) I have many other fields in Task model, but I want to change only one, (status), but I get following error: IntegrityError at /4/task_details/ (1048, "Column 'worker_on_task_id' cannot be null") Request Method: POST Request URL: http://127.0.0.1:8000/4/task_details/ Django Version: 3.2.11 Exception Type: IntegrityError Exception Value: (1048, "Column 'worker_on_task_id' cannot be null") What am I missing? :/ -
I cant delete my quotes in Django? Python
Ive created a Django project where people can enter quotes by different authors. I cant figure out why Im not able to delete quotes on the same page. The user should be able to delete there own quotes <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Main</title> </head> <body> <header> <h1>Welcome, {{request.session.greeting}}</h1> <a href='/Edit_Account'>Edit My Account</a> <a href='/logout'>Logout</a> </header> {% for quote in quotes %} <p>Posted on: {{review.created_at}}</p> {% if quote.user.id == request.session.user_id %} <a href='reviews/{{quote.id}}/delete'>Delete this quote</a> {% endif %} <li>{{quote.author}} {{quote.quote}}</li> <a href="/like/{{quote.id}}">Like Quote</a> <p>{{ quote.user_likes.count }}</p> <p>(Posted by </a><a href='/users/{{quote.user.id}}'>{{quote.creator.first_name}}) </a></p> {% endfor %} {% for message in messages %} <li>{{message}}</li> {% endfor %} <h2>Add A Quote!</h2> <form action="quote/create" method="POST"> {% csrf_token %} <label for="author">Author</label> <input type="text" name="author"> <label for="quote">Quote</label> <input type="text" name="quote"> <button type="submit">Submit</button> </form> </body> </html> def delete_quote(request, review_id): quote = Quote.objects.get(id = quote_id) if quote.user.id == request.session['user_id']: quote.delete() else: messages.error(request, "This isn't yours to delete.") return redirect(f'/main') -
How can I fix the dash bio error: devtools cannot load source map dashbio@1.0.1 bundle.js.map?
I am implementing a website in Python with Django framework and using django-plotly-dash to display data. I am trying to use dash_bio's IGV feature to display some chromosome data, but when I attempt to call the functionality, I receive the following errors and the callback that returns 'dashbio.igv' is unable to execute. The errors displayed in the console: HTML code receiving the Dash app with the dashbio.igv call: line 20 is where the dash object is returned and dashbio.igv goes. {% plotly_app name=igv_app_name %} This is the python file that returns the dashbio.igv in callback: from dash import html, dcc from dash.dependencies import Input, Output import dash_bio as dashbio import pandas as pd import io import plotly.express as px from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views.generic import DetailView from django_plotly_dash import DjangoDash from django.contrib import messages from .models import vcf_job class IgvView(DetailView): template_name = "rdr/igv.html" model = vcf_job context_object_name = "igv" def get(self, request): igv_app_name = 'igv_app' igv_app = DjangoDash(igv_app_name) HOSTED_GENOME_DICT = [ {'value': 'mm10', 'label': 'Mouse (GRCm38/mm10)'}, {'value': 'rn6', 'label': 'Rat (RGCS 6.0/rn6)'}, {'value': 'gorGor4', 'label': 'Gorilla (gorGor4.1/gorGor4)'}, {'value': 'panTro4', 'label': 'Chimp (SAC 2.1.4/panTro4)'}, {'value': 'panPan2', 'label': 'Bonobo (MPI-EVA panpan1.1/panPan2)'}, {'value': 'canFam3', 'label': 'Dog … -
Is there any way to redirect to a view from a separate view with arguments for that view function in Django?
I cannot for the life of me find a way to redirect to another view with arguments for that view in Django. I've tried the django.shortcuts redirect method, but that doesn't seem to work (it seems to want to take patterns for the url pattern and not the view function. The HttpResponseRedirect function obviously doesn't work because that function just redirects to another url. What other options are there? -
Django manual migration to add group
I am attempting to create a migration that will automatically add a group and permissions to the group when it is run. I adapted some code from the docs and an example. I can get the migration to add the group but not the permissions. I am getting the following error: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. I am not sure how to implement this suggestion. Any ideas? The migration: from django.db import migrations, models from django.contrib.auth.models import Group, Permission from django.contrib.auth.management import create_permissions def add_group_permissions(apps, schema_editor): for app_config in apps.get_app_configs(): create_permissions(app_config, apps=apps, verbosity=0) # Employee group, created = Group.objects.get_or_create(name='Employee') if created: permissions_qs = Permission.objects.filter( codename__in=[ 'can_add_how_to_entry', 'can_change_how_to_entry', 'can_view_how_to_entry', ] ) group.permissions = permissions_qs group.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] -
What is the best way to package a Django project to be easily used on multiple local networks?
I have a Django project, which is to be used by multiple clients on their local networks. I don't want each of them to figure out how to setup Django with Apache or nginx, etc. Is there a way of packaging this Django project in production quality so that my clients can easily get it running on their local networks, securely? -
How to use Sqlite string pattern matching from Django?
If I have a CharField in a Django model, and I try to filter it using a string pattern with the LIKE operator, such as: MyModel.objects.filter(text__like='he_lo') Django returns the error: django.core.exceptions.FieldError: Unsupported lookup 'like' for CharField or join on the field not permitted. However, if I use manage.py dbshell to run the raw SQL: select * from myapp_mymodel where text like 'he_lo'; it runs just fine. Why does Django disallow pattern matching in it's ORM even though Sqlite supports it? -
Reverse for 'author_details' with arguments '('',)' not found. 1 pattern(s) tried: ['author_details/(?P<auth_id>[^/]+)/\\Z']
I'm new to python and currently developing a practice app similar to Goodreads just to test and challenge myself. I have reached the part where I created three pages one with a simple list of books with a link to book details where there is a link to the author profile. The link between the book title link and the book details page works--but when I click on the author link on the book details page it gives me an error Reverse for 'author_details' with arguments '('',)' not found. 1 patern(s) tried: ['author_details/(?P<auth_id>[^/]+)/\\Z'] Here is my code. views.py from django.shortcuts import render from .models import Book from .models import BookAuthor from .models import BookGenre def authors_database(request): authors_database = BookAuthor.objects.all() return render(request,'authors_database.html',{ 'authors_database':authors_database }) def book_details(request,book_id): book_details = Book.objects.get(pk=book_id) return render(request,'book_details.html',{ 'book_details':book_details }) def author_details(self,auth_id): author_details = BookAuthor.objects.get(pk=auth_id) return render(request,'author_details.html',{ 'author_details':author_details }) def index(request): return render(request,'index.html',{ }) def discover_books_list(request): discover_books_list = Book.objects.all() return render(request,'discover_books_list.html',{ 'discover_books_list':discover_books_list }) book_details.html {% extends 'layout.html' %} {% block body %} <div class="container"> <div class="row"> <div class="col-md-4"> {% if book_details.book_cover_image %} <img src="{{book_details.book_cover_image.url}}" height="480" width="300" class="img-responsive"> {% endif %}<br> </div> <div class="col-md-8"> <h3>{{book_details}}</h3> <hr> <strong>By: </strong><a href="{% url 'author_details' auth.id %}">{{book_details.book_author}}</a> <br> <strong>Publication date:</strong> {{book_details.book_publication_date}}<br> <strong>In:</strong> {% … -
Serving sveltekit dev under django
I am building a project and I am trying to use sveltekit as front-end and Django as back-end. I am using gunicorn to serve Django and nginx as web-server that proxies to gunicorn. I want to serve sveltekit dev server under Django so that I don't have to add CORS and tweak settings.py to use different settings for production and development. Instead of developing front-end under http://localhost:3000, I want to access it like http://some-project.dev/app which points to Django. Is this possible? -
Contact form on a users personal site that posts to my Django DB?
I am wondering if it is possible to provide users of my django website a copyable HTML form element to put on their own personal website that actually POSTs to my Django database? The idea is to allow a User of my Django app to copy and paste an HTML Contact form into their own personal website with fields such as name, phone, email, notes which will all be fields of a model in my Django app. Basically when visitors of their website fill out the contact form I would like to post it to my Postgres DB in a model such as.. class Lead(models.Model): user = This would be the user on my Django app name... phone... email... notes... Is something that is possible or even safe to do? It would really be a big part of my project to allow for this lead collection. -
I want help in adding an event listener
I'm a django developer not good at javascript. I have a django template i really want to use Javascript for. i tried reading online for help but i'm not understanding I want to add an addEventlistener to this code below <div class="box-element hidden" id="request-info"> <button id="send-payment">Send request</button> Also, I want it to display a response when submitted. Response like "Request sent". Please I know about console.log, I don't want it in console.log. I know JS is really good at this. -
I can't get the notifications by i.d after saving it as a many to many field
I have previously figured out how to send and save notifications by many to many fields to send to users, now i can't specifically call the notifications by current user logged in i.d. Models.py class Notifications(models.Model): id=models.AutoField(primary_key=True) sent_to = models.ManyToManyField(CustomUser) message = models.TextField(null=True) message_reply = models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) The notifications_sent_to is the created table after I created the many to many save Views.py def add_notification(request): notifs = Notifications.objects.all() users = CustomUser.objects.filter(is_staff=True) if request.method == 'POST': form = AddNotifForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.message_reply = "none" instance.save() form.save_m2m() sent_to = form.cleaned_data.get('sent_to') messages.success(request, f'Message has been successfully sent .') return redirect('add_notif') else: form = AddNotifForm() context={ 'notifs' : notifs, 'form' : form, 'users' : users, } template_name ='main-admin/add-notif.html' return render(request, template_name, context) Forms.py class AddNotifForm(forms.ModelForm): sent_to = forms.ModelMultipleChoiceField( queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Notifications fields = ['sent_to', 'message'] -
How to insert data from html form into MySQL database using python django
I have created an html form in add_appointment.html and have created database "hospital", table "appointment" in MySQL. I able to view values that I inserted into my database on another html page called view_appointment.html but I do not know how to take html form input from the "add_appointment.html" file and insert it into MySQL database. I searched for a solution everywhere, but I don't see people doing it in python Django, its just php everywhere and python but with flask, if you can help with some link I'll be grateful. (I'm a beginner, in college, doing a project for the first time. I figured it out somehow until now but got stuck here. My project is almost done except this one thing, I promise if someone helps me the day I become good enough I'll try my best to help others as well ) filename: add_appointment.html <!doctype html> <html lang="en"> <head><title>Add Appointment</title></head> <body> <div class="container"> <form id="form" class="form"> <div class="from-control"> <h1> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Add Appointment</h1> <div class="form-control"> <label for="username">Name</label> <input type="text" id="name" placeholder="Enter name"> <small>Error Message</small> </div> <div class="form-control"> <label for="email">Email</label> <input type="text" id="email" placeholder="Enter email"> <small>Error Message</small> </div> <div class="form-control"> <label for="id">ID</label> <input type="text" id="id" placeholder="Enter ID"> <small>Error Message</small> </div> … -
Cannot add "<Model: Model object (None)>": the value for field "field" is None
I am trying to save an object to my database while adding it to the Many to Many field of another object. I already tried many other solutions from here but nothing worked so far. Model: class SellerPost(models.Model): post_uuid = models.UUIDField(default=uuid.uuid4, editable=False) seller = models.ForeignKey("User", on_delete=models.CASCADE) text_content = models.TextField() comments = models.ManyToManyField("SellerPostComment", blank=True) class SellerPostComment(models.Model): comment_id = models.IntegerField(primary_key=True) post = models.ForeignKey(SellerPost, on_delete=models.CASCADE) addressed = models.ForeignKey("User", on_delete=models.CASCADE, null=False, related_name="seller_addressed_comment") commenter = models.ForeignKey("User", on_delete=models.CASCADE, null=False) content = models.TextField() View (i cut everything but the essential part that has sth to do with the error): post = request.POST["post"] post_obj = SellerPost.objects.get(post_uuid=post) comment = comment_form.save(commit=False) comment.addressed = user comment.commenter = request.user comment.post = post_obj comment.save() post_obj.comments.add(comment) return redirect(index) class PostCommentForm(forms.ModelForm): class Meta: model = SellerPostComment fields = ("content",) def save(self, commit=True): comment = super(PostCommentForm, self).save(commit=False) if commit: comment.save() return comment Error: Cannot add "<SellerPostComment: SellerPostComment object (None)>": the value for field "sellerpostcomment" is None The form is valid but it just won't save the comment to the M2M field of the post. Thanks in advance!