Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Advanced Search in Django with Multiple Fields and Keeping Filters in Pagination
I have this piece of code that is working already. It enables you to have a search form, to search in a specific table with multiple filters. The results are paginated, and this form allows you to keep these filters when you browse multiple pages. The problem I'm having now is that I am reusing this piece of code in another scenario, and it involved checking one filter in multiple fields in the database table. Example of a standard scenario: First Name Last Name City In this case, the view will be as such: def clean_filters(filters): filters = {k: v for k, v in filters.items() if v} return filters def search(request): filters = { "user__first_name__icontains": request.GET.get("fname_kw"), "user__last_name__icontains": request.GET.get("lname_kw"), "city__name__icontains": request.GET.get("city_kw"), } html_queries = { "fname_kw": request.GET.get("fname_kw"), "lname_kw": request.GET.get("lname_kw"), "city_kw": request.GET.get("city_kw"), } filters = clean_filters(filters) html_queries = clean_filters(html_queries) people = Person.objects.filter(**filters) page_num = request.GET.get("page", 1) p = Paginator(people.order_by("-pk"), 12) people = p.get_page(page_num) context = { "people": people, "cities": City.objects.all(), "filters": html_queries, } return render(request, "pages/index.html", context) And the HTML will be as such: <form method="GET" action="{% url 'search' %}"> <div class="row"> <div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 col-xs-12"> <div class="row"> <div class="col-6"> <input class="form-control" name="fname_kw" id="search_fname" placeholder="First Name" /> </div> <div class="col-6"> … -
selinux is disabled and I'm still getting error 13
I'm running a django project on rhel7. Current selinux status: SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: permissive Mode from config file: permissive Policy MLS status: enabled Policy deny_unknown status: allowed Max kernel policy version: 31 Despite that, my application is still throwing this in the logs: [Mon Jun 06 17:09:12.573815 2022] [wsgi:error] [pid 34476] (13)Permission denied: mod_wsgi (pid=34476, process='graphite', application=''): Call to fopen() failed for '/opt/graphite/conf/graphite.wsgi'. -
update data using ajax with django and bootstrap modal
here is my views.py def update_article(request, pk): obj = Article.objects.get(pk=pk) if request.headers.get('x-requested-with') == 'XMLHttpRequest': new_designation = request.POST.get('designation') new_famille = request.POST.get('famille_id') new_quantite = request.POST.get('quantite') obj.designation = new_designation obj.famille = new_famille obj.quantite = new_quantite obj.save() return JsonResponse({ 'designation': new_designation, 'famille': new_famille, 'quantite': new_quantite, }) return redirect('/article') Here is my modal <div class="modal fade" id="UpdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" > <form action="" method="post" id="update-form"> {% csrf_token %} {% for field in form %} <div class="form-group col-lg-12"> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update</button> </div> </form> </div> </div> </div> here is my Js const getData = () =>{ $.ajax({ type:'GET', url:'/load/', success: function(response){ console.log(response) const data = response.article console.log(data) data.forEach(element => { articleBox.innerHTML +=` <tbody> <tr> <td><div ><a data-bs-toggle="modal" data-bs-target="#detailModal" href="" data-pic=${element.designation} class="detail" >${element.designation}</a></div></td> <td>${element.famille}</td> <td><a href="#">${element.quantite}</a></td> <td>${element.date}</td> <td>Available</td> <td><a href="#" data-bs-toggle="modal" data-bs-target="#delete">Delete</a> |<div data-bs-toggle="modal" data-bs-target="#UpdateModal" id="update-article" >Edit</div></td> </tr> </tbody> ` }); }, error: function(error){ console.log(error) } }) } from this code I want to update my data by id,I've tried everything but when I click the edit button , the form modal … -
Can multiple values be assigned to one variable without brackets "[]" or parentheses "()" (Python)
From this django answer in SO, I found 3 variables "JAN", "FEB" and "MAR" in the class "Month" extending "models.TextChoices" as shown below: # "models.py" from django.db import models class MyModel(models.Model): class Month(models.TextChoices): JAN = "1", "JANUARY" # Here FEB = "2", "FEBRUARY" # Here MAR = "3", "MAR" # Here # (...) month = models.CharField( max_length=2, choices=Month.choices, default=Month.JAN ) And multiple values are assigned to each variable without brackets "[]" which creates Array or parentheses "()" which creates Tuple as shown below: JAN = "1", "JANUARY" FEB = "2", "FEBRUARY" MAR = "3", "MAR" Now, can multiple values be assigned to one variable without brackets "[]" or parentheses "()"? -
Undefined Json response from django backend to chrome extension alert
Hi i am trying to return a json file to the chrome extention to show it to the user, the query go to server without a problem, fetched url is also working and does return the json file when i try it directly, but the chrome extention shows "undefined" message in the alert instead of the json file. the returned json file have this type : JsonResponse(data) data is a dict[str, Union[str, list]], another question, is how can i show the json file in the popup html page? to my chrome extension code: Manifest.json: { "name": "Price Comparator", "description": "Compare prices across other websites!", "version": "1.0", "manifest_version": 3, "background": { "service_worker": "background.js" }, "icons": { "16": "images/logo16.png", "48": "images/logo48.png", "128": "images/logo128.png" }, "action": { "default_icon": "images/logo16.png", "default_popup": "popup.html" }, "host_permissions": ["XXX*"], "permissions": [ "XXX", "http://127.0.0.1:8000/", "storage", "activeTab", "scripting", "tabs", "background", "identity", "notifications" ], "content_scripts": [ { "matches": [ "https://www.google.com/*" ], "css": [ "main.css" ] } ] } popup.js: $(function(){ $('#keywordsubmit').click(function(){ var search_topic = $('#keyword').val(); if (search_topic){ chrome.runtime.sendMessage( {topic: search_topic}, function(response) { result = response.farewell; alert(result.summary); var notifOptions = { type: "basic", iconUrl: "icon48.png", title: "WikiPedia Summary For Your Result", }; chrome.notifications.create('WikiNotif', notifOptions); }); } $('#keyword').val(''); }); }); Background.js: chrome.runtime.onInstalled.addListener(() => … -
Django-tables2 exporting badly
I'm using django-tables2 for export my tables. When I export the table to excel format it seems like this: enter image description here. I can't see all of the cell. How can I set the width of excel columns before export? tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','item_barcode','order_id', 'full_name','company','email','phone_number','note') html part <div class="container"> {% for format in table.export_formats %} <a id="{{format}}" href="{% export_url format %}">.{{ format }}</a> {% endfor %} {% render_table table %} </div> -
Extend User model in Django with jwt authorization
I am trying to extend User model in Django. I already have authorization using jwt Token and I am currently trying to add another field to User model, such as phone number and address. My views.py looks like this: class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (AllowAny,) serializer_class = MyTokenObtainPairSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer models.py like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.IntegerField(blank=False) address = models.CharField(max_length=500, 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() In here I'm trying to create another class that will store phone number and address. How can I incorporate my Profile class into User so that it will create new user model and what is more use earlier implemented Token authorization. -
Multiple nested choices in Django models
Forgive me if I'm not describing this correctly - I'm still learning and I've hit a wall with a problem I'm working on. I want to create a way (in the Admin backend for now) for users to show the books they like by fiction/non-fiction, age-range, genre(s) and sub-genre(s). So, a user who liked gothic horror books could select fiction>adult>horror>gothic. Or, a user who likes literally all YA books could select fiction>Young Adult and their selection would cascade down to every genre and sub-genre. I think the Choices field option and the MultiSelectField functionality might be a start, but there doesn't seem to be a way to add 'layers' to the choices beyond the categories below, and it seems like an inelegant solution when there could be hundreds of choices. I also don't know how it could be presented in the Admin - ideally with checkboxes that can 'open up' to show the sub-categories beneath them. GENRE_CHOICES = ( ('Fiction', ( ('FCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ('Non-Fiction', ( ('NCH', 'Childrens'), ('FMG', 'Middle Grade'), ('FYA', 'Young Adult'), ('FAD', 'Adult'), )), ) genres = MultiSelectField(max_length = 100, choices=GENRE_CHOICES, null=True) I don't even know the name of … -
Django blog categories wont show up
I got a problem where my blog post categories dosent show up on my categories page with the code i used below from cat_menu_list and {% for post in cat_menu_list %}. How do i get the diffrent categories to show up in my categories.html? hope someone can help ithink below is all the code that does this if u need anymore tell me and i upload it asap. views.py def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'category_list.html', { 'cat_menu_list': cat_menu_list}) def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render( request, 'categories.html', { 'page_obj': page_obj, 'cats': cats.replace('-', ' ').title(), "cat_menu_list": cat_menu_list}) categories.html {% extends 'base.html' %} {% block content %} <h1 class="headerh1">{{ cats }}</h1> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in cat_menu_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'article-detail' post.pk %}" class="text-dark">{{post.title }}</a></h2> <p class="card-text text-dark h6">{{ post.author.first_name }} {{post.author.last_name }} | {{ post.post_date }} <a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></p> <div class="card-text">{{ post.body|safe|slice:":200" }}</div> <a href="{% url 'article-detail' post.pk %}" class="btn btn-info">Read More</a> {% if user.is_authenticated %} {% if user.id == … -
Django file/image upload not responding
I've gone through about 8 tutorials across YouTube and Online websites. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files. I have done the settings file, urls, views, models everything. Any advice is greatly appreciated here are my files: // setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(null=True, blank =True, upload_to='trips') // urls.py ( there were 2 ways to write media according to tutorial) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('travelsiteapp.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) // views.py (lastly) def tripAdd(request): form = TripForm() if request.method == 'POST': form = TripForm(request.POST, request.FILES) if form.is_valid(): form.photo = form.cleaned_data["photo"] form.save() context = { 'form': form} return render(request, 'tripAdd.html', context) // I have hit all the steps not sure whats wrong? & and installed pip pillow -
Getting Errors while starting mod wsgi (Django app) via apache
Starting up a dockerised django application as a mod wsgi app via apache. Getting an endless stream of below errors. Errors: 2022-06-02 16:05:12.225137 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10992 exit signal Aborted (6) 2022-06-02 16:05:12.225382 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.225411 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.225433 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10992): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.227789 [notice] [pid 10002] mpm_unix.c(436): [client AH00052: child pid 10993 exit signal Aborted (6) 2022-06-02 16:05:12.227856 [info] [pid 10002] src/server/mod_wsgi.c(7761): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has died, deregister and restart it. 2022-06-02 16:05:12.227874 [info] [pid 10002] src/server/mod_wsgi.c(7775): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' terminated by signal 6 2022-06-02 16:05:12.227896 [info] [pid 10002] src/server/mod_wsgi.c(7846): [client mod_wsgi (pid=10993): Process 'in.goibibo.com' has been deregistered and will no longer be monitored. 2022-06-02 16:05:12.228150 [info] [pid 10994] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10994): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.229803 [info] [pid 10995] src/server/mod_wsgi.c(9381): [client mod_wsgi (pid=10995): Starting process 'in.goibibo.com' with uid=2, gid=2 and threads=30. 2022-06-02 16:05:12.230033 [info] [pid 10994] src/server/wsgi_interp.c(2260): [client mod_wsgi (pid=10994): Initializing Python. … -
How do you pass options to Django-flatpickr date picker?
Im trying to implement a datetime picker on a Django app but im having some trouble working out how to pass options to the picker using the django-flatpickr package -->docs here: django-flatpickr. The docs really just get you started but don't go into any detail on how to apply some options and filter provided by the flatpickr.js package. I have successfully implemented the basics with the form fields and passing it to and from the the template which all works fine. However im having difficulty passing options i.e a start date, end date, allowed dates, making sure dates can't be selected I the past etc So the backend: forms.py class DatePickerForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) date_from = forms.DateTimeField(widget=DateTimePickerInput()) date_to = forms.DateTimeField(widget=DateTimePickerInput()) amount = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) views.py def check_availability(request): #Get date time vals from client, pass to check_availabilty to query db if request.method == 'POST': form = DatePickerForm(request.POST) if form.is_valid(): cd = form.cleaned_data availability = check_availability(cd['id'], cd['date_from'], cd['date_to'], cd['amount']) else: print('Not bloody valid') return HttpResponse(f'Availabilty = {availability}') ClientSide: mytemplate.html <form action="{% url 'check_availability' %}" method="post"> {{ date_form.media }} {{ date_form.as_p }} <input type="hidden" name="id" value="{{ rental.id }}"> {% csrf_token %} <br> <button type="submit" value="Check Dates">Check Availability</button> </form> So what im really looking … -
Exporting tables in Django
I'm trying to export my Table datas. I tried to use django-tables2 but I couldn't did. From documentation I didn't understand much. How can I export my table? my html <!DOCTYPE html> {% load django_tables2 %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <title>Admin Page</title> </head> <body> <div class="container"> {% for format in table.export_formats %} <a href="{% export_url 'csv' %}">.{{ format }}</a> {% endfor %} </div> {% render_table table %} </body> </html> tables.py import django_tables2 as tables from .models import Customer class CustomerTable(tables.Table): export_formats = ['xls','xlsx','csv'] class Meta: model = Customer fields = ('orderorbarcode','barcode', 'full_name','company','email','phone_number','note') And it keep saying no module named django-tables2: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'olvapp', 'tablib', 'django-tables2', ] And When I pip list: django-tables2 2.4.1 -
Django + Django Rest Framework: get correct related objects on intermediate model
I have an intermediate model with the following fields: class UserSkill(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='user_skills') disabled = models.BooleanField(default=False) As you can see, it has two foreign keys, one to the auth user and one to another table called skill. I am trying to get all Skills assigned to an specific user, so I do the following get_queryset in my ViewSet: class AssignedSkillViewSet(viewsets.ModelViewSet): queryset = Skill.objects.all() serializer_class = AssignedSkillSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user return Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)) Now, I also need to include the intermediate model information in the API, which I can access trough users_skills related name in DRF's Serializer, as follows: class AssignedSkillSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Skill fields = [ 'id', 'url', 'title', 'description', 'user_skills', ] But when I try to get that information it returns ALL user_skills related to the assigned skill, no matter if they are assigned to other users. I need the related model information only for that user and that skill. For Example: If I have a skill named Math, and a user named Maria related_skills = Skill.objects.filter(user_skills__user=user, user_skills_user__disabled=False)).user_skills.all() The above code will return: [ <UserSkill: Math+Jenniffer>, <UserSkill: Math+Gabriel>, <UserSkill: Math+John>, <UserSkill: Math+Maria>, ] I only … -
Can't Create Django Test Database
I have a django 3.2/mysql 5.7.38 web site that is working. I am trying to write some unit test for the first time, and I am getting an error regarding the creation of the test database. About 1/2 of the tables are created before this error occurs (hence the question about the database already exists. Creating test database for alias 'default'... Got an error creating the test database: (1007, "Can't create database 'test_hopi_django'; database exists") Type 'yes' if you would like to try deleting the test database 'test_hopi_django', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'test_hopi_django.CurrentArticle' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mark/.virtualenvs/new_hopirockets_website/lib/python3.6/site-packages/django/core/management/commands/test.py", line … -
When searching for a child node in django admin, would like it to also display the parent org
The image below shows a django admin search page where the parent is authors and the child nodes are books. Currently, when searching for a book in the search box it will only display the book. I would like to also display the parent org when searching. That way if two books had the same name we could what author they were under and determine which is which. -
Handling multiple post request with fetch api in django
I want to fetch the values of the form data after submission through fetch API. I am able to do that with one form on a webpage. But I don't know how to do it with multiple forms on a single webpage. Please enlighten me regarding the same. views.py def home(request): context={} context2={} if 'submit' in request.method=="POST": options_value=request.POST.get('options_value') value=request.POST.get('value') print(options_value,value) result2=[("AD", "abc", "False"),("AD", "abc", "False")] context={ 'options_value':options_value, 'value':value, 'UserIds' : str(result2), } return JsonResponse(context, safe=False) if "save" in request.method=="POST": phone_no=request.POST.get('phone_no') context2={ 'phone_no':phone_no } return JsonResponse(context2, safe=False) return render(request, 'index.html', context) Just let me know what would be the format of fetch API for the above 2 Post requests. P.S - "submit" and "save" are the name given to the submit buttons of 2 different forms. -
django form.is_valid is failing & not saving the form
my account model automatically creates when user creates a new user account & only user value is added to that model, rest remains empty! i am trying to make the user update or add more info in their account model but the is.valid() is failing in views & not saving the form. what went wrong & how to fix it? #model.py class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True, max_length=100) profile_img = models.ImageField( upload_to="profile_images", default="default.jpg") location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username #form.py class accountForm(ModelForm): class Meta: model = profile fields = "__all__" widgets = { # 'fields': forms.TextInput(attrs={'class': "form-control"}), 'profile_img': forms.FileInput(attrs={'class': 'form-control', 'id': 'inputGroupFile04'}), 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'location': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Location'}), } #views.py def account(request): Profile = profile.objects.get(user=request.user) form = accountForm(instance=Profile) if request.method == "POST": form = accountForm(request.POST, instance=Profile) if form.is_valid(): form.save() return redirect("sign_in") context = {"form": form} return render(request, "account.html", context) -
Paid Promotion on an event in a Django Rest Framework App
Let's say i have a model Called Activity class Activity(models.Model): activity_name = models.CharField(max_length=50) Now suppose i am a user of this app and i am creating an activity/event.Once creation of an activity is done then i want to promote it for let's say 3days for 200USD. Now i need strong quality suggessions on how am i going to manage this promotion in django and in which models.please suggest me the database design for that Bearing in mind that promoted activities should appear in top of homepage..So how do i measure which activity would come first if there is a bunch of promoted activities? and also how am i going to automatically measure whether a promoted activity promotion period has expired? -
Patch don't work with the path I usually use with pytest
I have this file in a django project, 'project/src/connector.py' (manage.py is in src -> src/manage.py) from shared_tools import rest class Foo: def __init__(self): self.connector = rest.Restful() def make_call(self): self.connector.make_request() And this test: class FooTest(TestCase): @patch('connector.rest.Restful.make_request', autospec=True) def test_it(mock_request): assert mock_request.called is True Normally I worked with pytest, and I think I always did it in this way, is there something wrong with my code or it's becasuse it's different with django? -
Why do I get this error "No product matches the given query."?
When i add product to my home function in views.py I got this error : No product matches the given query. image Why do I get this error? views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request ): p=get_object_or_404(product,pk=1) return render(request,'home.html',{'p':p}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) urls: from django.urls import include, path from rest_framework import routers from quick.views import productviewset from quick import views from django.contrib import admin urlpatterns = [ path('api/', include(router.urls)), path('',views.home), path('foods',views.foods), path('admin/',admin.site.urls), ] -
Retrieving a pre-specified range of objects in django
I am creating a blog application, and I want to create a function that gives me access to a specific object(blog in this case) and render it on the view. I also want help with creating another function that will create access to a range of blog posts, say 0-3. Here is my index.html <div class="row g-5"> {% for post in posts %} <div class="post-entry-1 col-lg-4 box mx-1"> <a href="single-post.html"><img src="{{post.image.url}}" class="post_img"></a> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>{{post.created_at}}</span></div> <h2><a href="">{{post.title}}</a></h2> </div> <p class="mb-4 d-block">{{post.body|truncatewords:75}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">OlePundit</h3> </div> </div> </div> {% endfor %} It could also be a for or a while loop. I don't know how to edit the for loop on the index.html in order to access a specified range My view def index(request): posts = Post.objects.all() return render(request, 'index.html', {'posts':posts}) -
Manually caching a view in Django
I'm using Django 4.0 and I have some few pages that takes a bit to load since they have to load lots of stuff from the database. These pages are static, they never change, and I don't want the users to wait, so I want to cache them as soon as the server goes up. Unfortunately I'm not finding a way to do so (I tried the @cache_page decorator, but it only caches the page after the first visit). How could I accomplish this? Thank you. -
Overlap Check in Tuple django
i am trying to find the overlap , can anyone help me list_tuple = [(100, 350,"d"), (125, 145,"a"),(200,400,"o")] sorted_by_both = sorted(list_tuple, key=lambda element: (element[0], element[1]) ) i am trying to build the code to find the numbers that overlapping and how many times overlapping happening. output 3 overlap is happening. -
Been trying this for a while now. What else should I try?
getting this error when trying to run django-admin ERROR: Could not install packages due to an OSError: [WinError 5] Access is denied: 'C:\Python310\Lib\site-packages\pip\init.py' Consider using the --user option or check the permissions.