Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove none fileds from django templates
I created a django template with the following model Models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') product1 = models.CharField(max_length=500,default=0,blank=True,null=True) product1_quantity = models.IntegerField(default=0,blank=True,null=True) product2 = models.CharField(max_length=500,default=0, blank=True,null=True) product2_quantity = models.IntegerField(default=0,blank=True,null=True) product3 = models.CharField(max_length=500,default=0, blank=True,null=True) product3_quantity = models.IntegerField(default=0,blank=True,null=True) product4 = models.CharField(max_length=500,default=0, blank=True,null=True) product4_quantity = models.IntegerField(default=0,blank=True,null=True) product5 = models.CharField(max_length=500,default=0, blank=True,null=True) product5_quantity = models.IntegerField(default=0,blank=True,null=True) product6 = models.CharField(max_length=500,default=0, blank=True,null=True) product6_quantity = models.IntegerField(default=0,blank=True,null=True) product7 = models.CharField(max_length=500,default=0, blank=True,null=True) product7_quantity = models.IntegerField(default=0,blank=True,null=True) product8 = models.CharField(max_length=500,default=0, blank=True,null=True) product8_quantity = models.IntegerField(default=0,blank=True,null=True) and I tried displaying this data on the template using this view def load_salesorder(request): so_id = request.GET.get('sales_order') s_o = MaterialRequest.objects.filter(pk=so_id) print("kits=========",s_o) return render(request, 'allotment_so.html', {'sales_order': s_o}) HTML <table class="table table-bordered"> <thead> <tr> <th>Product Short Codes</th> <th>Product Quantity</th> </tr> </thead> <tbody> <div class="table-container"> {% for i in sales_order %} <tr> <td class="align-middle">{{ i.product1 }}</td> <td class="align-middle">{{ i.product1_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product2 }}</td> <td class="align-middle">{{ i.product2_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product3 }}</td> <td class="align-middle">{{ i.product3_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product4 }}</td> <td class="align-middle">{{ i.product4_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product5 }}</td> <td class="align-middle">{{ i.product5_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product6 }}</td> <td class="align-middle">{{ i.product6_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product7 }}</td> <td class="align-middle">{{ i.product7_quantity }}</td> </tr> <tr> <td class="align-middle">{{ i.product8 }}</td> <td class="align-middle">{{ i.product8_quantity }}</td> </tr> … -
Customize schema of dango REST's framework for documentation
I am trying to document my APIs with the inbuilt REST documentation for APIs. I get it to render all my endpoints which is great. Now I want to customize the schema but I am unsure how to achieve that. I know that swagger has a schema generator but I would like to tweak what django already provides me. I am going this so far by doing: API_TITLE = "title" API_DESCRIPTION = "description" urlpatterns = [ path('docs/', include_docs_urls( title=API_TITLE, description=API_DESCRIPTION, permission_classes=[IsAdminUser]) ), that renders me all my endpoint. I add a screenshot. I would like for instance to fill the description for the thus far empty fields. I also would like to delete some stuff. I am not really clear on how to use schemas and how manipulate them and use them in django. I also can't find docs that are comprehensible to me. I know they are in .yml format but how can I get them and manipulate them? Or how can I build my own? Can someone help me with this? Thanks in advance, very much appreciated! I would like to delete for example the grey boxes and fill the blanks in the description. -
How do I return a list in a Django Annotation?
Right now I have the following, very slow but working code: crossover_list = {} for song_id in song_ids: crossover_set = list(dance_occurrences.filter( song_id=song_id).values_list('dance_name_id', flat=True).distinct()) crossover_list[song_id] = crossover_set It returns a dictionary where a song ID is used as a dictionary key, and a list of integer values is used as the value. The first three keys are the following: crossover_list = { 1:[38,37], 2:[38], .... } Does anyone here know of a succinct way to wrap this up into a single query? The data exists in a single table that has three columns where each song_id can be associated with multiple dance_ids. song_id | playlist_id | dance_id 1 1 38 1 2 37 2 1 38 Ideally, what I am trying to figure out how to return is: <QuerySet[{'song_id':1, [{'dance_id':38, 'dance_id':37}]}, {'song_id':2, [{'dance_id':38}]}]> Any ideas or help is appreciated. -
My django template navbar is not working properly
Here I have two template called base.html and contact.html.contact.html extends the base.html.I only have these two templates.When i click blog or about it scrolls me to the about section or blog section. But the problem is while going to the contact page and when I try to click the any of the url in nav bar home or about from contact page it doesn't go anywhere.How can I solve this? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('contact/', views.contact, name='contact'), views.py def home(request): abt_me = Me.objects.order_by('-created').first() return render(request,'base.html',{'abt':abt_me}) def contact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact = form.save() messages.success(request, 'Hello {}!. Your message has been sent successfully'.format(contact.full_name)) return redirect('contact') return render(request,'contact.html',{'form':form}) base.html <nav class="site-navigation position-relative text-right" role="navigation"> <ul class="site-menu main-menu js-clone-nav mr-auto d-none d-lg-block"> <li><a href="#home" class="nav-link">Home</a></li> <li><a href="#blogs" class="nav-link">Blog</a></li> <li><a href="#about" class="nav-link">About</a></li> <li><a href="{% url 'contact' %}" class="nav-link">Contact</a></li> </ul> </nav> <div class="site-section" id="about"> <div class="container"> <div class="row "> contact.html {% extends 'base.html' %} {% load static %} {% block content %} <section class="site-section"> -
Create an event to update a table depending on entries from 2 other tables
Ok so I have these three tables created by my Django models in MariaDB: I want to create a daily event to update "LastInspected" in moorings_part whenever someone adds an inspection item. This should be the latest moorings_inspectionreport.Date available with an InspectionID_id which relates to the relevant moorings_inspection.PartID_id. It's really confusing me with not only the ordering by dates but trying to juggle 3 tables for this too. -
Django Rest Framework Not Null Error when creating from payload
I'm trying to write a test to check that the create method of my Viewset works ok: @pytest.mark.django_db def test_create(admin_user): parent = factories.ParentFactory() payload = { 'name': 'child', 'parent_id': parent.pk, } view = views.ParentViewSet.as_view({'post': 'create'}) request = factory.post('/', payload, format='json') force_authenticate(request, user=admin_user) response = view(request) assert response.status_code == status.HTTP_201_CREATED assert models.Child.objects.count() == 1 child = models.Child.objects.first() assert child.name == 'child' However, I get the following error when I run the code: psycopg2.errors.NotNullViolation: null value in column "parent_id" violates not-null constraint But the test for the Parent create method runs fine: def test_create(admin_user): payload = { 'name': 'parent', 'children': [ { 'name': 'child', } ], } view = views.ParentViewSet.as_view({'post': 'create'}) request = factory.post('/', payload, format='json') force_authenticate(request, user=admin_user) response = view(request) assert response.status_code == status.HTTP_201_CREATED assert models.Parent.objects.count() == 1 season = models.Parent.objects.first() assert season.name == 'parent' assert season.children.count() == 1 Can someone tell me the correct way to write the payload for the child test create? -
Django-ORM select columns from two tables
I have two models and one model has generic foreign key relation I want select the columns from both the tables. Can anyone help -
Django - Import_Export Custom Validation
Im using django import_export to upload data from excel. I want to customise the validation errors to warnings that everybody can understand, For example: NON-NULL Value Error ---> Hey there, please make sure there are no empty cells in the datasheet. Ive looked into the import_export library but I couldnt find any validation at all. Thank you for any suggestions -
Django selenium: i18n partially works
I currently develop a Django project and have a functional test using selenium. It was running until I internationalize my app. I do not understand why some 'send_keys' correctly use the translation but other do not. I try to find out how different are input that do not work but can't find. test.py from django.utils.translation import ugettext_lazy as _ # from django.utils.translation import ugettext as _ def test_randomisation(self): self.selenium.find_element_by_xpath('//*[@id="navbarSupportedContent"]/ul[1]/li[5]/a').click() PatientCode = self.selenium.find_element_by_xpath('//*[@id="table_id"]/tbody/tr[1]/td[1]').text self.selenium.find_element_by_xpath('//*[@id="table_id"]/tbody/tr[1]/td[4]/a').click() PatientCodeFormulaire = self.selenium.find_element_by_xpath('/html/body/div[1]/div[1]/div[1]').text self.assertEqual(PatientCodeFormulaire[14:24],PatientCode) ran_inv = self.selenium.find_element_by_xpath('//*[@id="id_ran_inv"]') ran_inv.send_keys('Slater') ran_pro = self.selenium.find_element_by_xpath('//*[@id="id_ran_pro"]') **ran_pro.send_keys(_('On-line'))** # problem here ran_pro_per = self.selenium.find_element_by_xpath('//*[@id="id_ran_pro_per"]') ran_pro_per.send_keys('Iron') ran_crf_inc = self.selenium.find_element_by_xpath('//*[@id="id_ran_crf_inc"]') **ran_crf_inc.send_keys(_('Yes'))** # problem here ran_tbc = self.selenium.find_element_by_xpath('//*[@id="id_ran_tbc"]') ran_tbc.send_keys(_('Possible')) ran_crf_eli = self.selenium.find_element_by_xpath('//*[@id="id_ran_crf_eli"]') **ran_crf_eli.send_keys(_('Yes'))** # problem here ran_cri = self.selenium.find_element_by_xpath('//*[@id="id_ran_cri"]') **ran_cri.send_keys(_('Yes'))** # problem here ran_sta = self.selenium.find_element_by_xpath('//*[@id="id_ran_sta"]') ran_sta.send_keys(_('Mild')) ran_vih = self.selenium.find_element_by_xpath('//*[@id="id_ran_vih"]') ran_vih.send_keys(_('Negative')) django.po # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-12-06 10:03+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: .\intenseTBM_eTool\settings.py:160 msgid "English" msgstr "Anglais" #: … -
Django: Unable to load admin page and HTML page using TemplateView.as_view()
I used the django-twoscoops project template to setup a simple project (made some modifications to use django 2.2.5). My project urls.py looks like this: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.views.generic import TemplateView urlpatterns = [ # Landing page. path('', TemplateView.as_view(template_name='base.html')), # Admin. path('admin/', admin.site.urls), # Apps. path('polls/', include('apps.polls.urls')), ] I ran check and no issues were found. When I run the server, and connect to 127.0.0.1:8000/admin/ I get an error. However, if I go to 127.0.0.1:8000/polls/ the polls page loads OK. I also get an error if I try to go to 127.0.0.1:8000 (it complains base.html is not found and I don't understand why it is looking at a different path). I am not sure what I am doing wrong. Admin error: OSError at /admin/login/ [Errno 22] Invalid argument: 'C:\\Users\\drpal\\PycharmProjects\\tvpv_portal\\:\\admin\\login.html' Landing page error: OSError at / [Errno 22] Invalid argument: 'C:\\Users\\drpal\\PycharmProjects\\tvpv_portal\\:\\base.html' For landing page, I have set 'DIRS' in TEMPLATE dictionary to point to C:\Users\drpal\PycharmProjects\tvpv_portal\templates which contains base.html, so I'm not sure why it is looking one directory above. The settings are shown below but I am not sure what the culprit could be: ABSOLUTE_URL_OVERRIDES {} ALLOWED_HOSTS [] APPEND_SLASH True AUTHENTICATION_BACKENDS … -
Docker compose executable file not found in $PATH": unknown
but I'm having a problem. Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 0 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ compose.yml : version: '3' services: db: image: postgres volumes: - ./docker/data:/var/lib/postgresql/data environment: - POSTGRES_DB=sampledb - POSTGRES_USER=sampleuser - POSTGRES_PASSWORD=samplesecret - POSTGRES_INITDB_ARGS=--encoding=UTF-8 django: build: . environment: - DJANGO_DEBUG=True - DJANGO_DB_HOST=db - DJANGO_DB_PORT=5432 - DJANGO_DB_NAME=sampledb - DJANGO_DB_USERNAME=sampleuser - DJANGO_DB_PASSWORD=samplesecret - DJANGO_SECRET_KEY=dev_secret_key ports: - "8000:8000" command: - python3 manage.py runserver volumes: - .:/code error : ERROR: for django Cannot start service django: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"python3 manage.py runserver\": executable file not found in $PATH": unknown At first, I thought Python Manage was wrong. But i tried command ls , To my surprise, I succeeded. Then I tried the ls -al command, but it failed. I think the addition of a command to write space is causing a problem. how can i fix it ? -
Django - how to run background script in loop
I have install django 3.0 and I want to add on website bot which will listen for events in background, manage server and users. Bot is dedicated for teamspeak application, using https://github.com/benediktschmitt/py-ts3/tree/v2 simple code: import time import ts3 with ts3.query.TS3ServerConnection("telnet://localhost:25639") as ts3conn: ts3conn.exec_("auth", apikey="AAAA-....-EEEE") # Register for events ts3conn.exec_("clientnotifyregister", event="any", schandlerid=0) while True: event = ts3conn.wait_for_event() print(event.parsed) How can I run this in django background, I have try add code with asyncio to manage.py but teamspeak bot connect to server and website doesn't work Shoud I use Celery, django-background-task or just add it as app, how to manage events received by bot in django? -
Django 1.11 error while trying to post data
I'm new to Django 1.11 LTS and I'm trying to solve this error from a very long time. Here is my code where the error is occurring: model.py: name = models.CharField(db_column="name", db_index=True, max_length=128) description = models.TextField(db_column="description", null=True, blank=True) created = models.DateTimeField(db_column="created", auto_now_add=True, blank=True) updated = models.DateTimeField(db_column="updated", auto_now=True, null=True) active = models.BooleanField(db_column="active", default=True) customer = models.ForeignKey(Customer, db_column="customer_id") class Meta(object): db_table="customer_build" unique_together = ("name", "customer") def __unicode__(self): return u"%s [%s]" % (self.name, self.customer) def get(self,row,customer): build_name = row['build'] return self._default_manager.filter(name = build_name, customer_id = customer.id).first() def add(self,row): pass Views.py block: for row in others: rack_name = row['rack'] build = Build().get(row,customer) try: rack = Rack().get(row,customer) except Exception as E: msg = {'exception': str(E), 'where':'Non-server device portmap creation', 'doing_what': 'Rack with name {} does not exist in build {}'.format(rack_name,build.name), 'current_row': row, 'status': 417} log_it('An error occurred: {}'.format(msg)) return JsonResponse(msg, status = 417) Error traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./customers/views.py", line 2513, in create_rack add_rack_status = add_rack(customer, csv_file) File "./customers/views.py", line 1803, in add_rack build = Build().get(row,customer) File "./customers/models.py", … -
ModuleNotFoundError: No module named 'C:\\Python\\Scripts'
I'm self-learning the Django and following the 'writing your first Django app' tutorial. I can start new projects. but when I ran ...\> py manage.py runserver to check the project. ModeleNotFoundError occurs. It says ModuleNotFoundError: No module named 'C:\Python\Scripts' I have no idea why this is happening. It used to work well until this happened recently. I would greatly appreciate any help. Thanks! -
How to create a form for feeding multiple object entries based on a query in django?
I am currently working on my college management application, where staff can enter internal marks of students and the student can view their marks. What i am stuck with is, i want a populate a list of forms to fill the internal marks of each student and submit it at once. I tried modelformset with the code below and it work exactly as below formset = modelformset_factory(Internal, fields=('student','marks1','marks2','marks3')) if request.method == "POST": form=formset(request.POST) form.save() form = formset() return render(request, 'console/academics/internals.html',{'form':form}) For the model class Internal(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks1 = models.IntegerField(default=0) marks2 = models.IntegerField(default=0) marks3 = models.IntegerField(default=0) marks = models.IntegerField(default=100) marksob = models.IntegerField(default=0) def save(self): self.marksob = (self.marks1 + self.marks2 + self.marks3)/15 return super(Internal, self).save() I want the form to be rendered in html using <input> and not passing {{form}} in html. And moreover I want the form to display only the entries of particular students based on a query. Can anyone help me on this? -
django.db.migrations.exceptions.NodeNotFoundError: Migration analytics.0002_auto_20140827_1705
I have created new app catalogue and while doing migrations getting django.db.migrations.exceptions.NodeNotFoundError: Migration analytics.0002_auto_20140827_1705 dependencies reference nonexistent parent node ('catalogue', '0001_initial') my Catalogue.models.py is from oscar.apps.catalogue.abstract_models import AbstractProductImage class ProductImage(AbstractProductImage): name = models.CharField(max_length=64) from oscar.apps.catalogue.models import * init.py default_app_config = 'catalogue.apps.CatalogueConfig' apps.py class CatalogueConfig(apps.CatalogueConfig): name = 'catalogue' label = 'catalogue' verbose_name = 'Catalogue' -
Django one field and multiple Formset
In Django, I want to create a form that involves 2 Models - a Library model and a Book model. The Library can contain multiple Books. class Library(models.Model): name = models.CharField(max_length=100) class Book(models.Model): for_library = models.ForeignKey(Library, null=False, on_delete=models.PROTECT) title = models.CharField(max_length=200) author = models.CharField(max_length=100) Now, I have created a Library with id=1 and now want to create a form to tag multiple books to the library. How can I create the form such that the fields look like (including pre-filling the library ID): Library: <id=1 Library> Book1 Title: _____ Book1 Author: _____ Book2 Title: _____ Book2 Author: _____ The furthest I have gone is: BookFormset = inlineformset_factory(Library, Book, fields=['title', 'author'], form=CreateBookForm, extra=2, min_num=1, max_num=20, can_delete=True) But cannot continue and am not sure of integrating this with views.py. Any help on this? -
Similar Image api drf
I am trying to make api for similar image based on keyword with drf search filter: models.py: class Image(models.Model): title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) image_keyword = models.TextField(max_length=1000) def __str__(self): return self.title views.py: class DynamicSearchFilter(filters.SearchFilter): def get_search_fields(self,view,request): return request.GET.getlist('search_fields',[]) class SimilarImageView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] search_fields = ['image_keyword','id'] filter_backends = (DynamicSearchFilter,) queryset = Image.objects.all() serializer_class = ImageSearchSerializer what i want to achieve is that if i add keyword 'lake nature ocean' it should show all the images which contain keyword lake or nature or ocean but search filter show only image which keyword contain lakenatureocean keyword -
Getting empty file from response and not able to save the file in django models class
My task is to create .xlsx file of late employees and return it to download at the same time I should create an object for every day with fields day and list(.xlsx). My implementation code is: ... file = excel_file.save('my_data.xlsx') day = Day.objects.create(days_date=timezone.now(), days_file=File(file)) response = HttpResponse(file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',) response['Content-Disposition'] = 'attachment; filename={date}-attendance.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d'),) return response There are no error messages but the file from response is empty, for the class object doesn't exist my models.py: class Day(models.Model): days_date = models.DateField() days_file = models.FileField(upload_to='day/') def __str__(self): return '{date}'.format(date=timezone.now().strftime('%Y-%m-%d')) I am using django==2.2 and I am using Linux ubuntu OS -
On looping through django allauth social login profile pictures
I've been trying to loop through the social login account photos of the users and myself on the app that I'm doing. Currently, I have a different model for the contributors on the app that is shown on the homepage and on a separate page. The models of my pages app is class Volunteers(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to="volunteers/") def __str__(self): return self.name class Meta: verbose_name = "volunteer" verbose_name_plural = "volunteers" The profile page has {% if object == request.user %} ... <img class="rounded-circle account-img center-align" src="{{ user.socialaccount_set.all.0.get_avatar_url }}"> ... {% endif %} Since cookiecutter-django has a default users model, I imported the views of the model to my pages app to try and see if it will show on the home page. The default cookiecutter-django model for the users is class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) The view on the pages app is from pages.users.models import User def home(request): ... users = User.objects.all() ... context = {"user": user } return render(request, pages/home.html, context) The for loop on the template is {% for u in … -
How to Append/Include
I have the following line of code in my index.html {% csrf_token %} <div class="form-group"> <input type="text" id="form_name" class="form-control" name="name" required="required" placeholder="Your Full Name" value='{% if submitbutton == "Submit" %} {{ name }} {% endif %}'> </div> <div class="form-group"> <input type="email" id="form_email" class="form-control" name="email" required="required" placeholder="abc@email.com" value='{% if submitbutton == "Submit" %} {{ email }} {% endif %}'> </div> <div class="form-group"> <textarea name="message" id="form_message" rows="5" class="form-control" required="required" placeholder="Add your message." value='{% if submitbutton == "Submit" %} {{ message }} {% endif %}'></textarea> </div> <input type="submit" class="btn btn-outline-light btn-sm" value="Send Message" name="Submit"> </form> and for views.py def index(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] try: send_mail( name, message, email, ['cmadiam@ruthlymtspmuandaesthetics.com'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('Success! Thank you for your message.') return render(request, "index.html", {}) Now, I want add New Inquiry from: before the name(subject) when the email is received. How can I do that. Is that possible? Thank you in advance! -
Move div to next line
In my django templates some fields are created using multiple divs but all the columns are coming in a single row HTML <div class="row product-form-row"> <form method="post" id="Outwarddocketform" data-kit-url="{% url 'client:ajax_load_kit_c' %}" data-product-url="{% url 'client:ajax_load_product_c' %}" onkeyup="add()" class="col-md-10 proct-form" novalidate> {% csrf_token %} <div class="form-group col-md-3 mb-0"> {{ form.transaction_date|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.dispatch_date|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.sending_location|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.flow|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.kit|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.transporter_name|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.vehicle_details|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.invoice_number|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.remarks|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.created_for|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.product1|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.product1_quantity|as_crispy_field }} </div> <div id="products-table" class="col-md-12 col-sm-8 col-12 product-table-ajax"></div> <div class="form-group col-md-12 mb-0"> <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'client:inward_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </div> </form> This creates a page like this: I want to move product1 or product1 quantity to the next line. How can I do that ? Basically what i want to do is shown below: -
Cannot Install Pillow with Python 3.6
I downloaded the Pillow package for my offline computer and tried installing it locally with this command: pip install Pillow-6.2.1.tar.gz But it gives the following error: The headers or library files could not be found for zlib Then I tried installing it with Python 3.7, 3.8 and it gives the same error. -
Can’t sort elements to categories
Im writing an online store, which is why I need the list of goods to be sorted in categories Eventually, the right path does generate, but there is no content on the page. Where might I made a mistake? models.py class Category(models.Model): class Meta(): db_table = 'category' ordering = ['name'] verbose_name_plural = 'Категории' name = models.CharField(max_length=150, unique=True, verbose_name='Категория') slug = models.SlugField(verbose_name='Транслит', null=True) def __str__(self): return self.name def __unicode__(self): return self.name class Merchandise(models.Model): title = models.CharField(max_length=50,verbose_name='Имя товара') image = models.ImageField(upload_to='user_images',default='default.jpg',verbose_name='Изображение') price = models.CharField(max_length=15,verbose_name='Цена') text = models.TextField(max_length=150,verbose_name='Описание') category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name='Категория') views.py There was a pagination func primarily def category(reguest, slug): category = Category.objects.get(slug=slug) merch = Merchandise.objects.filter(category=category) return render(reguest, 'mainpage/category.html', { 'category': category, 'merch': merch}) def mainpage(request): data = { 'goods': Merchandise.objects.all(), 'slides': Slide.objects.all(), 'categories': Category.objects.all(), 'title': 'CyberGear' } return render(request,'mainpage/home.html',data) category.html {% extends 'mainpage/main.html' %} {% for mer in merch %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{{ mer.image.url }}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{{ mer.title }}</a> </h4> <h5>{{ mer.price }}</h5> <p class="card-text">{{ mer.text }}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> </div> </div> {% endfor %} and urls.py url(r'^category/(<slug>)/$',views.category,name'category'), -
I don't know where i mess up with my code in my view
from django.http import HttpResponse from django.shortcuts import render,redirect, get_list_or_404, get_object_or_404 from .models import Users from .forms import UsersForm from django.contrib.auth import authenticate # Create your views here. def login(request): #Username = request.POST.get(‘username’) #password = request.POST.get(‘password’) form = UsersForm(request.POST or None) if form.is_valid(): form.save() form = UsersForm() return redirect('/product/itemlist') user = authenticate(username='username', password='password') if user is not None: # redirect to homepage return redirect('/product/itemlist') else: # display login again return render(request, 'users/login.html', {'form':form}) This is my view page when i runserver it takes me to login page then the problem start when i enter my credintials and try to log in Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/users/login/index.html Using the URLconf defined in mazwefuneral.urls, Django tried these URL patterns, in this order: admin/ product/ users/ login/ [name='login'] main/ accounts/ The current path, users/login/index.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is the error am getting