Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i solve this "POST 400: Bad request"? Using Django REST API and React frontend
i'm pretty new to web development so please forgive me in advance for my ignorance. I'm using React to try to post data into the database managed by django using this method: sendData(data) { const url = "http://127.0.0.1:8080/api/filtros/1/"; const requestOptions = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }; fetch(url, requestOptions); } On the onClick of a NavDropdown React component: <NavDropdown.Item key={item.id} onClick={() => this.sendData({ id: 0, dimension_id: dimension.id, item_id: item.id, usuario_id: 1 }) } > {item.descripcion} </NavDropdown.Item> This is how I register the url on the router using Django: router.register('api/filtros/1', FiltroUsuariosViewSet, 'filtro') My Django ModelViewSet looks like this: class FiltroUsuariosViewSet(viewsets.ModelViewSet): queryset = FiltroUsuarios.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = FiltroUsuariosSerializers And my Django Serializer looks like this: class FiltroUsuariosSerializers (serializers.ModelSerializer): class Meta: model = FiltroUsuarios fields = ('id', 'dimension_id', 'item_id', 'usuario_id') def create(self, validated_data): post = FiltroUsuarios.objects.create(**validated_data) When i click on the Component I get this: POST http://127.0.0.1:8080/api/filtros/1/ 400 (Bad Request) and apparently the error is on the fetch request. Do you guys have any idea on whats the problem? Thanks a lot in advance! -
nginx and django setting for docker-compose
I have setting with nginx and django(named python container). I can access see the top page with localhost:8000, however I cannot fetch the static file nor use API localhost:8000/api/items I am newbee for nginx and django so still confusing. I am planning the setting like this belo normal files browser ->8000 -> nginx -> 8001 ->django for static file django ->8000 -> nginx am it correct???or where should I fix?? These are settings below. docker-composer.yml version: '3' services: python: container_name: python build: ./python command: uwsgi --socket :8001 --module myapp.wsgi --py-autoreload 1 --logto /tmp/mylog.log expose: - "8001" nginx: image: nginx:1.13 container_name: nginx ports: - "8000:8000" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./nginx/static:/static depends_on: - python app_nginx.conf upstream django { ip_hash; server python:8001; } server { listen 8000; server_name 127.0.0.1; charset utf-8; location /static { alias /static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } } server_tokens off; uwsgi_prams uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; -
Name error in django name 'index' is not defined
I am building a travel website.The project name is travel. I am getting the following error message: NameError at / name 'index' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: NameError Exception Value: name 'index' is not defined Exception Location: E:\coding\fyp\travel\app1\views.py in cities, line 20 Python Executable: D:\anacondapython3\python.exe Python Version: 3.7.4 Python Path: ['E:\coding\fyp\travel', 'D:\anacondapython3\python37.zip', 'D:\anacondapython3\DLLs', 'D:\anacondapython3\lib', 'D:\anacondapython3', 'D:\anacondapython3\lib\site-packages', 'D:\anacondapython3\lib\site-packages\win32', 'D:\anacondapython3\lib\site-packages\win32\lib', 'D:\anacondapython3\lib\site-packages\Pythonwin'] Server time: Mon, 23 Mar 2020 15:51:04 +0000 Traceback Switch to copy-and-paste view D:\anacondapython3\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars D:\anacondapython3\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars D:\anacondapython3\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars E:\coding\fyp\travel\app1\views.py in cities return render(request,index.html,{'dests':dests}) … ▶ Local vars My travel urls.py look like: """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL … -
Django Char vs. Varchar
Please Help, I have an existing database that uses a char(12) as its PK. CREATE TABLE sop_customer ( customer_id char(12) NOT NULL, PRIMARY KEY (customer_id), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; I then create a Django Model and create a model based on inspectdb (awesome tool :-)) The problem is when I create another table with a foreign key to this table, the new table will use varchar() and MySQL at the database level will not honour the relationship because of the different types (char vs .varchar) HELP! I am in the process of trying: 1 - Update the existing db to Varchar (seems like a rather extreme operation just to get this thing to work :-0) 2 - Get Django's foreign Key class to recognise the type properly (I understand ORM agnostisism etc). 2 - Force Django to create a char field and then add the constraint after in Django, although I cant see how this could be achieved without heavy lifting 3 - Not use Django Help! -
Django URL language prefix redirect
brand new into programming& django so be gentle with me :) i just implemented (using the docs) bellow form with a drop-down list for language change: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{request.get_full_path }}"/> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option type="submit" value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value={% trans "GO" %} /> </form> All works just as expected so i can use the drop-down list to do the switch. As the value="{{request.get_full_path }}" i get back to the link where i was (which is fine); still just for learning purpose i would like to change this and be redirected to a link with the lang_code in the prefix. I have noticed that the prefix feature is already in place -> http://127.0.0.1:8000/en/Django_book_app_1/ & http://127.0.0.1:8000/fr/Django_book_app_1/ working just fine. How i can implement this already in place feature while still using the drop down list for changing the language (get redirected to the prefix link when switching)? For the … -
How do I move the following code in view to serializer?
I have written the following code, and after review I was told that this is not the correct way, instead I should use DRF and serializer to do the work. I am having hard time to move this code to the serializer. And the problem is, I have done this in every view. See the view below, and please tell me how do I take the help of serializers and get_object to move most of my code in serializer and let it handle the data. The example below takes an email_token and verifies the user if the token is correct. class EmailVerifyView(APIView): def post(self, request, *args, **kwargs): token = request.data['token'] user_obj = get_object_or_404(UserProfile, email_token=token) if user_obj.verified: return Response("Already verified", status=status.HTTP_400_BAD_REQUEST) user_obj.verified = True user_obj.save() return Response("Verified successfully", status=status.HTTP_200_OK) -
Django Convert HTML that has JS charts to PDF
I am trying to build an application that can make Report Cards. These report cards have charts made in ChartJs showing student's growth and development each semester. I need to make these cards into PDF or an Image and then download them. I have already tried XHtml2pdf and it is not able to generate the charts. I just wanna know, is there a way I could covert my HTML ( with JS charts) into PDF or Image. -
I want to add my own qrcode generator to my django application and store the qrcode to my MySQL database
So i was trying to add my own QRCode generator to my django application so that the user info will also be stored into a custom QRCode with an image on the middle. And i want the QRCode to be stored to my database (im using mysql) so that i can display that QRCode on the user dashboard. How do i do that? #models.py from django.db import models from django.contrib.auth.models import User from django_countries.fields import CountryField from phonenumber_field.modelfields import PhoneNumberField from short_text_field.models import ShortTextField class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nama_lengkap = models.CharField(default="", null=False, max_length=30) birthdate = models.DateField(default="") city = ShortTextField(default='', blank=True, help_text="Masukkan nama kota dengan benar") GENDER_CHOICES = (('Laki-laki', 'Laki-laki'), ('Perempuan', 'Perempuan')) gender = models.CharField(choices=GENDER_CHOICES, max_length=10) phone_number = PhoneNumberField(default='+62',null=False, blank=False, unique=True, max_length=15) qrcode = models.ImageField(default="") Akun_Instagram = models.CharField(blank=True, null=False, default="@", max_length=35) bio = models.TextField(default='', blank=True) def __str__(self): return self.user.username #views.py from django.shortcuts import render from accounts.forms import UserForm,UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from PIL import Image from django.contrib.auth.models import User from accounts.models import UserProfileInfo import qrcode def index(request): return render(request, 'templates/landing.html') @login_required def special(request): return HttpResponse("You are logged in !")\ @login_required def user_logout(request): logout(request) … -
Django - context must be a dict rather than ReturnList
I am working on a django project and I have a Post Model, which has this view: class PostListApiView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer filter_backends = [SearchFilter] search_fields = ['user','title','content'] I use this view to create new posts: @method_decorator(login_required, name='dispatch') class PostCreateView(APIView): queryset = Post.objects.all() serializer_class = PostCreateSerializer renderer_classes = [TemplateHTMLRenderer] permission_classes = [IsAuthenticated] template_name = 'post_form.html' def get(self, request, format=None): serializer=PostCreateSerializer() return Response({'serializer':serializer}) def post(self, request): serializer = PostCreateSerializer(data=request.data) if not serializer.is_valid(): return Response({'serializer':serializer}) serializer.save() return redirect('/') I want to consolidate both views into one view, class PostListApiView(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer filter_backends = [SearchFilter] search_fields = ['user','title','content'] renderer_classes = [TemplateHTMLRenderer] template_name = 'post_form.html' but when I try to add the TemplateHTMLRenderer to the ListCreateAPIView, I get this error: Traceback (most recent call last): File "C:\...\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\...\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\...\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\...\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\...\lib\site-packages\rest_framework\renderers.py", line 167, in render return template.render(context, request=request) File "C:\...\lib\site-packages\django\template\backends\django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\...\lib\site-packages\django\template\context.py", line 270, … -
UTF-8mb4 encoding on MySQL in Django Rest Framework shows question marks
I have a site based on Django Rest Framework, with a high amount of non-Latin characters (namely CJV). I have changed my database encoding, my specific table encoding and and the encoding of all of my columns encodings to UTF-8mb4. All of the data is showing in the CMS I have added on top of the site (Wagtails), and in the database, however when I try to make a call to DRF, I get the following (this is inside one of my JSON objects in DRF): "title": "Reason launches the world’s first remote team escape experience: Lola...", "date": "2018-12-15", "rendered": "?????????????? ... When in fact it should look like this: "title": "Reason launches the world’s first remote team escape experience: Lola...", "date": "2018-12-15", "rendered": "佛罗里达州杰克逊维尔 .... As far as I can tell, Django should automatically figure out the correct encoding - but it does not seem to do so here. How do I get DRF to output UTF-8mb4? -
Django, GraphQL query login issue
I was following along with the following tutorial... https://www.howtographql.com/graphql-python/4-authentication/ For the resolve_me query... def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') When I do the query in Insomnia Rest client it works OK. When I do the query in the GraphiQL web interface it works OK. But when I do the query in the Vue/ Apollo code it is returning "Not logged in!". Even after I have logged in via JWT. I have the JWT token in the header auth. When I print user variable above, it returns AnonymousUser in the python server(it returns my username when I do the query in browser with GraphiQL web interface). Vue main.js... const middlewareLink = setContext(() => ({ headers: { authorization: `Bearer ${localStorage.getItem("jwt")}` } })); const link = middlewareLink.concat(httpLink); export const apolloClient = new ApolloClient({ link, cache: new InMemoryCache(), connectToDevTools: true }); Is there any setting or configuration I may be missing? I am using Vue 2.6 and Python 3.8.1 and Django 3.0.3. -
Database error during the test: cannot change column
I changed one field of the model, to create migrations and applied it. There were no errors. But when I try to run the tests, there's an error. django.db.utils.OperationalError: (1833, "Cannot change column 'rfiid': used in a foreign key constraint 'elements_attachments_rfi_id_bc723558_fk_rfis_rfiid' of table 'test_smap_production.elements_attachments'") field that I changed - rfiid. I switched it from Integer to CharField. models.py class Rfis(models.Model): rfiid = models.CharField(max_length=6, primary_key=True) .... The migration was successful, and there is no already created instance of the model in the database. Why such an error occurs and how to correct it? -
NoReverseMatch at / in django3
Reverse for 'delete_order' with no arguments not found. 1 pattern(s) tried: ['delete_order/(?P[^/]+)/$'] This is the error. Dashboard html file after adding the url in Remove link i am getting this error <div class="col-md-7"> <h5>LAST 5 ORDERS:</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for or in orders %} <tr> <td>{{or.product}}</td> <td>{{or.date_created}}</td> <td>{{or.status}}</td> <td><a class = "btn btn-sm btn-info" href="{% url 'update_order' or.id %}">Update</a> </td> <td><a class="btn btn-sm btn-danger"href="{% url 'delete_order' %}">Remove</a> </td> </tr> {% endfor %} </table> This is my views.py file. def updateOrder(request,pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == "POST": form=OrderForm(request.POST,instance=order) if form.is_valid: form.save() return redirect('/') con = {'form':form} return render(request,'food/orderform.html',con) def deleteOrder(request,pk): order = Order.objects.get(id=pk) con={'item':order} return render(request,'food/deleteform.html',con) This is my urls.py file. Last one is the url for delete operation from django.urls import path from . import views urlpatterns = [ path('',views.home, name="home"), path('products/', views.products,name="products"), path('customer/<str:pk_test>/',views.customer,name = "customer"), path('create_order/',views.create_order,name="create_order"), path('update_order/<str:pk>/',views.updateOrder,name="update_order"), path('delete_order/<str:pk>/',views.deleteOrder,name="delete_order"), ] This is the models.py file code from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length = 200,null = True) phone = models.CharField(max_length = 200, null = True) email … -
How to store a polygon field in PostgreSQL and Django?
I am trying to store images in PostgreSQL and a polygon storing coordinates of some shape on top of the image. I tried using PostGIS for the same but it doesn't allow for making polygon on the image being stored rather it shows a map of the globe to mark coordinates on. How can I change it so that it takes coordinates relative to the image I am storing? Here are my models in Django `class Image(models.Model): image_id = models.IntegerField(primary_key=True, unique=True) image_source = models.URLField() provider_id = models.CharField(max_length=20, null=True) def __str__(self): return self.image_source class Annotation(models.Model): annotation_id = models.IntegerField(primary_key=True, unique=True) image_id = models.ForeignKey('Image', on_delete=models.CASCADE) user = models.IntegerField() coordinates = models.PolygonField(null=True) label = models.CharField(max_length=300)` -
form action not working to redirect in django v2
The form action is not redirecting from home.html to password.html in Django 2 even I recheck everything including URL pattern Below I am sharing the basic code. My apologies if it's a basic question as I am very new to Django that's why I may not able to detect the issue. urls.py code from django.urls import path from generator import views urlpatterns = [ path('', views.home), path('password/', views.password), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, 'generator/home.html') def password(request): return render(request, 'generator/password.html') home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Password Generator</h1> <form action="password" method="get"> <select name="length"> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <input type="button" value="Generate Password"> </form> </body> </html> password.py <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Password</title> </head> <body> <h1>Password page</h1> </body> </html> Error Log File Structure -
How to extact all value instance of a model in django views.py
Hy Guys, I have a question for you. I have the following model: from djmoney.models.fields import MoneyField class Totale_Vendite(models.Model): totale_vendite = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_03 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_04 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_05 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_06 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_07 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_08 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_09 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_10 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_11 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_12 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) Each instance rappresents the income on the month utilizing the djmoney app. In my views.py I want to extract for each instance ( ricavi_01, ricavi_02) the "amount" value (not currency). For the moment I have tried only the following way, that is to extract the value individually for each month: def ricavi_dalle_vendite(request): queryset = Totale_Vendite.objects.all() labels = ['Gen','Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'] data = [] for entry in queryset: data.append(str(entry.ricavi_01.amount)) .... how could solve it following the DRY principles??? -
How to redirect to a new id page after submitting a form in Django?
I wanted to redirect to a page that is newly created with the submission of the form. I tried and got a NoReverseMatch error instead. Here's the exception raised: Reverse for 'receive' with keyword arguments '{'id': 15}' not found. 1 pattern(s) tried: ['receive/(?P[0-9]+)$'] Here's the my views: def new_receive(request): """The page for adding a new receive.""" if request.method != 'POST': form = ReceiveForm() else: form = ReceiveForm(data=request.POST) if form.is_valid(): new_receive = form.save(commit=False) new_receive.save() return redirect('imsapp:receive', id=new_receive.id) context = {'form':form} return render(request, 'imsapp/new_receive.html', context) def receive(request, receive_id): """The page for viewing a receive.""" receive = Receive.objects.get(id=receive_id) receipt_no = receive.receipt_no date = receive.date context = {'receive':receive, 'receipt_no':receipt_no, 'date':date} return render(request, 'imsapp/receive.html', context) -
Django forms, iteration over different types of fields with bootstrap css
I looking for method to iterate over fields with bootstrap css. I have two form fields and one should have drop down list and second one is date. If I iterate using {{ field }} I receive what I want. But if I want to use bootstrap field styling i have blank fields. <div class="container"> <form method="POST"> <div class="form-group"> {% csrf_token %} <br> <a class="btn btn-primary btn-sm" href="{% url 'dodaj_ph' numer %}" role="button" name="dodaj_ph">Dodaj PH</a> <br> {% for field in form %} <label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label> <input class="form-control" type="{{ field }}"> {% endfor %} <button type="submit" class="btn btn-primary" name="button">Wypożycz</button> </div> </form> </div> class testerForm(forms.ModelForm): class Meta: model = Tester fields = ('phandlowy', 'data_wypozyczenia') labels = {'phandlowy' : 'Przedstawiciel handl'} ''' ''' class Tester(models.Model): numer_seryjny = models.IntegerField(primary_key=True) licencja_car = models.BooleanField(default=True) licencja_hd = models.BooleanField(default=True) dhandlowiec = models.ForeignKey(DHandlowiec, null=True, on_delete=models.SET_NULL) phandlowy = models.ForeignKey(Phandlowy, null=True, on_delete=models.SET_NULL, blank=True) wypozyczony = models.BooleanField(default=True) data_wypozyczenia = models.DateField(blank=True, null=True) problemy = models.CharField(max_length=2000, default="Brak problemów") history = HistoricalRecords() ''' -
Celery Task Running number of server times
I am having one issue with Celery tasks which are running a number of server times. I am using Django and Tastypie for building APIs and I am using Celery and Elaasticache Redis for periodic tasks. version details are as below: Django==1.9.4 celery==3.1.20 django-celery==3.1.17 So the main issue which I am facing right now is my periodic tasks are running number or server times as we have auto-scaling enabled. so for example, there are 3 servers after auto-scaling then the same periodic tasks are running parallelly. I am registering periodic tasks through djcelery admin panel. so can someone please help me with the above issue? any help would be highly appreciated. let me know if you need more details on same issue. thanks. -
Django button menu & generic page for product
I would like to know how to display other bikes by clicking on the button "urbain" for example here is my piece of code: <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <div class="filter-control"> <ul> <li class="active">Pliable</li> <li>Urbain</li> <li>Route</li> <li>VTT</li> </ul> </div> <div class="product-slider owl-carousel"> {% for velo in pliable %} <div class="product-item"> <div class="pi-pic"> <img src="{{ velo.image }}" alt=""> </div> <div class="pi-text"> <div class="catagory-name">{{ velo.slogan }}</div> <a href="#"> <h5>{{ velo.model }}</h5> </a> <div class="product-price"> {{ velo.prix }} </div> </div> </div> {% endfor %} </div> </div> </div> </div> enter image description here I have a second problem which resembles the first. I have a generic page for my products and I would like when I click on the button "VTT" it sends me back to this page with only "VTT", I already have a piece of code but I cannot pass him the query <li class="active"><a href="{% url 'index' %}">Accueil</a></li> <li><a href="{% url 'shop' %}">Vélo</a> <ul class="dropdown"> <li><a href="{% url 'shop' %}" name="Urbain">URBAIN</a></li> <li><a href="{% url 'shop' %}" name="Route">ROUTE</a></li> <li><a href="{% url 'shop' %}" name="VTT">VTT</a></li> <li><a href="{% url 'shop' %}" name="Trekking">TREKKING</a></li> <li><a href="{% url 'shop' %}" name="SpeedBike">SPEED BIKE</a></li> <li><a href="{% url 'shop' %}" name="pliant">PLIABLE</a></li> </ul> </li> my views.py def shop(request): product = … -
Using the object id in django forms
Why can't I access the object id in the def clean(self)? I get the error `'CheckInForm' object has no attribute 'id'. forms.py from django import forms from .models import Student from django.core.exceptions import ValidationError class CheckInForm(forms.ModelForm): class Meta: model = Student fields = ['room', 'name'] widgets = {'room': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') if Student.objects.filter(room=new_room).count() > 3: print(Student.objects.filter(room=new_room).count()) if not Student.objects.filter(room=new_room, id=self.id): raise ValidationError('The room is full') models.py class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, db_index=True) room = models.CharField(max_length=8, db_index=True, blank=True) -
What is the best way to display the value of a model function in a Django ModelAdmin change form view?
I have a model, say MyModel, represented by a few fields, and a function that I can display the output of on the model's change list page as follows: models.py class MyModel(models.Model): my_field = models.CharField(max_length=1000) def my_function(self): return 'Hello world' my_function.admin_order_field = 'hello' my_function.allow_tags = True my_function.short_description = 'Hello!' admin.py class MyModelAdmin(admin.ModelAdmin): model = MyModel fields = ['my_field', 'hello'] list_display = ['my_field', 'hello'] This works fine for the change list page, but when I view the change form I get AttributeError: 'MyModel' object has no attribute 'hello'. What's the best way of making the output of the model's function visible on the change form page? -
can't get the POST parameters in django
I am trying to make a login-page using django, I am facing troubles in getting POST parameters login view: def ProcLogin(request): if request.method == 'POST': account_name = request.POST.get('username','') password = ToMd5(request.POST.get('password','')) if not account_name or not password: return HttpResponse("invalid input") template code: <form method="post" action="{% url 'Main:login' %}" class="login_form"> {% csrf_token %} <div class="form-group text-right"> <label for="username">User name:</label> <input id="username" type="text" class="form-control box_shadow"> </div> <div class="form-group text-right"> <label for="password">Password: </label> <input id="password" type="password" class="form-control box_shadow"> </div> <button type="submit" class="login_btn"></button> </form> Output when testing it: [invalid input][1][1]: https://i.stack.imgur.com/N6A9a.png everything is supposed to be correct except the results aren't. Thank you. -
Django xhtml2pdf Invalid color value 'initial'
In my django application i use xhtml2pdf for convert an html template in pdf file. This is the part of my html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="UTF-8"> <title>Documento senza titolo</title> <style type="text/css"> body {margin:0;padding:0;background-color:#FAFAFA;font:8pt "Tahoma";} * {box-sizing:border-box;-moz-box-sizing:border-box;} table, th, td {border:1px solid black;border-collapse:collapse;} .page {width: 21cm; min-height: 29.7cm;padding: 1cm; margin: 1cm auto;border: 1px #D3D3D3 solid;border-radius: 5px; background: white;box-shadow: 0 0 5px rgba(0, 0, 0, 0.1)} p {margin:0;padding:0;line-height:1.4em} .column-50-left {width:49.5%;display:inline- block;vertical-align:top;padding-right:15px} .column-50-right {width:49.5%;display:inline-block;vertical-align:top;padding-left:15px} .invoice {font-size:6pt} .invoice td {height:50px;vertical-align:top;padding:5px;} .destinatario td {height:120px;vertical-align:top;padding:5px;font-size:6pt} .description th {height: 30px} .description td {height: 360px} .top-10 {margin-top:10px} .top-15 {margin-top:15px} .top-20 {margin-top:20px} .padding-top-4 {padding-top:4px} .padding-bottom-15 {padding-bottom:15px} .padding-bottom-30 {padding-bottom:30px} .border-top {border-top:1px solid #000000} @media print { html, body {width:210mm;height:297mm;padding:0px;margin:0px} .page {margin:0;border:initial;border-radius:initial;width:initial;min-height:initial;box-shadow:initial;background:initial;page-break-after:always;padding:0px;margin:0px} } when i run code and pdf was created i get error: Invalid color value 'initial' i found 'initial' values in @media print directive. How have i to use instead the 'initial' for print my document? so manu thanks in advance -
how can make Personality Test with Django? [closed]
I am building a site through django. I want to create various functions related to psychology. It is considered the simplest of them, but there are some that have yet to be found. It's the personality test app. I think it's really simple, but I don't know how to implement it. For example, personlality test question is: Do you get angry easily? (1 to 7 points) Are you good at keeping your temper? (1 to 7 points) **when user press the button, it save the score of each question. and according to the internal formula , value is caculated [for example, (No. 1 Score + 8 - No. 2 score)}/2] , I want to show score for user visually. (User's score vs. Average of existing studies / graph or something else)** If you have any tips, please help me! Thank you for reading