Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set-up wagtail pages
I am trying to configure a django project that uses the wagtail CMS to display the templates(the templates is already in the file) on the frontend but since it is my first time working with wagtail, I am having issues and don't know where to head to. I have checked some external sources like YouTube perhaps I will get any illustration of such but I don't seem to get any. The whole project structure is shown below and this shows that the whole templates and html files are intact but I don't know how to set it up. If I run the program using the python manage.py runserver, I get the project running and after opening the localhost:8000 on the browser, I only get a blank screen. The url.py file of the main project is show below: # django imports from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin # wagtail imports from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocuments_urls urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^robots\.txt$', TemplateView.as_view( template_name='robots.txt', content_type='text/plain' )), url(r'^documents/', include(wagtaildocuments_urls)), ] urlpatterns += i18n_patterns( url(r'', include(wagtail_urls)), ) The … -
Using MySQL REGEXP to filter string with Django ORM
I have a model which have FileField field and in this model we have millions of records. class MyModel(models.Model): media = models.FileField(upload_to=my_function, db_index=True) ... These media records are stored in database like; media/some/folder/filename.jpg media/filename.jpg media/2021091240-10328.JPG media/aXay-123.jpeg media/some/another/folder/202110-12-12.jpeg etc. and I need to find records which are not have nested path like /some/folder/ or /some/another/folder/ with django orm __iregex lookup. So, I tried something like; MyModel.objects.filter(media__iregex=r"^media/[0-9a-zA-Z\-][.][a-zA-Z]") but it does not match and I do not understand to write proper regex [mysql regexp]. How can I do filter with mysql regexp with using Django orm to get records with only have pattern like; media/filename.extension? -
Django: Display a PDF document in iframe or embed not working
I want to display a PDF on on a page in our website. The URL is correct and pointing to the PDF. I am seeing a display, but I see garbage characters instead of the PDF. In template using: <embed src="{{packet.certificate_pdf.url}}" ...> <iframe src="{{packet.certificate_pdf.url}}" ...> Then I see results on the page where the PDF is suppose to display: %PDF-1.3 %âãÏÓ 1 0 obj << /Type /Pages /Count 6 /Kids [ 3 0 R 4 0 R 5 0 R 6 0 R 7 0 R 8 0 R ] >> endobj 2 0 obj << /Producer (PyPDF4) >> endobj 3 0 obj << /MediaBox [ 0 0 595 842 ] /Type /Page /Parent 1 0 R /Contents [ 10 0 R ] /Resources << /ProcSet [ /PDF /Text /ImageC ] /XObject << /HiQPdf_mlpnjcimdfejkpcopajmiphnnjaiocbm 11 0 R >> >> >> endobj 4 0 obj << /MediaBox [ 0 0 .... etc Using in Production enviroment: Django 3.2 Python 3.8 Already using: X_FRAME_OPTIONS = 'SAMEORIGIN' I also tried converting to base64 then displaying it: <iframe src="data:application/pdf;base64,{{pdf_in_base64}} ... This used to work, but recently Chrome sometimes show the PDF and sometimes not, which I can't solve. Something in the base64 seems to … -
Cleaning up library from old Django migration
I have a Django migration which used the partial-index library. This is a fairly old migration in a long running project, created before Django supported partial indices, and now I need to upgrade the project from Django 2.2 to Django 3.2. The partial-index library is no longer necessary as Django now supports partial indices. Moreover, this library has code which does not seem to work with Django 3 as the model structures have changed (specifically related to the FieldDoesNotExist exception). I am trying to update the old partial index to the new Django format, using the condition system described here https://docs.djangoproject.com/en/2.2/ref/models/indexes/#condition The change itself is simple, it involves changing the index definition in the model from indexes = [Index(fields=['round'], name='round_index', condition=PQ(removed_at__isnull=True))] to indexes = [Index(fields=['round'], name='round_index', condition=Q(removed_at__isnull=True))] (note the change PQ which is from partial-index to Q which is Django's own construct) This results in a migration which drops and recreates the index, where everything looks ok. However, an earlier migration where this index was originally created, imported the partial-index library to reference the PQ object. This will fail with an ImportError if the library is removed from the project completely. What is the safest way to remove the reference … -
Email verification using django and firebase
I know want to implement a email verification and then check if the user has verified his/her email or not in Django and database being firebase. I have seen method to send emails using send_email_verification in python that works fine, But I cant seem to get the firebase.auth().current_user.emailVerified thing right. I get an error saying current_user has no key emailVerified. I have also tried to write in different forms and check the printed the user dictionary but couldn't find emailVerified parameter. What am I doing wrong here? -
How to ignore the HTTP response and post the form?
I have a form for user registration .After the users press the submit button , the user should receive a confirmation email .And the whole form will post to the db . But the problem is I use Gmail as the domain email and it causes lots of security prevention that I can't send the confirmation email when there is new registration. Therefore , the system can't post the form to the db . The user keep stucking in the #loading page. Now , I'm going to ignore the confirmation email process . Gmail system still send a confirmation email when there is a new registration . But the form will then post anyway, no matter the confirmation email successfully sends it out or not. How to amend the code ? HTML var form = $("#form_data")[0]; var data_item = new FormData(form); data_item.append("profile_img",document.getElementById("imgInp").files[0]) data_item.append("username",username) data_item.append("password",password) ..... $("#loading").show() $.ajax({ method : "POST", url : "/signup/", enctype : "mutipart/form_data", processData : false, contentType : false, cache : false, data : data_item, success : function(response){ console.log(response) $("#loading").hide() if (response == "success") swal("Registration Saved Successfully", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.href = "/signin/"; }); else if (response == "email exists"){ $('#error_email_exists').show(); … -
print for loop data based on the item quantity given in django
Let us consider purchase_order_id = 199 for this purchase_order we are having 2 items (let us consider item_names as Samsung Note 3(item 1),Ear capsule(item 2)) Now item_1(Samsung Note 3) quantity is given as 2 and item_2(,Ear capsule) quantity is given as 3 now in the pdf how i need to print the labels is item_1 2 times as quantity is 2 and item_2 as 3 times as quantity is 3 Let us consider my views.py as class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() items_list = [] for c in items: item_dict = {} if c.batch_number: item_dict['batch_number'] = c.batch_number if c.due_date: item_dict['due_date'] = c.due_date if c.season_support: item_dict['season_support'] = c.season_support if c.flower_colour: item_dict['flower_colour'] = c.flower_colour .... .... .... items_list.append(item_dict) template = loader.get_template('po_labels.django.html') context_dict = { 'items_list' : items_list, 'items' : items, 'order' : order, } context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdfkit.from_string(html, 'applicationpdf.pdf') pdf = open("applicationpdf.pdf") response = HttpResponse(pdf.read(), content_type='application/pdf') return response let us consider my template.html as <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Light Degree</title> {% load i18n crm_tags sekizai_tags widget_tweaks %} <style> html { background-color:#f4f4f4; } body … -
I need to create Hierarchical structured JSON file from Django Models for using create menu submenu
I need to create Hierarchical structured JSON file from Django Models for using create menu submenu Please give solution Experts class Menuandurls(models.Model): id = models.BigAutoField(primary_key=True) seqno = models.CharField(db_column='seqNo', max_length=20, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) type = models.CharField(max_length=20, blank=True, null=True) isdirecturl = models.BooleanField(db_column='isDirectUrl', blank=True, null=True) class Meta: db_table = '[masters].[menuAndUrls]' -
Python dict into HTML-template (Django)
I have a pythondict with the example format data ={"X":{"0":1234, "1":5678, "2":1234}, "X":{"0":4567, "1":1234,"2":4456}} Unfortunately, I don't know how to iterate through the nested data in an HTML template to create a table. Can you help me? -
How can I set ldap_user in a django test?
We have a django application with LDAP authentification (django-auth-ldap). In a custom permission we check if request.ldap_user.group_names contains a certain group (depending on request.data). Manual testing shows it is working. Now we want to write an automated test, but we keep getting "AttributeError: 'User' object has no attribute 'ldap_user' and we can not find anywhere how we can set the ldap_user and the ldap_user group names. This is the test so far: import pytest from django.urls import reverse from django.test import Client from django.contrib.auth.models import User import requests client = Client() url_create_artifact = reverse("artifacts/create-list") @pytest.mark.django_db() def test_post_artifacts_create_logged_in(): component = Component() component.id = "test_component" component.ldap_group = "test_group" component.save() user = User.objects.create(username="test_user") user.set_password("1234") user.save() client.login(username="test_user", password="1234") response = client.post( url_create_artifact, { "component_id": "test_component" }, ) assert response.status_code == 200 This is the custom permission: from rest_framework.permissions import BasePermission, SAFE_METHODS from django.shortcuts import get_object_or_404 class CustomPermission(BasePermission): def has_permission(self, request, view): component_id = request.data["component_id"] component = get_object_or_404(klass=Component, id=component_id) user = request.user if user.is_authenticated: user_ldap_groups = request.user.ldap_user.group_names component_ldap_group = component.ldap_group return component_ldap_group in user_ldap_groups else: return False Our view starts with from rest_framework.authentication import SessionAuthentication from our_app.permissions import ApplicationPermission from rest_framework import viewsets class ArtifactSetCreate(viewsets.GenericViewSet): authentication_classes = [SessionAuthentication] permission_classes = [CustomPermission] [...] urls.py contains from … -
accessing an element of a django database object
I am trying to access an element of a django database table object. My under standing is the structure is as follows: Database table -> object -> elements. I can access the Database object that i want by doing the following: wanted_object = WholeValues.objects.get(id=1) how can I access the the elements of this database object. I have tried wanted_element = wanted_object.get(id=2) when I try to access the first element I get an error. this error says WholeValues' object has no attribute 'get' My model for the object is as follows: class WholeValues(models.Model): a_count = models.FloatField() b_count = models.FloatField() c_count = models.FloatField() in my specific case I want to access the b_count value. -
Connecting Django to CosmosDB
Currently in my settings i have: DATABASES = { 'default': { 'ENGINE': env.str("SQL_ENGINE"), # djongo is set here 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': env.str("SQL_HOST"), 'name': env.str("SQL_NAME"), 'port': env.int("SQL_PORT"), 'username': env.str("SQL_USERNAME"), 'password': env.str("SQL_PASSWORD"), }, 'SSL': True }, } I'm still not able to make migrations, the following error is thrown when i run makemigrations . Error: raise ServerSelectionTimeoutError pymongo.errors.ServerSelectionTimeoutError -
Detail of Order/Cart with annotate() [django]
I have a models: class Product(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) slug = models.SlugField() description = models.TextField() image = models.ImageField() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) products = models.ManyToManyField(Products, through='OrderItem', related_name='orders') being_delivered = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) And I have views for for creating Order and OrderItems attached to Order. I need views for cart/order_detail: what I do: def cart_detail(request): order = Order.objects.filter(user=request.user) order_item = OrderItem.objects.filter(order=order).annotate(???) return render(request, 'cart/cart_detail.html', {'order':order, 'order_item':order_item}) I need help on how to correctly display in the template - the quantity, units of the Product, the price per unit, the total price. Please, any help would be helpful. Any links or code snippets. -
Django ModelAdmin not working with custom field method
I'm trying to write a custom method to ovveride the default viewing of a field in ModelAdmin, a described here: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/ So this should work: @admin.register(Contract) class ContractDataAdmin(admin.ModelAdmin): list_display = ("name", "status", "date_end") list_filter = ('name','status', "date_end", "headquarters_access_list") fields = ("name", "status", "date_start", "date_end", "manager_list", "buyer", "get_document_list_field", "headquarters_access_list") @admin.display(empty_value='???') def get_document_list_field(self, obj): return "\n".join([c.name for c in obj.document_list.all()]) Where the model is: class Contract(models.Model): class Meta: verbose_name = _('Contract') verbose_name_plural = _('Contracts') name = models.CharField(max_length=255, help_text=_('Contract name'), verbose_name=_('contract name')) status = models.CharField(max_length=255, default=ContractStatus.OPEN, choices=ContractStatus.choices(), help_text=_('Status'), verbose_name=_('Status')) date_start = models.DateField(editable=True, help_text=_('Start date'), verbose_name=_('Start date')) date_end = models.DateField(editable=True, help_text=_('End date'), verbose_name=_('End date')) manager_list = models.ManyToManyField(User, blank=True, help_text=_('Manager list'), verbose_name=_('Manager list')) buyer = models.OneToOneField(CompanyData, # Committente related_name="buyer", on_delete=models.RESTRICT, default=None, null=True, auto_created=False, help_text=_('Buyer'), verbose_name=_('buyer')) headquarters_access_list = models.ManyToManyField(Headquarters, blank=True, help_text=_('Headquarters access list'), verbose_name=_('Headquarters access list')) contractor_list = models.ManyToManyField(CompanyData, blank=True, help_text=_('Contractors list'), verbose_name=_('Contractors list')) staff_list = models.ManyToManyField(UserData, blank=True, help_text=_('Staff list'), verbose_name=_('Staff list')) vehicle_list = models.ManyToManyField(VehicleData, blank=True, help_text=_('Vehicle list'), verbose_name=_('Vehicle list')) document_list = models.ManyToManyField(Document, blank=True, help_text=_('Document list'), verbose_name=_('Document list')) When going to the chagne page of the model (/admin/common/contract/1/change/) I get the following error: Traceback (most recent call last): File "C:\Users\gianluca.romanin\AppData\Local\pypoetry\Cache\virtualenvs\kdocweb-1PRTDUa5-py3.9\lib\site-packages\django\contrib\admin\options.py", line 710, in get_form return modelform_factory(self.model, **defaults) File "C:\Users\gianluca.romanin\AppData\Local\pypoetry\Cache\virtualenvs\kdocweb-1PRTDUa5-py3.9\lib\site-packages\django\forms\models.py", line 563, in modelform_factory return type(form)(class_name, (form,), … -
Django TypeError: got an unexpected keyword argument 'model_name'
While coding a Django signal, I am getting a TypeError: got an unexpected keyword argument 'model_name'. From the code, I expected to get the 'Payment_record' function triggered when a 'Payment' is made. Here is the code. models.py class Payment(models.Model): paid_by = models.CharField(max_length=200) student_name = models.ForeignKey(Student, on_delete=models.CASCADE) payable_towards = models.CharField(max_length=200, choices = payable_towards, default = "tuition_fee") payment_date = models.DateTimeField(default=timezone.now) amount_paid = models.IntegerField(blank=False, null=True) account_name = models.ForeignKey(Account, on_delete=models.CASCADE, default=70) receipt_number = models.IntegerField(blank=False, null=True, unique=True) name = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name="pay_received_by",) def __str__(self): return str(self.student_name) # signal to add payment to account class Payment_record(models.Model): payment_date = models.DateTimeField(default=timezone.now) student_name = models.ForeignKey(Payment, on_delete=models.CASCADE, related_name="pay_date_record",) balance = models.IntegerField(blank=False, null=True) # record_history = payment_status = models.CharField(max_length=200, choices = payment_status, default = "underpaid") def __str__(self): return str(self.student_name) ..................................... apps.py from django.apps import AppConfig class FinancesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'finances' def ready(self): import finances.signals ...................................... signals.py from .models import Payment_record, Payment from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Payment) def create_payment_record(sender, instance, created, **kwargs): if created: Payment_record.objects.create(Payment=instance) @receiver(post_save, sender=Payment) def save_payment_record(sender, instance, **kwargs): instance.Payment_record.save ...................................... I have also attached the screenshots for the above code snippets. What could be the problem and how do I solve it? Or better still, with the 2 models, how can … -
How can I choose which choice to show up in django form field?
I am trying to dynamically change the viewable choices in a django form choice field depending on the user. Here is my form: SubmitForm(forms.ModelForm): class Meta: model = Lesson fields = ( "status", ) Here is my models.py for Lesson: CLASS_STATUS = ( ('Attended', 'Attended'), ('Absent', 'Absent'), ('Teacher Postponed', 'Teacher Postponed'), ('Student Postponed', 'Student Postponed'), ) status = models.CharField( max_length=30, choices=CLASS_STATUS, null=True, blank=True, ) So, basically I want to be able to select which choices to show for each type of user. In order to do this, I hope you guys could also show how I could access the request.user information in my form. Thank you, and please ask me any questions you have. -
post request 413 Error django with gunicorn
class test(BaseListView): def post(self,request): data=json.loads(request.body.decode('utf-8')) url = 'other server API' res=requests.post(url, json=json.dumps(data)) print(res.status_code) return 'ok' This is the code. 'data' i put as a request body to send this data to other server. and when i printed res.status_code i got 413 error. It's because the data size is big.(1GB) the size of the request body depends on the platform or webserver. I think this is the problem in gunicorn. i found this solution on docs but i don't know how to use it. https://docs.gunicorn.org/en/latest/settings.html#limit-request-line If anyone has other solution or how to use --limit-request-line INT command line i would be thankful. Currently, i put my gunicorn.service on /etc/systemd/system and to start the server i command "sudo systemctl restart gunicorn" this is how gunicorn.service looks like [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/django-boilerplate/mysite ExecStart=/home/ubuntu/django_env/bin/gunicorn \ --workers 3 \ --bind 0.0.0.0:8000 \ mysite.wsgi:application [Install] WantedBy=multi-user.target -
Django: how to access field attributes in a template
I have a form for updating an object with an image field styled with bootstrap. And right now it just looks ugly: is there a way to access individual html elements like form.image.label_tag, so i can style them? I would definitely like to remove this line break in the middle. django template: <div class="input-group"> <span class="input-group-text"> <label for="{{ form.image.auto_id }}"><i class="{{ form.image.label }}"></i></label> </span> {{ form.image|add_class:"form-control" }} </div> html i am getting: <div class="input-group"> <span class="input-group-text"><label for="id_image"><i class="bi bi-image"></i></label></span> Currently: <a href="/media/dishes/27.jpg">dishes/27.jpg</a> <input type="checkbox" name="image-clear" id="image-clear_id"> <label for="image-clear_id">Clear</label> <br> Change: <input type="file" name="image" accept="image/*" class="form-control" id="id_image"> </div> -
NginX location management with Django&Vue.js setup
I have a Django backend and Vue.js frontend served by the same machine. I want a specific path to be directed to the django API and admin panel, while the rest should load Vue index.html and be passed to Vue router. My problem is, that while the base path is passed on to Vue.js, and my selected path does go through to Django, any other path results in 404, which means that if I want to revisit a path generated though Vue router, it's impossible to do so. I figured the problem must be somewhere in the NginX config file: # the upstream component nginx needs to connect to upstream myproject { server unix:///tmp/myproject .sock; } server { listen 80; listen [::]:80; server_name serverurl.com; return 301 https://serverurl.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl_certificate /home/projects/myproject/ssl/ANY.serverurl.com.crt; ssl_certificate_key /home/projects/myproject/ssl/ANY.serverurl.com.key; server_name serverurl.com www.serverurl.com; access_log /home/projects/myproject/logs/nginx_access.log; error_log /home/projects/myproject/logs/nginx_error.log; location / { root /home/projects/insights/vue/dist; try_files $uri $uri/ /home/projects/myproject/vue/dist/index.html =404; } location /backend/ { include /etc/nginx/uwsgi_params; uwsgi_pass myproject; } location /static/ { alias /home/projects/myproject/static/; } location /media/ { alias /home/projects/myproject/media/; } } So the "/" path results in correctly rendering Vue index.html And "/backend/" correctly loads django urls But, for example, if the … -
How to save file to particular folder?
I have the following code: urls.py: urlpatterns = [ ... url(r'^upload_file', FileFieldFormView.as_view(), name='upload_file'), url(r'^success', lambda request: HttpResponse('Hello World!'), name='hello_world'), ] upload_file.py: from django.views.generic.edit import FormView from ..forms import FileFieldForm import ipdb def handle_uploaded_file(f): ipdb.set_trace() with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class FileFieldFormView(FormView): form_class = FileFieldForm template_name = 'reports/upload_file.html' # Replace with your template. success_url = '/reports/success' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: print("hello") handle_uploaded_file(f) return self.form_valid(form) else: print("invalidated") return self.form_invalid(form) forms.py: from django import forms class FileFieldForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) and upload_file.html template: {% extends "core/layout.html" %} {% block content %} <br/> <h3>{{ title }}</h3> <br/> {% block controls %}{% endblock %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_table }} <button type="submit">Upload</button> </form> {% endblock %} In "files" variable in upload_file.py I get the list of temporary uploaded files and I just want to save them all to particular folder, preliminary checking their type. How can I do it in handle_uploaded_file function? -
How to make the integer field in django models accept float point numbers
Hey I am making an application but requires me to accept input ask percentages and floats. Currently I can only accept input as integers, but I wanted to make it accept floats as well. Thanks -
How to add pagination to a django ReadOnlyModelViewSet or ListAPIView?
I have a Django Restframework project. Here is my view: class JobView(viewsets.ReadOnlyModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer filter_backends = [filters.OrderingFilter, DjangoFilterBackend, filters.SearchFilter] search_fields = [...] ordering_fields = ['jobId'] ordering = ['-jobId'] filterset_fields = ['jobId', 'status'] pagination_class = StandardResultsSetPagination and my pagination class: class StandardResultsSetPagination(LimitOffsetPagination): page_size = 1 The view is registerd in a router: router.register(r'jobs', JobView) The problem is, it does not paginate at all. It just ignores the pagination_class attribute. I also tried: class JobView(generics.ListAPIView) And registered the view without the router. But the problem is the same. It does not paginate and just returns a json list with all jobs. How can achieve pagination in this view without defining it for the project in settings.py globally? -
show specific data in a table django
I have a webpage where it currently shows all the data in 1 page which I do not want it, I want to show a specific data based on the status, like if the status is reception, only the reception status will be shown. This is the current page that I have which it will show all the data which I do not want. What I wanted is this, all the status that is reception will only appear at the logistic page. views.py @login_required(login_url='login') def gallery(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "status"] # Sort the data if (part is not None) and part in valid_sort: allusername = allusername.order_by(part) page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post, 'order_by': part} return render(request, 'photos/gallery.html', context) gallery.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { … -
find users function of availabilities
I have an issue with my projet and related models. Suppose a really basic user model: class User(AbstractUser): """Default user model.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None email = models.EmailField(unique=True) In my app, users have a calendar: class Calendar(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) and then define their availabilities: class Availability(models.Model): calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) date = models.DateField() It was a kind model because in the profile page I can retrieve all availabilities function of a calendar. But, I have an issue when I want to find all users mathing a given availabities. How can I retrieve them ? When playing with others parameters, I use: users = User.petsitters.filter( Q(zipcode=selected_zipcode), Q(proposals__pk=selected_service) ) -
ValueError: Field 'bid' expected a number but got ' '
I am making an Auction website using Django. When is use Migrate command it gives an error "ValueError: Field 'bid' expected a number but got ''.". The code of the models.py file is: from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.base import Model from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.utils import timezone class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return f'{self.category}' class AuctionListing(models.Model): item_name = models.CharField(max_length=100) item_image = models.ImageField(upload_to="products", null=True, blank=True) detail = models.TextField() price = models.IntegerField() last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True) watchers = models.ManyToManyField(User, blank=True, related_name='watched_list') pub_date = models.DateTimeField(null=True) deadline = models.DateTimeField(null=True) list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion') closed = models.BooleanField(default=False) def __str__(self): return f'{self.item_name} - {self.price}' class Bid(models.Model): p_bid = models.IntegerField() user = models.ForeignKey(User, on_delete=CASCADE) auction = models.ForeignKey(AuctionListing, on_delete=CASCADE) bid_date = models.DateTimeField(timezone.now) def __str__(self): return '%s' % (self.bid) class Comment(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) com = models.TextField() pub_date = models.DateField() com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment') def __str__(self): return f'{self.user} - {self.pub_date}' The code of views.py is: from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render …