Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you drop a specific migration that has no use currently and cause some errors when running tests?
I have a custom migration that is used to create a model object in the DB as a follow-up change, It adds a new option to the DB that was added later after the initial options list was created. I did that for the sake of automation and to avoid adding it manually. Now, a problem arises when running tests, all migrations run and therefore the first migration that creates the updated options list is applied, then that later custom migration is being applied and tries to create and it causes errors. So, my question is how to drop that migration. it was used for production DB to keep up but now it has no use for freshly DBs and causes errors Thank you for your answers and help -
Access data without token Django simple_jwt lib
I am using django simple_jwt library with DRF for a React project. Everything is working well except I cannot access any data (even simple GET requests) if no access token is provided. I didn't find a way to do it in the docs , is there some kind of decorator, setting to allow simple requests without an access token? Many thanks -
Filter by a virtual name in the admin site
Django4.1 class Exercise(NameMixin, UrlMixin, PriorityMixin, CommentMixin): unit = models.ForeignKey('vocabulary_units.Unit', on_delete=models.CASCADE, null=True, ) class Phrase(models.Model): exercise = models.ForeignKey('vocabulary_exercises.Exercise', on_delete=models.CASCADE, null=True, blank=False) @property def unit(self): result = self.exercise.unit return result A phase belongs to an exercise, excercise belongs to a unit. The problem is that in the admin site I'd like to organise for phrases a filter by unit. Is it possible? -
Add styling to form.as_div in Django
I am rendering a model form in Django using {{ form.as_div }} It is rendering as expected as I want each field wrapped in a div. I would now like to add a class to this auto generated div. adding widgets in the forms.py file only adds attribute to the input field itself and not the div around the field. Can someone point me in the right direction to add attributes to the div instead of the input field? Thank you -
how to use pillow module in pyscript to open screenshot with the help of html onclick button?
<button id="button" type = "button" class="btn btn-primary" pys-onClick="run_python"> NEXT </button> <py-script> from PIL import Image op = Element("output") def run_python(*args,**kwargs): image = Image.open("home/saikumar/Desktop/screenshot/selenium1.jpg"/) image.show() </py-script> i am trying to open the screenshot image which is present in my local directory with the help PIL module by clicking button but i am unable open and getting error like file not found and i have to open the screenshot by clicking NEXT button. please help through this. Error case: Uncaught PythonError: Traceback (most recent call last): File "<exec>", line 4, in run_python File "/lib/python3.10/site-packages/PIL/Image.py", line 3068, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 44] No such file or directory: 'home/saikumar/Desktop/screenshot/selenium1.jpg' at new_error (pyodide.asm.js:14:238191) at pyodide.asm.wasm:0xedbcb at pyodide.asm.wasm:0xedccc at Module._pythonexc2js (pyodide.asm.js:14:932707) at Module.callPyObjectKwargs (pyproxy.gen.ts:374:12) at Module.callPyObject (pyproxy.gen.ts:384:17) at PyProxyClass.apply (pyproxy.gen.ts:1145:19) at Object.apply (pyproxy.gen.ts:1022:18) new_error @ pyodide.asm.js:14 $wrap_exception @ pyodide.asm.wasm:0xedbcb $pythonexc2js @ pyodide.asm.wasm:0xedccc Module._pythonexc2js @ pyodide.asm.js:14 Module.callPyObjectKwargs @ pyproxy.gen.ts:374 Module.callPyObject @ pyproxy.gen.ts:384 apply @ pyproxy.gen.ts:1145 apply @ pyproxy.gen.ts:1022 -
How to access other data of foreign key and call them on frontend in django
I have to models Customers and Purchase_order. I am taking customer as a foreign key in purchase invoice and fetching data.. My data is like this: {'id': 5, 'purchase_number': 'TES-PO-1', 'purchase_date': datetime.date(2022, 9, 1), 'customer_id_id': 1, 'special_instructions': '', 'total': '70', 'discount': 2.578125, 'round_off': '77.5', 'grand_total': '78', 'user_id': 1, 'remarks': '', 'company_id': 1} {'id': 6, 'purchase_number': 'TES-PO-2', 'purchase_date': datetime.date(2022, 9, 6), 'customer_id_id': 2, 'special_instructions': '', 'total': '24', 'discount': 0.75, 'round_off': '28.5', 'grand_total': '29', 'user_id': 1, 'remarks': '', 'company_id': 1} Action here I am getting customer id as 1,2,3 its pk value but I wish to call its customer_company there.. how can I access them by its id on frontend? want to show name instead of ID -
Highlight the selected part in the table of contents (htmx)
I use django-htmx to create the table of contents. It works fine, but I can't select the selected part of the table of contents. I understand that it can be done with a url, but I'm shown a different address where the htmx itself is located. And the request.htmx.current_url command outputs a link without the parts in the table of contents. For example, the article is located at example.com/post/harry_potter , if I click on a certain part of the table of contents, the address will already be example.com/post/harry_potter#II. The request.htmx.current_url command gives a link to example.com/post/harry_potter , so I can't check in any way. this is the latest attempt, but it doesn't work <div class="offcanvas-body"> <nav id="navbar-example3" class="h-100 flex-column align-items-stretch pe-4 border-end"> <nav class="nav nav-pills flex-column"> <ul class="list-unstyled fw-normal pb-2 small"> {% for new in table_content %} {% if request.htmx.current_url == new %} <li><a href="#{{new}}" class="bd-links-link d-inline-block rounded nav-link active">{{new}}</a></li> {% else %} <li><a href="#{{new}}" class="bd-links-link d-inline-block rounded nav-link">{{new}}</a></li> {% endif %} {% endfor %} </ul> </nav> </nav> </div> -
Get queryset of related one to one fields
I have 3 models: class BillingNumbering(models.Model): number = models.IntegerField() date = models.DateField(default=now) class Invoice(models.Model): number = models.OneToOneField(BillingNumbering, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class DamageClaim(models.Model): number = models.OneToOneField(BillingNumbering, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) I want to query only those BillingNumbering objects that is connected to either Invoice or DamageClaim. So if I have <BillingNumbering: 1> - connected to invoice <BillingNumbering: 2> - connected to damage claim <BillingNumbering: 3> - connected to None where instance.invoice or instance.damageclaim will result to ObjectDoesNotExist Error. Then I only want to return <BillingNumbering: 1> and <BillingNumbering: 2> with BillingNumbering filter -
when i uses post.get_absolute_url in href i got this error. how fix this?
AttributeError at /blog/ Manager isn't accessible via Post instances Error during template rendering In template C:\Users\Mahdyar Eatemad\OneDrive\Projects\Gallery\templates\blog\post\list.html, error at line 33 Manager isn't accessible via Post instances error i used get_absolute_url to create slug for blog posts This is my models from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'چرک نویس'), ('published', 'منتشر شده'), ) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique_for_date='publish', allow_unicode=True) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') bolded_text = models.TextField(blank=True) picture = models.ImageField(upload_to='photos', blank=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('blog:post_detail', args=[self.published.year, self.published.month, self.published.day, self.slug]) def __str__(self): return self.title my views from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', published__year=year, published__month=month, published__day=day) return render(request, 'blog/post/list.html', {'post': post}) my url from django.urls import path, register_converter from django.urls.converters import SlugConverter from . import … -
Django architecture for different clients/technologies using same models
My team and I are having a hard time defining the architecture for my backend environment using Django. To contextualize a little, we built an application similar to an App Store, for all our developments to be displayed, with the difference that it also launches the apps. To maintain all the information about this apps, we built this backend in Django that is basically a database accessed through an API from the App Store, and a Django Admin website to register the informations to be delivered in the API (the one Django automatically generates). The thing is, today, we have only one technology involved and therefore only one database and one Django Admin. But, other areas in our company want to use this architecture we built, with other apps and therefore other informations, not related to our environment. The question is, should we deploy several Djangos in different ports of our server? Or should we try to create a dependency in our models to a "Technology" related to it? (For this option it is important to note that our architecture is complex and highly nested). Or maybe should we use the multiple databases provided from Django? Has anyone had a … -
Save multiple items in same form django
let say these are the inputs of user, in my view it's well validated form.is_valid(). item code | description | unit | quantity --------------------------------------------------------------- #itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1 #itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2 #itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3 reqeust.POST.getlist('description') return a list -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3'] How can i save all the cells that the user enter to my MaterialIndent model?? just like in myview i could only save the last item only !! # models class MaterialIndent(models.Model): material_indent_id = models.AutoField(primary_key=True) date_request = models.DateTimeField(auto_now_add=True) local_code = models.CharField(max_length=10, default='Local') quotation = models.FileField(upload_to='files/', null=True, blank=True) description = models.CharField(max_length=200) unit = models.CharField(max_length=100) quantity_requested = models.DecimalField(max_digits=12, decimal_places=2) quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True) request_for = models.CharField(max_length=50) requester = models.ForeignKey(User, on_delete=models.CASCADE) priority = models.CharField(max_length=100) status = models.CharField(max_length=50, default='Store Checking') def __str__(self): return str(self.material_indent_id) # form class MaterialIndentForm(ModelForm): class Meta: model = MaterialIndent fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation'] # views def test(request): available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True) if request.method == 'POST': form = MaterialIndentForm(request.POST, request.FILES) if form.is_valid(): length = len(request.POST.getlist('local_code')) post = form.save(commit=False) for r in range(length): local_code = request.POST.getlist('local_code')[r] description = request.POST.getlist('description')[r] unit = request.POST.getlist('unit')[r] quantity_requested = request.POST.getlist('quantity_requested')[r] post.local_code = local_code post.description = description post.unit = unit post.quantity_requested = … -
DJango, custom filter with list_display custom method
I'm trying to filter by the custom method i made for language column. In admin.py i have the following; from django.contrib import admin from .models import * class MovieAdminModel(admin.ModelAdmin): search_fields= ('title_en') list_display = ('get_language',) list_filter = ('get_language') def get_language(self, obj): if obj.language==1: return 'Persian With English Subtitle' else: return 'Persian' get_language.admin_order_field = "language" get_language.short_description = "language" In list_filter i use get_language and this error is returned The value of 'list_filter[0]' refers to 'get_language', which does not refer to a Field. If i use language in list_filter , the filters shows yes or no. Filter should show either Persian With English Subtitle or Persian. How do i solve? -
Scheduling a function in python/django
I have a form and a function. The function will run in exactly 60 seconds after the form has been submitted. N.B. time.sleep() is not an option here #django #python -
CreateView doesn't save object , throws 'this field is required ' error
models.py is : class Todo(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True) title=models.CharField(max_length=200) desc=models.TextField(null=True,blank=True) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['created'] views.py is: class TaskCreate(generic.CreateView): model = Todo fields = '__all__' template_name = 'create.html' success_url = reverse_lazy('home') create.html is: <body> <a href="{% url 'home' %}">go back</a> {{ form.as_p }} <form method="post"> {% csrf_token %} <input type="submit" value="submit"> </form> </body> Whenever I submit data from create.html form it doesn't save it to the database and throws this field is required on 'user' field. How do I resolve this? -
Import Error: cannot import name 'User' from partially initialized module 'auctions.models
class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,blank=True, null=True,related_name='userComment') listing = models.ForeignKey(Listing, on_delete=models.CASCADE,blank=True, null=True,related_name="listingComment") message = models.IntegerField(max_length=200) def str(self): return f"{self.author} comment on {self.listing}" -
how to add if/else statement to base.html?
I'm trying to put the if/else statement to my base.html file. The idea is to have if/else as a part of the template that will be an extension for my HTML files. The problem is, I'm not sure what syntax would look like. Previously, I had an HTML page (called the essay-page) with some content and if/else statement hardcoded to this particular page. But I want to have if/else as a part of my template too, so I could use it with several pages. Essay-page with hardcoded if/else: {% block body %} {% if essay_found %} <article> <img src="" alt=""> <section id="location"> <h2>Other infos</h2> <address>This essay was made in <span>LOCATION</span> (ADDRESS).</address> </section> <section id="details"> <h2>What's this essay about?</h2> <p>{{ essay_description }}</p> <footer> <p>Need more details? <a href="">Please contact me</a> (but don't spam ;))</p> </footer> </section> <section id="registration"> <h2>Send me your request and job offers!</h2> FORM </section> </article> {% else %} <h2>No essay found for this slug, sorry! </h2> {% endif %} {% endblock%} now I try to put this if/else to my base.html (without a success): <main> {% block body %} {% if essay_found %} {% block article %}{% endblock %} {% else %} <h2>No essay found for this slug, … -
Orm Model coonetion to Mysql Database
I'm trying to perform insert and update operations through Django ORM into MySQL Database but I don't know how to do it. Can anyone please help me with this operation? -
Django how to send html-designed email bodies
On my Django project I am trying to send beautiful mails with colorful body and so on. My mail body constructing function looks like the following: def construct_mail_body(): user = User.objects.get(id=1) context = { 'username': user.username, } template = render_to_string('mail/mail_body.html', context=context) message = strip_tags(template) return message mail_body.html: {% load static %} <h3>Hello <span style="color: red;">{{ username }}</span>,</h3> <h3>You've successfully completed our Tutorial!></h3> <h3>Congratulations!</h3> But it doesn't work as expected. My mail bodies looks like: Body 1: Body 2 (Btw, why this happens? Why the mail is in purple?): So how to make HTML tags work properly and is it possible to add some styling properties of css? Thanks! -
What is the original purpose of Django apps? What are the use cases of Django apps?
I'm building a website that'll use a Bootstrap template similar to the image shown below. I intend to add an authentication and authorization functionality using OAuth 2. The main menu will consist of: Homepage link Statistics app link NLP app link Computer vision app link Contacts page link Login button Without using Django, the homepage would just be index.html, the Statistics app would be a statistics.html page which interacts with the backend to show some plots, the NLP app would be an nlp.html page which interacts with the backend to display some NLP processed text and so on. When using Django, how am I supposed to structure it? Should I create a separate NLP Django app, and a separate Statistics Django app and a separate Homepage Django app? I'm already surprised that I had to create an app just to be able to have a homepage, and then had to add path('', include('homepage.urls')), to urlpatterns to redirect / to the homepage app. If I use the Bootstrap template for the homepage app, then how would I share the JS files, the CSS files and other boilerplate files of the template with the other apps of my website? Once the user … -
how to trigger an event of web socket (Django Channels) whenever new object of model has been created via django signals
This is my signal @receiver(post_save, sender=ChannelGroup) def channel_list_signal(sender, instance, created, **kwargs): try: print("signals") channel_layer = get_channel_layer() print(channel_layer) channel_layer.group_send( "channellist", { 'type': 'send_notification', 'message': "Done", }) print("return 'Done'") return "Done" except Exception as e: raise Exception(f"Something went wrong in channel_list signal {e}") This is my consumer class ListChannelConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = "channellist" self.channel_layer = None self.msg = None self.channels = [] # self.connected = False async def connect(self): user_id = self.scope["url_route"]["kwargs"]["user_id"] is_user_present = await check_user(user_id) print(self.channel_layer) # group_id = sender + receiver if is_user_present: self.user_name = is_user_present.username await self.channel_layer.group_add( "channellist", "temp" ) await self.accept() channel = await get_channels(is_user_present.username) await self.send(text_data=json.dumps({ "payload": "connected", "Channels": channel }, default=str)) else: raise Exception(f"User not present in database or private chat does not exists") async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def send_notification(self, event): print(event) event_data = QueryDict.dict(event) channels = event_data.get('message') # Send message to WebSocket self.channels = await get_channels(self.user_name) await self.send(text_data=json.dumps({ "Success": "channels", "message": channels })) What i am trying to achieve is i want to trigger send_notification event whenever i create new channel in my db but when i tried so it is not working actually i try to check the what … -
Map should count distance as per current Address in Django
I am new to Django, and I want to check if the entered address should not be far more than 2 hours from the current location using Map. I am sharing the screenshot of the UI. After adding the complete address I want to check if the entered address is how much far from the current address. and gave alert if addrees is far than 2 hours. I have tried this but not working. from django.contrib.gis.measure import Distance p2 = Event.objects.get(id=3).position for event in Event.objects.all().exclude(id=3).annotate(distance=Distance('position', p2)): print('{0} - {1}'.format(event.id, event.distance.m)) -
Why this ValidationError occur when deleting objects in Django model?
As far as I know, there are two ways to delete an object in the Django admin panel: delete one by one from the screen of each record -> Screen Transition delete items selected with check boxes from the record list screen -> Screen Transition The following ValidationError occurs only when trying to delete with the second way and the object cannot be deleted. (see image below) Please tell me how to fix this error. ValidationError at /admin/my_app_name/schedule/ ['“Oct. 2, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] Below is the code that seems relevant. # models.py from django.db import models from django.utils.timezone import now class ScheduleType(models.Model): choices = ( ('normal', 'normal'), ('am', 'am'), ) schedule_type = models.CharField(max_length=32, choices=choices, primary_key=True) start_time = models.TimeField() end_time = models.TimeField() class Schedule(models.Model): choices = ( ('type1', 'type1'), ('type2', 'type2'), ) date = models.DateField(default=now, primary_key=True) is_working = models.BooleanField(default=True) schedule_type = models.ForeignKey(ScheduleType, on_delete=models.SET_NULL, null=True) service1_type = models.CharField(max_length=32, choices=choices) offer_service2= models.BooleanField(default=True) offer_service3= models.BooleanField(default=True) info = models.CharField(max_length=128, default='This is a normal day.') def __str__(self): return str(self.date) -
TypeError: unsupported operand type(s) for | [closed]
I'm getting the following linting error using Django Q objects: TypeError: unsupported operand type(s) for | The below is my code (it does work but not sure why I'm getting this linting error). Also the error disappears when I remove the third Q object. if request.GET: if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search critera") return redirect(reverse('products')) queries = Q( name__icontains=query) | Q(description__icontains=query) | Q( excerpt__icontains=query) products = products.filter(queries) -
Django + React Ecommerce project [Stripe payment connecting problem]
I've got a problem with Stripe connecting to my e-commerce website based on Django + React. I've got an e-commerce website in that I want to connect Stripe as a payment system. My website has about 200 products so I want to create a system when [Order.TotalPrice] is taken to Stripe (ofc. from the server side) and Payment is done. I care about the most trivial version of the code, because I want to add it to my website. I'aint a professionalist, so I really care of simplicity because of my skills. Thanks.! Thanks, dudes a lot! -
Django Signals pick up instances and choose the right one
I need a custom function based on date for calculations. I want to use signals for that, Plan is, When user updates a date, then the signal looks for everything what has the range of that date and uses the instances within the date range