Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Utils in models: acceptable or not?
Have a look at the static method get_raster_image. Of course it is a utility. class RasterImage(models.Model): raster_original = models.ImageField(upload_to=omnibus.utils.model_utils.UploadManager.get_upload_to, verbose_name=images_general.OriginalsFileNames.RASTER_ORIGINAL.value, validators=[ images.validators.RasterImageValidator. validate_file_name_according_to_pattern, images.validators.FileValidator. validate_if_file_name_already_occupied, ] ) @staticmethod def get_raster_image(an_id: str) -> RasterImage: result = RasterImage.objects.get(pk=an_id) return result To avoid imports I usually use apps.get_model(). I avoid imports like the plague. And frankly speaking, at first I placed get_raster_image in the utils subdir. But then I was afraid: even a possibility of circular import is a nightmare for me. Right now to get an instance of RasterImage I'll have to write: raster_image_model = apps.get_model(app_label="images", model_name="RasterImage") raster_image_model.get_raster_image(an_id=1) But, please, keep in mind that once I had to discard an almost finished project and rewrite it from the scratch. Just because at some late stage a circular import appeared and I failed to cope with it. Could you tell me whether it is acceptable or a complete garbage? What is the correct way to organize such an utility? -
Many to many field form inline add, remove and edit
There are already quite a few questions (1, 2, etc.) about this but without (good) answers. Working code I have one model for an employee and another one for business hours. I want to link them with a many-to-many relationship. For this I would like to create a form to add, remove and edit them. So far, I'm only able to select them from the list of all relationships. models.py class WeekdayHour(models.Model): """Model representing a business hours in for specific weekdays.""" WEEKDAYS = [ (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ] weekday = models.IntegerField(choices=WEEKDAYS) from_hour = models.TimeField() to_hour = models.TimeField() class Employee(models.Model): """Model representing a user employee.""" name = models.CharField(max_length=50) business_hours = models.ManyToManyField('WeekdayHour', through='WeekdayHourEmployee') class WeekdayHourEmployee(models.Model): weekday_hour = models.ForeignKey('WeekdayHour', on_delete=models.RESTRICT) employee = models.ForeignKey('Employee', on_delete=models.RESTRICT) class Meta: unique_together = ('weekday_hour', 'employee') The reason for using the intermediate table is to define the unique together constraint. Next I define the form in the following way. forms.py class EmployeeForm(ModelForm): # define the specific widget for the business hours business_hours = forms.ModelMultipleChoiceField( queryset=WeekdayHour.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Employee fields = ('name', 'business_hours') So far I have a form displaying the business hours that looks … -
Overwrite a Django Material Admin template and keep it inside Project Folder
I'm working with Django Material Admin framework. I want to overwrite a template(example: clearable_file_input.html) and place the overwritten template in the project folder to get the updated functionality of the template while running the project. Where do I need to place that updated template inside the project? What are all the changes (if there is any like updating settings.py file) that I need to do for automatically fetching the updated template but not the original template? Example Scenario: I want to update the functionality of opening a link (of TabularInline Model) when it's clicked. I want to open the link in another tab when it's clicked. So, I got to know that I need to update the clearable_file_input.html and I successfully updated that. Now I need to figure out where do I need to place this file inside my project to get the updated functionality. I don't want to update the original template present in the path: "./local/lib/python3.7/site-packages/material/admin/templates/admin/widgets/clearable_file_input.html" I want to place the updated template in project so that while running the project, the updated template is taken rather than the original template present in the previously specified path. What do I need to do for this functionality to work? -
How to use AJAX based autocompletion with html form and django
I want to do a stock management system in django. I don't have any code yet relevant for the problem I want to ask. So bear with my explaination: I have a working django project with a working REST API. The database for example contains a "Component" model/table that holds all the components that can be stored. The "Stock" Model holds the Stock entries of how many components are stored where. These entries hold a foreign key to the component. Currently I'm trying to make a "new Stock" Form that allows me to create a new entry in the "Stock" table. To specify the component foreign key, I would usually use a dropdown select and let django fill in the possibilities (ChoiceField). Similar to how it's done in the admin panel. The main problem is: The component table is huge: >10000 Entries. I cannot simply add all the possibilities to the webpage. Therefore, I want to use a standard text field (?) with an autocomplete dropdown, that will use the REST API to query the results. However, I do not really find a way to fill out the HTML form. My best guess is to search the components via the … -
Authenticate with Google OAuth2 in unit test in Python Django
I'm working on a Django project that uses Google OAuth2 to authenticate users. It's the first time I work with OAuth2 authentication, so my knowledge of Google OAuth2 is from the resources I found in the web today. In writing unit tests for the application I need to authenticate in it, and I don't know how to do it inside a unittest.TestCase test suit. How to authenticate to the application using Google OAuth2 in unit tests suits? -
Image between text in Django
I'm trying to figure out how I can place an image between text in a blog post in Django. I first thought of using something like the urlize filter ({ blog.body | urlize }) that would allow me to include a link for the image on the text body and then render the image on the post, but alas there is no filter for that. Or at least not that I know of. I then realized it would be much more preferable if I could place the image inside the admin panel itself, in the form of an inline command, like it is done here: https://pythonhosted.org/django-inline-media/ What is an easy implementation of this that wouldn't require me using the whole package there? Any help is greatly appreciated. -
Calling functions in a django app from url
Consider the domain example.content.com. Now I want that content.com part to point to my django web application, and that example part to point to specific functions in my views.py folder, so that I can call different functions in my views.py by changing that example part. Is there any way to achieve this? Any help is appreciated. Thankyou! -
There are 2 same querysets in context for the ListView
I am wondering why there are 2 same querysets in the context: object_list and massage_list. Did I do something wrong? I could find massage_list only in urls path('work/', MassageListView.as_view(), name='massage_list') class MassageListView(ListView): def get_queryset(self): return Massage.objects.filter(time_of_receipt__year=now().year, time_of_receipt__month=now().month) def get_context_data(self, *, object_list=None, **kwargs): context = super(MassageListView, self).get_context_data(**kwargs) month_salary = 0 for i in context['object_list']: month_salary += i.price context['month_salary'] = month_salary context['form'] = MassageForm() print(context) return context printed context {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 'massage_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 'view': <myapp.views.MassageListView object at 0x7f2e166200a0>, 'month_salary': 13800, 'form': <MassageForm bound=False, valid=Unknown, fields=(client;price;count;time_of_receipt)>} -
django REST framework group by in nested model
I am new to django rest framework. i have a nested model for saving orders of a restaurant. now when i send a GET request i get below response; [ { "menu": { "id": 1, "food_name": "food1" }, "user": { "id": 49, "username": "A" } }, { "menu": { "id": 1, "food_name": "food1" }, "user": { "id": 63, "username": "B" } } ] but i want to group users with the same menu like this: [ { "menu": { "id": 1, "food_name": "food1", "users": { "1": { "id": 49, "username": "A" }, "2": { "id": 63, "username": "B" } } } } ] here is my code: models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer serilizers.py class OrderSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() menu = MenuSerializer() class Meta: model = Order fields = ['id', 'user', 'menu'] thanks -
draft.js showing "require is not defined" error when used without a react app
I want to make a react.js component inside my django application which will allow me to 1) have a rich text editor 2) the ability to edit the style of some text when the user types. For the first feature, i don't understand how i need to import EditorState inside my template. It shows this error Uncaught ReferenceError: require is not defined at this line: import {Editor, EditorState} from 'draft-js'; -
How to show backend stream data in the front-end in django
I have a django app that recieve an value from the client and do some processes in the backend and this process takes time and i want to show to the user the live process output. in the backend i'm using subprocess.Popen and then i'm using yield to return stream data. and in the views.py I'm using StreamingHttpResponse() to show stream data. my problem is where, when the process is starting, the live results are shown in the blank page, but i want to show the live data at current page and in a terminal window. and after the process is finished, i want to show the Download button to the user, to download the result as pdf. everything in building PDF file and download page works perfect and my file is builing in the /media directory. and before my problem, i did that and client could download the result pdf. but now, i want to add live-stream to the app to show the process.\ here is my current views.py which run perfect in the new blank page. @login_required(login_url='/login/') def dir_s(request): if request.method == 'GET': return render(request, 'app/dir_s.html', {'form':IpsForm()}) elif request.method == 'POST': try: global ip, user_name, function_name form = … -
Edit form is not showing data of tags with tags input
I am building a Blog App and I am building a tagging functionality in a Blog Post , So I used django-taggit. Then i used bootstrap's tags input library. BUT when I try to edit blogpost with bootstrap's tags input then previously saved tags are not showing, And when I try to show using {{ form.tags }} then they are showing but not in HTML's input tag. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() views.py def edit_blog_post(request,blogpost_id): post = BlogPost.objects.get(id=blogpost_id) user = post.user if request.method != 'POST': form = UpdateBlogPost(request.POST or None, request.FILES or None, instance=post) else: form = UpdateBlogPost(instance=post, data=request.POST, files=request.FILES) if form.is_valid(): form.save() return redirect('mains:home') context = {'form': form} return render(request, 'edit_blog_post.html', context) edit_blog_post.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form }} </table> <button type="submit">Save Changes</button> </form> </div> When i use this then it is showing saved tags BUT {{ form.title }} <input class='form-control' id="choices-text-remove-button" type='text' name='tags' /> When i try this then saved tags are not showing. Then i tried value = '{{ form.tags }}' BUT this was not showing tags but with some glitches. I also tried rendering-fields-manually BUT it is also not showing. Any help … -
Authenticate user with User model, where I created user table in phpmyadmin and connected with django. Then migrated it to app
I'm new to django. I try to make login user with authentication, but my model refers to table in phpmyadmin. I connected DB and made migration but when I try login it do not authenticate with my phpmyadmin table. I just want to know how to authenticate with the phpmyadmin user table and login into the website. -
redirection from old urls to new urls
Hello everyone I want to redirect URLs like this from https://www.example.co.uk/pages/terms-conditions to https://www.example.co.uk/terms-conditions I developed the updated site using the Django framework and now want to redirect old site URLs to new URLs and not losing traffic. what is the best way of doing…? -
Django Query: aggregate() + distinct(fields) not implemented
I have the following model: class Data(models.Model): metric = models.IntegerField(choices=....) date = models.DateField() value = models.IntegerField() linkedObject = models.ForeignKey() ..... What I would like to achieve is to create the sum of all values for the newest metric and date. What I already use is order_by + distinct to get the newest value for each metric choice. This works. Data.objects.all().order_by("metric", "-date").distinct("metric") I tried to combine this with aggregate to make the next step: Data.objects.all().order_by("metric", "-date").distinct("metric").annotate(Sum("value")) Unfortunately, I get the following error message: aggregate() + distinct(fields) not implemented. Hint: I use postgres as database -
Separate Model for storing Choices vs Choices Field in a Model Django
Currently, I implemented the status as a separate model like this class OrderStatus(models.Model): name = models.CharField(max_length=200) class Order(models.Model): status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE, null=True, blank=True) but I just realized that Django has a field called "choices". Django docs: https://docs.djangoproject.com/en/2.2/ref/models/fields/#choices based on that Django docs, I think my model should be like this: class Order(models.Model): UNPAID = 'UNPAID' PAID = 'PAID' ORDER_STATUS_CHOICES = [ (UNPAID, 'UNPAID'), (PAID, 'PAID'), ] status = models.CharField( max_length=2, choices=ORDER_STATUS_CHOICES, default=UNPAID, ) By using this, I think I don't need a separate model called "OrderStatus" anymore. Here are my questions. Is there any downside if I keep my implementation? If I change/refactor my code to use the "choices" field. Can I add more status in the future? do I only have to add more items in the ORDER_STATUS_CHOICES variable? Are there other things that I have to do? -
Getting no such table: auth_user error and also not able to access the admin page
I am trying to add the Django default user creation form for my registration and getting errors. I even removed all my old migration files any solution? Can anyone guide me on how I can fix this? Settings.py INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'crispy_forms', 'crispy_tailwind', 'ckeditor', #local apps #'leads', 'waqart', ] MODELS.PY from django.contrib.auth.models import User MODEL CLASS class Item(models.Model): title = models.CharField(max_length=100) description= RichTextField(blank=True, null=True) main_image= models.ImageField(null=True, blank=True,upload_to='images/') date = models.DateTimeField(auto_now_add=True) item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT) slug = models.SlugField(unique=True, blank=True, null=True) # new author = models.ForeignKey(User, on_delete=models.CASCADE) VIEW from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages # Create your views here. # Register View def register (request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success (request, f'Account created for {username}!') return redirect('waqart-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) -
How to send data into word document with Django?
I'm using Django I want to send some data from my database to a document word, I'm using py-Docx for creating word documents I use the class ExportDocx it can generate a static word file but I want to place some dynamic data (e.g. product id =5, name=""..) basically all the details to the "product" into the document class ExportDocx(APIView): def get(self, request, *args, **kwargs): queryset=Products.objects.all() # create an empty document object document = Document() document = self.build_document() # save document info buffer = io.BytesIO() document.save(buffer) # save your memory stream buffer.seek(0) # rewind the stream # put them to streaming content response # within docx content_type response = StreamingHttpResponse( streaming_content=buffer, # use the stream's content content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment;filename=Test.docx' response["Content-Encoding"] = 'UTF-8' return response def build_document(self, *args, **kwargs): document = Document() sections = document.sections for section in sections: section.top_margin = Inches(0.95) section.bottom_margin = Inches(0.95) section.left_margin = Inches(0.79) section.right_margin = Inches(0.79) # add a header document.add_heading("This is a header") # add a paragraph document.add_paragraph("This is a normal style paragraph") # add a paragraph within an italic text then go on with a break. paragraph = document.add_paragraph() run = paragraph.add_run() run.italic = True run.add_text("text will have italic style") run.add_break() return … -
how to call on('keyup') inside ajax success
i'm trying to make live search based on returned json data via ajax call , this is what i tried , but unfortunately it doesnt work function returnVistors(){ k = ''; $.ajax({ type:'GET', url:'/vistors/list', success:function(data){ const searchInput = document.getElementById('search_visitors').val(); if(searchInput.length > 0){ $('#search_visitors').on('keyup',function(){ for(i = 0;i < visitors.length; i++){ const full_name = visitors[i]['full_name'].toLowerCase(); if(full_name.incudes(searchInput)){ k+='<p class="mr-2">'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'</p>' } k+='<p class="mr-2">'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'</p>' } }); } else{ for(i = 0;i < visitors.length; i++){ const id = visitors[i]['id'] const detail_url = '{% url "vistors:vistor_obj" id=1111 %}'.replace(/1111/,parseInt(id)); k+='<a href="'+detail_url+'" class="flex hover:bg-purple-900 hover:text-white items-center border rounded-xl mt-1 p-2"></a>'; k+='<p class="mr-2">'+visitors[i]['full_name'] + ' - '+ visitors[i]['city']+'</p>' } document.getElementById('visitors_results').innerHTML = k } }, }); } <div class="mt-10 p-2 header rounded-xl md:rounded-tr-none md:rounded-tl-none rounded-bl-xl rounded-br-xl w-full md:w-2/12 h-96 md:h-screen"> <div class="p-3 bg-white rounded-xl"> <button class="text-lg focus:outline-none"><i class="bi bi-search"></i></button> <input type="text" class="w-11/12 focus:outline-none" name="search_visitors" id="search_visitors" placeholder="search here"> </div> <div id="visitors_results" class="p-3 bg-white rounded-xl mt-4 md:mt-5 p-2 overflow-y-scroll" style="height: 90%;"> <div class=" flex justify-center items-center" id="spinner"> <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-gray-900"></div> </div> </div> </div> is it possible creating a new function inside ajax success !? thank you for letting me know -
Django image saving issue
VIEWS.PY def Profile(request): if request.method == "POST": profile = UserForm(request.POST, request.FILES, instance=request.user) if profile.is_valid(): profile.save() return redirect("Profile") profile = UserForm(instance=request.user) return render(request, "book/Profile.html", context={"user": request.user, "profile": profile}) FORMS.PY class UserForm(forms.ModelForm): username = forms.CharField(max_length=50, label='Username', widget=forms.TextInput(attrs={"class": "form-control"})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={"class": "form-control"})) first_name = forms.CharField(max_length=50, required=False, label='First name', widget=forms.TextInput(attrs={"class": "form-control"})) last_name = forms.CharField(max_length=50, required=False, label='Last name', widget=forms.TextInput(attrs={"class": "form-control"})) avatar = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class": "form-control"})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'avatar') MODELS.PY class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='UserAvatar/%Y/%m/%d/', blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() PROFILE.HTML <div class="modal-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ profile }} <div class="modal-footer"> <button type="submit" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> Well, I'm kind of having an issue here. I'm new in Django and I've recently uploaded an image from forms.Form but now I'm using forms.ModelForm and don't really know what the problem is. What am I doing wrong ? -
In Django guardian, how can I determine which group gave the user permissions to the object instance?
I am trying to set up object-level permissions using Django guardian and groups; where I give permissions to the groups - not the users - and add/remove users from the groups as required. When a user has permission to interact with an object instance - because they are in a group that has the necessary permissions - how can I determine which of the user's groups gave them the permission? As an example, building off the example in the django-guardian-docs , ideally there would be something like: >>> joe.has_perm_from_groups('sites.change_site', site) [site_owners_group] -
Virtual Printer / Printing from Django
I want to print labels from a django app, the site this app is on has 4 printers in the same network, all with different label sizes and colours. To create the labels I used fpdf2 for python to get .pdf files and the user can view them in the browser they are using. The problem is: How can I automate the printing process? The user still needs to open the document, which happens in Firefox/Chrome, press CTRL+P and select the right printer. I have 2 ideas, but don't know how to do either of them. Create a "virtual printer" that they always print to, this printer sees the document, categorizes it, and redirects it to the correct printer Somehow print directly from django, which is python and I already know that. Any ideas on how to do either of those? I can't find information on the first and don't know if the second one is a good approach. -
How do I remove duplicate children from django-rest-framework and django-mptt?
I followed this answer How to serialize a Django MPTT family and keep it hierarchical? I could serialize mptt-model but I am also receiving duplicate children from mptt-model. I have simple Menu model class Menu(MPTTModel, BaseModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') serializer class MenuSerializer(serializers.ModelSerializer): children = RecursiveField(many=True) class Meta: model = Menu fields = ('id', 'title', 'children',) I am receiving duplicate menu like this Duplicate response API I am on Python 3.9 Django 3.2.6 django-rest-framework 3.12.4 How do I remove duplicate menu children from djagno-mptt? -
How to make schedule basis delivery and lock the time and date in django
this is my UI design class OrderDashboard(models.Model): time = models.TimeField() reserved = models.BooleanField(default=False) class Reserved(models.Model): time = models.TimeField() date = models.DateField() # @login_required() def order_fuel(request): from django.db.models import Q date_time = OrderDashboard.objects.all() reservation = False if request.method == "POST": time = request.POST.get('time') date = request.POST.get('date') reserved = Reserved.objects.filter(Q(time=time) & Q(date=date)) if reserved: reservation = True print(reservation) return HttpResponse('Time already reserved!') else: reserved_ins = Reserved( time=time, date=date ) reserved_ins.save() return HttpResponse('Order confirmed') dict = {'date_time': date_time, 'reservation': reservation} return render(request, 'Uftl_App/orderfuel.html', context=dict) We building a Django application where we want to manage time slots such that where multiple users can use the same time slot to order their fuel. On the contrary a delivery truck can ship fuel up to 9 times per day (9:30 AM, 10:30AM, 12:30 PM, 02:30PM, 04:00PM, 06:00PM, 08:00PM, 09:00PM, 12:00AM) . If we have 2 trucks then we can deliver our product at 9:30 AM twice a day. We manage to lock/reserve/order the date only one time. We can’t manage to order the same time slot multiple times. How we can implement multiple orders in the same time slot? -
Authentication with react and django
I am an Intermediate django developer. What is the best possible way to implement authentication system in django + react framework.