Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception Value: NOT NULL constraint failed: send_appdata.product_id_id
I am using a custom user model and when i am trying to reference it in other model i am getting an error. Exception Value: NOT NULL constraint failed: send_appdata.product_id_id views.py from django.contrib.auth import get_user_model AppOnboarding = get_user_model() # get data from json @api_view(['POST']) def index(request): product_id = AppOnboarding.objects.get(pk=request.data['product_id']) product_name = request.data['product_name'] product_url = request.data['product_url'] subject = request.data['subject'] body = request.data['body'] recipient_list = request.data['recipient_list'] sender_mail = request.data['sender_mail'] email_type = request.data['email_type'] broadcast_mail = request.data['broadcast_mail'] email_status = status.HTTP_200_OK location = request.data['location'] # make an object of AppData app_data = AppData(product_id=product_id, product_name=product_name, product_url=product_url, subject=subject, body=body, recipient_list=recipient_list, sender_mail=sender_mail, email_type=email_type, broadcast_mail=broadcast_mail, email_status=email_status, location=location) # save it to DB app_data.save() models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth import get_user_model AppOnboarding = get_user_model() class AppData(models.Model): # app_data_id = models.IntegerField(primary_key=True) product_id = models.ForeignKey(AppOnboarding, on_delete=models.PROTECT) product_name = models.CharField(max_length=100) product_url = models.URLField() subject = models.CharField(max_length=100) body = models.TextField() recipient_list = models.TextField() sender_mail = models.EmailField(max_length=254) email_type = models.CharField(max_length=50) broadcast_mail = models.BooleanField() email_status = models.CharField(max_length=50) date_time = models.DateTimeField(auto_now_add=True) location = models.CharField(max_length=100) AppOnboarding is a custom user model in a different app. I explored the similar questions but could not resolve the issue. Any help is highly appreciated. -
Display datetime after selection
I'm using XDSoft datetime picker as inlined <form id="dateForm" action="" method="post"> {{ form }} <script> $(function () { $("#id_scheduled_time").datetimepicker ({ format: 'd - m - Y H:i', inline:true, ... }); }); </script> </form> How can I display the picked datetime value beside the calendar ? I've tried this: var logic = function( currentDateTime ) { div = document.getElementById( 'fieldWrapper' ) div.insertAdjacentHTML( 'beforeend', currentDateTime ); }; but nothing is displayed beside the calendar. This is working but I don't want to use an alert: var logic = function( currentDateTime ) { alert( currentDateTime ); }; -
local variable prblem with the JS code in pycharm
I am running in issues with the pycharm, down below i have the whole sets of home html/css.js. It is interesting how the code i have it works here , also when i try in VScode it works, but when i try to run in my django project in pycharm it says "introduce local variable". Is there anything i am missing? Thank You. $(document).ready(function() { $(".carousel").carousel(); }); .carousel { position: relative; top: 100px; height: 250px; perspective:175px; } .carousel .carousel-item { width: 450px; } .carousel .carousel-item img { width: 100%; border-radius: 10px 10px 0 0; } .carousel .carousel-item h2 { margin: -5px 0 0; background: #fff; color: #000; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 3em; text-align: center; } <html lang=""> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <link rel="stylesheet" href="/Main/static/blog/imageslider.css" /> <script src="/Main/static/functionality/imageslider.js"></script> <title></title> </head> <body> <div class="carousel"> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt="" /> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> <a class="carousel-item" href="#" ><img src="/Main/static/pics/photo-1454942901704-3c44c11b2ad1.jpg" alt=""/> <h2>3D CAROUSEL</h2> </a> </div> </body> </html> -
'NoReverseMatch at /blog/' even when asking for a list view the program looks for a detail view
This question comes from the book 'Django 2 by example', and has been asked many times before, but even though I checked all the answers I can't fix the problem. The only thing I am doing differently from the book is creating the 'blog' app inside a 'my_project' project (which contains other apps) rather than inside a 'mysite' project directory. my error looks like this: my_project/urls.py """my_project 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 to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from person import views from accounts.views import RegisterView # register urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name='home'), path('person/', include('person.urls')), path('create/', include('person.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/register/', RegisterView.as_view(), name='register'), path('shopping-cart/', include('shopping_cart.urls')), path('blog/', include('blog.urls', namespace='blog')), ] my blog/urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = … -
Django.core.exeptions.ImproperlyConfigured: the included URLconf does not appear to have any patterns in it
from django.contrib import admin from django.urls import path, include import Echo.urls import users.urls #this is the urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('Echo.urls', namespace='Echo')), path('users/', include('users.urls', namespace='users')) ] help? anything will appreciate. django on visual studio -
how to update many to many fields in django?
I'm struggling with this problem for 2 weeks please help me. how to update many to many fields? -
Conditional object class template tagging Django
I am attempting to replicate HTML cards based on a uniform model: Models.py class Uniform(models.Model): category = models.CharField(choices = CATEGORY_CHOICES, max_length=11) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(choices=CLOTHES_SIZE, max_length=4) image = models.ImageField(upload_to='uniforms/') class Meta: ordering = ['category'] def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) Views.py def item_list(request): uniform = Uniform.objects.all() description = Uniform.objects.order_by().values('description').distinct() category = Uniform.objects.order_by().values('category').distinct() context = { 'uniform':uniform, 'description': description, 'category': category } return render(request, 'apparelapp/item_list.html', context) html <div class="row wow fadeIn"> {% for item in description %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="" alt=""> <a> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center"> <label> <h5>{{ item.description }}</h5> </label> <h5> {% if uniform.description %} <strong> <label for="">{{ uniform.category }}</label> </strong> </h5> {% endif %} <!--<h4 class="font-weight-bold blue-text"> <strong>${{item.price}}</strong> <div class="dropdown"> {% for size in item.size %} <ul> {{size}} </ul> {% endfor %} </div> </h4> --> </div> </div> </div> {% endfor %} What I get is the item description, but not the item category: I am trying to say, if the uniform's description is shown, show the uniform's category - but it is blank I have tried formatting to call on just the … -
Multiple event with variable number of participants registration form in django
I am kinda new to Django. I want to create a Django application which has say three events: event1, event2, event3. Now each event has team participation, so event1 can have maximum of 15 participants, event2 has individual and event3 has no limit(but for simplicity lets keep max as 30). My initial idea was to create separate apps for each event and then handle it. In that case, will I have to create a different object for each of 15 people in event1? Is there any easier way? Also, if there is some better way of handling it please do tell. Thanks in advance! -
Django Session's Not Saved After Move From Local Pc to VPS
I have big problem ... since i want to move my local django project to vps and run it .... i remove sqlite and migrations (- inits remain) and Create Postgre Sql And Connect it to my django project and makemigrations and ... i can login in django admin or any other stuffs but sessions that i saved it with request.session['something'] = 'something' dosent save's but in local computer it's works :( .. i tried request.session.modified = True But It Dosent Work .. Please Help -
what do I need to learn about React for rest framework?
I'm seeking to learn react for using rest framework of Django. I already have some basic knowledge of Javascript and a little of ES6. I started watching some tutorials and knew some react concepts like functional component, class component, props, states. but I'm not sure if I'm on the right path learning what I really need to learn and I don't want spend much time and effort on something I won't make use of. so, I was wondering if I need to learn the whole react technology or just some specific concepts? and if it's only some concepts I need to learn about, then what are those concepts? -
Error writing to many to many field django rest framework api
This seems to be my solution https://stackoverflow.com/a/48636446/7989638 (for "How can I make a writable ManyToManyField with a Through Model in Django Rest Framework? ") but I am getting this error : {"images":["Incorrect type. Expected pk value, received unicode."]} their solution works in the create method of the serializer but i debugged and checked that it never reaches that method; returns error beforehand. Could you please help me fix this. Thanks -
Adding a value to a database field that is in your model but is not in your form
I have a model with a property called authID that looks like this: authID = models.CharField(max_length=400) In my view, all of the fields that are in my form get put into the database as follows: if request.method == 'POST': form = PersonalDetailsModelForm(request.POST) if form.is_valid(): form.save() What I want to know how to do is that when they submit the form, I want to also put the value of authID into my database. However, authID is not a field in my form. I don't want to make it a hidden field either for security reasons. How do you add a value to a database field that is in your model, but is not in your form? -
Need help in rendering a dataframe in html in django
I am new to python and django. need help to convert the below code to django model/view.py in order to render the output as a table with subtotal functionality. from kiteconnect import KiteConnect import iv_greeks import pandas as pd import csv import itertools from pprint import pprint apikey = open('apikey.txt','r').read() apisecret = open('apisec.txt','r').read() atr = open('access_token.txt','r').read() kite = KiteConnect(api_key=apikey) kite.set_access_token(atr) def lastprice(symbol): a = kite.ltp(symbol) for i,j in a.items(): b = j.pop('last_price') return b from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) while (current_time > "09:00:00") & (current_time < "15:30:00") : positions = kite.positions() N = 1 net = dict(itertools.islice(positions.items(), N)) for typ,pos in net.items(): with open('net_position.csv', 'w', encoding='utf8', newline='') as output_file: fc = csv.DictWriter(output_file, fieldnames=pos[0].keys(), ) fc.writeheader() fc.writerows(pos) positions = pd.read_csv('net_position.csv') positions['Underlying'] = positions.tradingsymbol.str.split('19').apply(lambda x: x[0]) positions['Strike'] = positions.tradingsymbol.str.split('DEC').apply(lambda x: x[1]) positions['StrikePrice'] = positions.Strike.str.split('CE').apply(lambda x: x[0]) positions['StrikePrice'] = positions.StrikePrice.str.split('PE').apply(lambda x: x[0]) positions['StrikePrice'] = positions.StrikePrice.astype(float) positions['CallPut'] = positions.Strike.str[-2:] positions.rename(columns = {'product' : 'Product','quantity' : 'Qty', 'average_price' : 'Avg', 'last_price' : 'LTP', 'unrealised' : 'Unrealised', 'realised' : 'Realised', 'pnl' : 'PnL'}, inplace = True) #import underlying instrument token fno = pd.read_csv('nse_stk.csv') positions.rename(columns = {'instrument_token' : 'instrument_token_tradingsymbol'}, inplace = True) fno.rename(columns = {'tradingsymbol' : 'Underlying'}, inplace … -
Django EditStamdata() got an unexpected keyword argument 'instance'
Hej, I got a error if I load a Form: from django import forms from .models import CountryList, Stamdata from django.db.models.functions import Lower from django.contrib.auth.models import User class EditStamdata(forms.ModelForm): Firmanavn = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), label='Firmanavn') EMail = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'autofocus': True}), label='EMail') Bank = forms.CharField(widget=forms.Textarea(attrs={'rows' :'4', 'class': 'form-control', 'autofocus': True}), label='Bank') Navn = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), label='Navn') Adresse = forms.CharField(widget=forms.Textarea(attrs={'rows' :'4', 'class': 'form-control'}),label='Adresse') Land = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),queryset=CountryList.objects.values_list('countryname', flat=True).order_by('code'), initial='Denmark', to_field_name='countryname') CVRCountrycode = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control col-md-4'}),label='CVR Landkode', queryset=CountryList.objects.values_list('code', flat=True).order_by('code'), initial='DK', to_field_name='code') CVR = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control'}),label='CVR Nummer') class Meta: model = Stamdata labels = { 'Byen': 'By', 'CVRCountrycode': 'Landekode', 'CVR': 'CVR Nummer', } fields = ['Firmanavn', 'UserID', 'Adresse', 'Land', 'CVRCountrycode', 'CVR', 'EMail', 'Bank', 'Navn'] And the view: def EditStamdata(request): StamdataData = get_object_or_404(Stamdata, pk=1) # if this is a POST request we need to process the form data if request.method == 'POST': form = EditStamdata(request.POST, instance=StamdataData) if form.is_valid(): form.save() return HttpResponseRedirect('backend/stamdata.html') else: print ('somethin goes wrong') form = EditStamdata(instance=StamdataData) return render( request, 'backend/stamdata.html', {'form': form }, ) And then I got this error message: EditStamdata() got an unexpected keyword argument 'instance' If I google it everbody fix it if they uses forms.ModelForm but I use it. -
Is there a way to get a query/stored procedure field and pass it to a form as an uneditable field, alongside other editable fields?
View: def post(self, request): form = AnswerForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() messages.success(request, 'Thank you for your request') return redirect('consumer_answer') args = {'form':form} return render(request, self.template_name, args) Form class AnswerForm(forms.ModelForm): question1 = forms.ModelChoiceField(queryset = Question.objects.all()) class Meta: model = Answer fields = ['answer', 'consumer'] Template {% for answers in answer_request %} <p>______________________________________________________________</p> <b><li> {{answers.5}}</li></b> <i><p> {{answers.6}}</p></i> Question ID: {{answers.8}}<br> <form method="post"> {% csrf_token %} {{form.as_p}} <select id="question1"> <option value= {{ answers.8 }}> Label </option> </select> <button type="submit">Submit Answer {{answers.8}}</button> </form> {% endfor %} </ol> {% endif %} At the moment, the above creates a blank form field called 'answer' (fine as completed by user and then posts to db, but the next two fields of 'consumer' and 'question' are drop downs of all instances in the model). Would like the 'consumer' and 'question' field to be uneditable with the result of the query so they are then posted to the db. The query works fine outside of the form as the loop above the form successful iterates and displays the output, I would just like to get it into the form. Thank you in advance for any help. -
Django and remote MariaDB
I use Django on a Postgres DB. Then I connect remote MySQL databases to it, no problem. But now I want to connect a remote MariaDB. I have a problem: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (110)") This problem seems to come from the remote DB. However I checked the rights of the database and the remote server. I can connect to this database remotely from HeidiSQL, or a local PhpMyAdmin. So I start to think that maybe it comes from Django, Python, connectors ... Please do you know this problem? -
Access to CreateView form modal on every page
I'm wondering is it possible to create modal that include CreateView form and have access to it on every page in django, on every view? So far I have a CreateView in my views.py: class ScenarioCreateView(CreateView): model = Scenario fields = ['title', 'area', 'author'] urls.py path('scenario/new/', ScenarioCreateView.as_view(), name='scenario-create'), and modal: <li><a class="modal-trigger" href="#modal1"><i class="material-icons">add</i></a></li> <!-- Modal Structure --> <div id="modal1" class="modal" method="post" action="/scenario/new/"> <div class="modal-content"> {% block new %} {% endblock %} </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> It's working now only from /scenario/new/, of course. I should probably change the path in urls.py, right? Could you help me? -
How do i fix this operational error in Django?
I created a comment view in my views.py, for the user to write and submit comments through a form. The comments will be displayed on the same template the info regarding a movie is shown. When I try to enter one of the films i get this error: OperationalError at /myapp2/2/ no such column: myapp2_comentario.pelicula_id views.py def detallesPelicula(request, pelicula_id): peliculas = get_list_or_404(Pelicula.objects.order_by('titulo')) pelicula = get_object_or_404(Pelicula, pk=pelicula_id) actor = get_list_or_404(Actor.objects) comentarios = Comentario.objects.filter(pelicula=pelicula).order_by('fecha') comment_form = CommentForm(request.POST or None) if request.method == 'POST': if comment_form.is_valid(): comentario = comment_form.save(commit=False) comentario.usuario = request.user comentario.save() return HttpResponseRedirect(pelicula.get_absolute_url()) context = {'pelicula': pelicula, 'peliculas': peliculas, 'comentarios':comentarios,'comment_form':comment_form} return render(request, 'detallesPelicula.html', context) my models.py class Comentario(models.Model): usuario = models.ForeignKey(User,on_delete=models.CASCADE) pelicula =models.ForeignKey(Pelicula, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True,null=True,blank=True) texto = models.TextField(max_length=2000, default="") def __str__(self): return self.usuario.nickname forms.py class CommentForm(forms.ModelForm): class Meta: model = Comentario fields = ['texto'] -
How to make a selection form in Django and use the selected value as session variable in a view?
When a user visits my web app he needs to select an account number within a dropdown menu. I then want to use his selection for further view functions within the session. 1.) How to create the required form? class selectMT4(forms.Form): CHOICES = (('Option 1', 'Option 1'),('Option 2', 'Option 2'),) field = forms.ChoiceField(choices=CHOICES) Here I am not sure how to offer the right options to select. The available account numbers are linked to his pk in the database table. He might have 10 entries with account number X and 2 entries with account number Y e.g.. So I somehow need to query each different available account number to use it as options in the form. This is how it looks like, thus the desired select options should be Option 1: 1925323 and Option 2: 1933381. Is it possible to implement such querySet within the form class itself? 2.) How to use the selected option in a view function? def getTrades(request, *args, **kwargs): trades = serializers.serialize('json', Trades.objects.filter(DID=request.user.DID)) return HttpResponse(trades) After the user made his selection, I want to use the selected value for view functions within that user session. In particular I would like to add the users selection as another … -
ImportError: cannot import name 'modelname' from 'apps.models' (D:\project\django\projects\django\apps\models.py)
thanks to your visit to my post, i one error here, please help me to find whats wrong in my code. i use django 2.2. i get one wrong : ImportError: cannot import name 'CategoryRoom' from 'rooms.models' (D:\project\django\voice web app\django\rooms\models.py) my full list in my comand line is like this : (env) D:\project\django\voice web app\django>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\project\django\voice web app\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\project\django\voice web app\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "D:\project\django\voice web app\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\project\django\voice web app\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\project\django\voice web app\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python 3.7.5\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\project\django\voice web app\django\rooms\models.py", line 4, in <module> from promotions.models import Bundle File "D:\project\django\voice web app\django\promotions\models.py", line 3, in <module> from rooms.models import … -
WeasyPrint HTML to PDF not rendered Images in TEST VM Environment - Django
I am using Django + WeasyPrint for HTML to PDF generation. In HTML template I am having around 2 SVG files. While running in Development (local) server, it rendered SVG Images when converting HTML to PDF. Whereas in TEST Server(Which runs by using NGINX and Docker Container), it fail to render SVG files. In WeasePrint, I have mentioned my TEST URL (http//test.sampleproject.com:8000) in the base_url. I don't know why it is working in my dev server and not working in TEST Server My Code. html_string = render_to_string('sample.html', {'data': data}) result = HTML(string=html_string, base_url='http//test.sampleproject.com:8000').write_pdf(presentational_hints=True) response = HttpResponse(result, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename={}'.format('sample.pdf') return response In my Template file I have loaded around 10 images. Ex: 'sample.html' template file: {% load staticfiles %} <img src="{% static 'svg/Logo1.svg' %}" alt="" /> <img src="{% static 'svg/Logo2.svg' %}" alt="" /> Please help me to render the SVG files in the output PDF. -
ValueError('Related model %r cannot be resolved' % self.remote_field.model) inside a single app
Here is models.py from django.db import models class Owner(models.Model): first_name = models.CharField('Ім`я', max_length=30) last_name = models.CharField('Фамілія', max_length=30) surname = models.CharField('По-батькові', max_length=30) class Address(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник') house = models.IntegerField('Будинок', default=0) street = models.CharField('Вулиця', max_length=30) city = models.CharField('Місто', max_length=30) region = models.CharField('Область', max_length=30) cantry = models.CharField('Країна', max_length=30) class Car(models.Model): number = models.IntegerField('Номер', primary_key=True) date = models.CharField('Місто', max_length=30) brand = models.CharField('Марка', max_length=30) colors = models.CharField('Кольори', max_length=30) state = models.CharField('Стан', max_length=30) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник') address = models.ForeignKey(Address, on_delete=models.CASCADE, verbose_name='Адреса') class Engine(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, verbose_name='Машина') cylinders = models.CharField('Циліндри', max_length=30) fuel_injection = models.CharField('Вприскування пального', max_length=30) supercharger = models.CharField('Суперчарджер', max_length=30) catalytic = models.CharField('Каталізатор', max_length=30) automatic = models.CharField('Автоматичний', max_length=4) class Performance(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) acceleration = models.FloatField('0-100 kmph (сек)', default=0) max_speed = models.IntegerField('Максимальна швидкість', default=0) fuel_eff = models.FloatField('Витрата пального', default=0) pollution_class = models.CharField('Клас забруднення', max_length=8) base_price = models.IntegerField('Базова ціна', default=0) class Type(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) body_type = models.CharField('Тип кузова', max_length=16) no_of_door = models.IntegerField('Кількість дверей', default=0) no_of_seats = models.IntegerField('Кількість сидіннь', default=0) engine_place = models.CharField('Місце мотору', max_length=2) drivetrain = models.CharField('Привід', max_length=16) class Body(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) … -
How to pass initial choices from view to form
I'm trying to pass choices from django based view to form choice field what I did: forms.py class FormName(forms.Form): freq = forms.ChoiceField(choices=FREQ) start_date = forms.DateField(widget=forms.TextInput( attrs={'type': 'date'} ), label='Start Date') projects = forms.ChoiceField(required=False, label='Project') views.py def view_name(request, *args, **kwargs): all_projects = list( Model.objects.filter(user_id=user_id).values("project_id", "project_name").distinct()) projects = tuple((q['project_id'], q['project_name']) for q in all_projects) form = FormName(initial={'freq': grouping_by, 'start_date': start_date, 'projects': projects}) in view code I retrieve the choices as tuple of tuples and I want to pass it in the initial part how can I do that? many thanks -
AttributeError: 'ManyToManyField' object has no attribute 'First_Name'
i encountered the following problem when i try to migrate list of models one of which contains a ManyToMany field. class Item(models.Model): File "C:\Users\helin\Downloads\Django\E-commerce\Farmers\Farmersapp\models.py", line 60, in Item sluger = farmer.First_Name AttributeError: 'ManyToManyField' object has no attribute 'First_Name' Below are the models i created.any help is appreciated.Thank you class Farmer(models.Model): id = models.AutoField(default=1,primary_key=True) First_Name = models.CharField(max_length=15) Last_Name = models.CharField(max_length=15) def __str__(self): return self.First_Name+" "+self.Last_Name def get_farmer(self): return self.farmer.First_Name+" " +self.farmer.Last_Name class Item(models.Model): id = models.AutoField(default=1,primary_key=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=6) price = models.FloatField() description = models.TextField(blank=True) image = models.ImageField() farmer = models.ManyToManyField(Farmer, through='ItemAmount',related_name='item') sluger = farmer.First_Name slug = models.SlugField(default=sluger) def __str__(self): return self.category class ItemAmount(models.Model): farmer = models.ForeignKey(Farmer, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) -
Can not set value of ace editor with template tags filters
I have an ace editor in my html page,for which I can write editor.setValue( '//Your code here'); It perfectly works and I get an editor with "//Your code here" written inside it. But when I pass a template tag from django backend,with this line. def func(request): context={"message":"hello there,write your code"} return render(request,'index.html',context) and try to set value using template tagging filter with this line editor.setValue({{message}}); It is not working,If I write it in simple html,It works,but not inside setValue() function.