Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue using the django usercreationform, not rendering form in HTML
im making a signup page in a django project using the UserCreationForm but when rendering my html i only see the submit button from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def register(request): form = UserCreationForm return(render(request, 'register.html', {form: form})) {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="button"> <button type="submit">Sign up</button> </form> {% endblock %} -
Naming convention for Django migrations
Is there a best practice naming convention for Django migrations? If it's a small migration the names are pretty obvious, but things get harry when multiple fields are being changed. Just wondering if anyone has a standard they like to use. -
Django - error from call to values_list: 'flat' is not defined
Here's a loop I'm using to process an Excel sheet with openpyxl. On occasion the partno field is missing and I try to derive it from another database table (booking) using a field called transmittal. I'm having trouble with this lookup and it returns an error. When I run the same thing under the Django shell, it works fine. parser = parse_defrev(book) brs = [] xmtl_part = {} invalid = [] for r in parser.process(): # If no partno, try to look it up in the bookings table if r.get('partno') is None: xmtl = r.get('transmittal') if xmtl: r['partno'] = xmtl_part.get(xmtl) if not r['partno']: parts = set(Booking.objects.filter(bookingtransmittal=r['transmittal']).values_list('bookingpartno', flat=True)) if len(parts) == 1: r['partno'] = parts.pop() xmtl_part[xmtl] = r['partno'] process is a generator function in the parse_defrev class which returns a dictionary with the processed fields from the workbook. If partno is missing, then it first tries to retrieve it from a caching dictionary and then from the booking table. The values_list returns any matching partno values, and if there is more than 1 match it just logs the problem and skips to the next row. I get the following error, and don't understand how it could fail to recognize the flat … -
How to run migration against a different database in Django?
I'm using two database instances in Django, one is in Postgis and the other is in Postgres itself. Postgis is a geospatial database that has some model fields and features that the PostgreSQL database which is its extender does not have. When I run the ./manage.py migrate, to avoid tracebacks, I want the migrations related to Postgis migrate to Postgis and the ones related to Postgres migrated to Postgres which is the default database. I could do this by specifying --database="postgis" while running the migration command but it would be best option to avoid doing that. -
ERR_CONNECTION_TIMED_OUT when trying to access AWS EC2 hosted Django application
I'm stuck with ERR_CONNECTION_TIMED_OUT in browser when trying to access Django application which is deployed to AWS EC2. A week ago I was able to connect but now when I relaunched instance, changed ALLOWED_HOSTS in .env file the browser just throw me this error. The output in the console says everything is ok. To fix this I've tried to create another instance and deploy the app there and also added Elastic IP address but still got the same error. How can I fix this issue? I'm using Django with Docker, Nginx proxy and UWSGI. Nginx proxy configuration (default.conf.tpl): server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Nginx proxy Dockerfile (Dockerfile): FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] run.sh script: #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' .env: ... ALLOWED_HOSTS=18.119.35.216 ... (18.119.35.216 is the Elastic IP address) uwsgi_params: uwsgi_param QUERY_STRING $query_string; uwsgi_param … -
How to append/load Chatbot model in Django Website?
I have a django site on which machine learning chatbot model is needed to be appended. What I am unable to understand when I trained and saved my model using tensorflow, it created three files Now I am trying to load my model on django site in views. As I am beginner on this so I don't really know how should I do this. So I decided to load my model on site first but I really I don't know which file should I load bexause my model is saved as model.save('model.tflearn'). Should I load file using pickle or joblib. Any suggestion and solution will be appreciated! -
Django RestAPI, expose a function instead a model
In my django project i have a function like thisone: def calc_q(start_d, end_d, var_id): d = {"[": "", "]": "", ",": ""} var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), var_id_id=var_id, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", "var_val_conv" ) df = pd.DataFrame(list(var_results)) df['id_res__read_date'] = pd.to_datetime(df['id_res__read_date']) df = df.set_index('id_res__read_date') df_15 = df.resample('15min')['var_val_conv'].agg(['first','last']) return pickle.dumps(df_15) well, function used instead of my project works well but i need to expose this function as an API for leave external user to call it specifying parameters (dates and var_id) and get pandas dataframe serialization results. How can i expose this function using Django Rest APi, i read something about serializers.SerializerMethodField but i don't understand how exactly it works and if it could be useful for my intention. So many thanks in advance Manuel -
Django's django-crispy-forms not showing asterisk for required field on form
As the title states I have a required field displayed on a form, and it doesn't show the asterisk to indicate that it is required. NOTE: The field is not required on the models side, but I set it on the forms.py side. models.py: class ErrorEvent(models.Model): """Error Event Submissions""" event_id = models.BigAutoField(primary_key=True) team = models.CharField(verbose_name="Team", blank=True, max_length=100, choices=teams_choices) event_name = models.CharField(verbose_name="Event Name", max_length=100) forms.py: from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = ErrorEvent # fields = exclude = ['event_id'] widgets = { 'team': forms.Select(attrs={'required': True}),} When I check the website 'Team' is shown to be not required (but you can't finish the form without filling it) However 'Event Name' is shown to be required. Anyway I can fix this? Thank you for all help in advance! -
DJANGO MultiValueDictKeyError problem with UPDATE
I had a working update table. I am updating in the same form. But after entering the photo upload codes, the problem of updating other variables appeared. I am seeing the error page I mentioned below. I am updating these lines of code. I am updating the POSTed data in the database. Lastly, I added code related to uploading photos. There is no problem in uploading and changing photos. It works pretty well. However, this time the updating other variables part is broken. It was working normally. views.py def bilgilerim_guncel(request, id): if(request.method=='POST'): name_surname= request.POST['name_surname'] mobile_number= request.POST['mobile_number'] age= request.POST['age'] length= request.POST['length'] weight= request.POST['weight'] foot= request.POST['foot'] position= request.POST['position'] photo = request.FILES['photo'] if (os.path.isfile('static/players/' + str(id) + '.jpg')): os.remove('static/players/' + str(id) + '.jpg') storage=FileSystemStorage() filename=storage.save('static/players/'+str(id)+'.jpg',photo) storage.url(filename) players.objects.filter(user_id=id,).update(photo=str(id)+'.jpg',name_surname=name_surname,mobile_number=mobile_number,age=age,foot=foot,length=length,position=position,weight=weight,) return redirect(reverse('bilgilerim_x' ,args=(id,))) urls.py from django.contrib import admin from django.urls import path from uygulama import views urlpatterns = [ path('admin/', admin.site.urls, name='yonetim'), path('', views.anasayfa, name='home'), path('ligler/<int:id>', views.leagueLists, name='leagues'), path('haberler/',views.haberler, name='habers'), path('kayit/',views.kayit, name='kayit_x'), path('giris/',views.giris, name='giris_x'), path('cikis/',views.cikis, name='cikis_x'), path('bilgilerim/<int:id>',views.bilgilerim, name='bilgilerim_x'), path('bilgilerim-guncelle/<int:id>',views.bilgilerim_guncel, name='bilgilerim_guncel_x'), path('bildirimler/<int:id>',views.bildirimler, name='bildirimler_x'), ] players_models.py from django.db import models from django.contrib.auth.models import User from uygulama.models import teams class players(models.Model): name_surname=models.CharField(max_length=18,null=False,blank=False) mobile_number=models.IntegerField(null=False,blank=False) player_status=models.IntegerField(null=True,blank=True,default=0) team=models.ForeignKey(teams,on_delete=models.DO_NOTHING,null=True,blank=True,default=4) photo=models.ImageField(null=True,blank=True,default='resim-yok.jpg') awards=models.IntegerField(null=True,blank=True) dogecoin=models.IntegerField(null=True,blank=True) age=models.IntegerField(null=False,blank=False) foot=models.CharField(max_length=10,null=False,blank=False) length=models.CharField(max_length=4,null=False,blank=False) weight=models.IntegerField(null=False,blank=False) red_card=models.IntegerField(null=True,blank=True,default=0) position=models.CharField(max_length=2,null=False,blank=False) form_points=models.CharField(max_length=3,null=True,blank=True) user=models.ForeignKey(User,on_delete=models.CASCADE) ERROR PAGE -
Need to be able to execute a function for multiple items but it can't work, why?
I have a library app that issues books to students. My issue function is as follows. It works well. def issue_student(request,pk): if request.method == 'POST': form = OldIssueForm(request.POST,school= request.user.school,pk=pk,issuer = request.user) if form.is_valid(): try: book = form.cleaned_data['book_id'].id form.save(commit=True) books = Books.objects.filter(school = request.user.school).get(id=book) Books.Claimbook(books) return redirect('view_issue') except Exception as e: messages.info(request,f"{e}") else: form = OldIssueForm(school= request.user.school,pk=pk,issuer = request.user) return render(request, 'issue_student.html', {'form': form}) My Issue is I can't get the code to be able to issue a student with more than one book. My form is ashown below... class OldIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(OldIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['book_id'].queryset = Books.objects.filter(school=school,no_of_books=1) self.fields['borrower_id'].initial = pk class Meta: model = Issue fields = ['issuer','book_id','borrower_id'] widgets = { 'borrower_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'book_id':Select2Widget(attrs={'data-placeholder': 'Select Book',"style":"width:100%",'class':'form-control'}), } The Issue model is below class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) -
Simple tag loosing the value set after leaving a FOR tag in template
I have this simple tag defined and loaded into my template: from django import template @register.simple_tag def defining(val=None): return val The tag works! My goal is, i want to set a value for a variable using this simple tag inside the FOR looping using some condition, and then, check the value of this variable after leaving the FOR. Simple right? {% defining 'negative' as var %} {% for anything in some_query_set %} {% if 1 == 1 %} {% defining 'positive' as var %} {% endif %} {% endfor %} <p>The value of var is: {{var}}</p> The problem is: I want this variable 'var' to be 'positive' after leaving the for, but it always turn into 'negative'. I've checked its values inside the IF and inside the FOR and it gets 'positive' as expected, but after leaving the FOR, it gets back to 'negative'. I may have some workaround using context variables through views, but i really need to do this in the template. I also searched the forum, but i couldn't find anything close enough to explain me why this is happening. Am i missing something? I'm kinda new to Django, so i'm trying to avoid more complex aproaches, … -
Passing a variable to an included html modal with Django
I wanted to quickly build a small web app, so I decided to go purely with django and what django offers - template rendering, so no React/Vue or such. The problem that I am having is, that I have some cards, which are being displayed in a for loop (jinja) once the user clicks on a card, a modal shows up and this is where it gets messy. I want to pass the id of the card, so that I can make a get request and render the data in the modal. The code that I have is: // index.html <div id="machine-cards" class="grid grid-cols-3 gap-4 m-20"> {% for machine in machines %} <div id="card" class="bg-white shadow-md rounded px-8 pt-6 pb-2 mb-4 transform hover:scale-105 cursor-pointer"> <div id="card-header" class="flex justify-between"> <p>Machine number: {{ machine.number }}</p> <div id="state" class="rounded-full h-4 w-4 {% if machine.status == 1 %} bg-green-500 {% elif machine.status == 2 %} bg-red-500 {% elif machine.status == 3 %} bg-yellow-500 {% else %} bg-gray-500 {% endif %}"> </div> </div> <div id="card-body" class="flex justify-center align-center mt-5 mb-5"> <p>{{ machine.manufacturer }}</p> </div> <div id="card-footer" class="flex justify-end"> <p class="text-gray-300 text-sm">Last updated: 28.06.2021</p> </div> </div> {% endfor %} </div> {% include "general/modal.html" %} <script> function … -
How can I have check constraint in django which check two fields of related models?
from django.db import models from djago.db.models import F, Q class(models.Model): order_date = models.DateField() class OrderLine(models.Model): order = models.ForeignKeyField(Order) loading_date = models.DateField() class Meta: constraints = [ models.CheckConstraint(check=Q(loading_date__gte=F("order__order_date")), name="disallow_backdated_loading") I want to make sure always orderline loading_date is higher than orderdate -
Having trouble running the django extensions command reset_db programatically
Basically I am writing a script to reset a django webapp completely. In this script, I want to reset the database, and there is a command to do it from django extensions. Unfortunately, I haven't been able to run it programatically. It works fine when I run it via command line, but it just won't execute when I try programatically. I have tried using os.system and subprocess. I have also tried using management.call_command('reset_db'), but it keeps saying that there isn't a command called reset_db. I have checked to make sure the django_extensions is in my installed apps, so I have no idea why that isn't working. Does anyone know how I could fix this? Thank you! Also I am using python3, the most recent version of django I believe, and it is a MYSQL server that I am trying to delete. -
How do i show a list of object in Django DetailView
I'm still learning Django, using Class based view, i have created a ProductDetailView and have a ProductListView. Everything working perfect, but i want to add on my product_detail page, a list of products, after client viewed a product_detail page may also be interested by related product or what they may want. enter image description here **my model.py** class Product(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(null=False, unique=True) featured = models.ImageField(upload_to='product_images') price = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) available_colours = models.ManyToManyField(ColourVariation, blank=True) available_sizes = models.ManyToManyField(SizeVariation) primary_category = models.ForeignKey( Category, related_name='primary_products', blank=True, null=True, on_delete=models.CASCADE) secondary_categories = models.ManyToManyField(Category, blank=True) stock = models.IntegerField(default=0) def __str__(self): return self.title ProductListView: class ProductListView(generic.ListView): template_name = 'cart/product_list.html' def get_queryset(self): qs = Product.objects.all() category = self.request.GET.get('category', None) if category: qs = qs.filter(Q(primary_category__name=category) | Q(secondary_categories__name=category)).distinct() return qs def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) context.update({ "categories": Category.objects.values("name") }) return context **ProductDetailView:** class ProductDetailView(generic.FormView): template_name = 'cart/product_detail.html' form_class = AddToCartForm def get_object(self): return get_object_or_404(Product, slug=self.kwargs["slug"]) def get_success_url(self): return reverse("cart:summary") def get_form_kwargs(self): kwargs = super(ProductDetailView, self).get_form_kwargs() kwargs["product_id"] = self.get_object().id return kwargs def form_valid(self, form): order = get_or_set_order_session(self.request) product = self.get_object() item_filter = order.items.filter( product=product, colour=form.cleaned_data['colour'], size=form.cleaned_data['size'], ) if item_filter.exists(): item = item_filter.first() item.quantity += int(form.cleaned_data['quantity']) item.save() else: new_item … -
Django Form is not Loading in HTML Template
My Form is not loading in html template, Ive checked everything but i don't found anything wrong. Please do help if possible. adddept.html <form method="post">{% csrf_token %} {{form|crispy}} <div class="d-flex justify-content-center"> <input class="btn btn-success" type="submit" value="Submit"> </div> </form> Views.py def adddept(req): if req.user.is_authenticated: form = deptform(req.POST or None) if form.is_valid(): form.save() form = deptform() context = { 'form' : form, 'usr' : req.user } return render(req, 'adddept.html', context) else: return redirect('../login/') Forms.py class deptform(forms.Form): class meta: model = department fields = '__all__' Models.py class department(models.Model): dept_id = models.AutoField(primary_key=True) dept_name = models.CharField(max_length=100) adid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) def __str__(self): return self.dept_name -
Image is not showing in the post. In Django, post.image is not showing the image in blogHome.html and blogPost.html page
I have two apps in my django project home and blog. All the post related coding is in the blog app. I am fetching the data from Post model. here is the coding of blogHome.html template {% extends base.html %} <h1>Posts Results By Ayyal Ayuro Care</h1> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3 my-4"> {% for post in allPosts %} <div class="col"> <div class="card shadow-sm"> <img src="{{post.image}}" class="d-block w-100" alt="..."> <div class="card-body"> <h3>Post by {{post.author}}</h3> <h4>{{post.title}}</h4> <p class="card-text"> <div class="preview">{{post.content|safe| truncatechars:150 }}</div> </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a href="{{post.slug}}" role="button" class="btn btn-primary">View More</a> </div> <small class="text-muted">{{post.timestamp}}</small> </div> </div> </div> </div> {% endfor %} </div> here is the coding of the blogPost.html. when someone click on the view more button in blogHome.html page it shws up blogPost.html page. But Images are not showing in this page also. {% extends base.html %} <div class="container my-4"> <img src="{{post.image}}" class="d-block w-100" alt="..."> <h2 class="blog-post-title">{{post.title}}</h2> <p class="blog-post-meta">{{post.timestamp}} by <a href="#">{{post.author}}</a></p> <p>{{post.content|safe}}</p> <hr> </div> here is my views.py file of blog app from django.contrib.auth import models from django.http import response from django.shortcuts import redirect, render, HttpResponse from datetime import datetime from home.models import Comment from blog.models import Post from django.contrib import messages from django.contrib.auth.models import … -
Overwrite validate_unique with M2M relations
I am trying to implement my own validation for a many-to-many relation (m2m) since django does not allow m2m fields in the unique-together constraint (https://code.djangoproject.com/ticket/702) (Django Unique Together (with foreign keys)) What I want is to check is if a newly created object instance is already existent within the scope of a m2m related model. Imagine I have the following 3 models: class Juice(model.Model) name=CharField, year=IntegerField, flavor=CharField class Company(model.Model) name=CharField, cooperates=ManytoManyField juice=ManytoManyFiedl class Cooperate(model.Model) name=CharField That means that a company can have many juices and many juices can belong to many companies. Equally a company can belong to many cooperates and a cooperate can belong to many companies. What I want to implement now is the following restriction: Whenever I create a new juice with name, year and flavor it should validate if a juice like this already exists within the scope of the Cooperate model. That means if there is any company within the cooperates that already have this juice it should raise a ValidationError. Let's say for example I create a new juice (bb-sparkle, 2020, blueberry) it should raise a validation if cooperate-optimusprime already has a company (e.g. company-truck-juices) that has a juice with bb-sparkle, 2020, blueberry. But … -
How can I pass a function into the validators kwarg in Django model field? Is there a way to do so?
Here is a function in my models.py: def maxfra(): if Treatment.treatment=='XYZ' and PatientType.patient_type=='ABC': return 40 if Treatment.treatment=='DEF' and PatientType.patient_type=='MNO': return 40 if Treatment.treatment=='RSO' and PatientType.patient_type=='BPO': return 40 And here is the model-field that I want to put the validation into: maxfra=models.CharField(max_length=2, validators=[maxfra]) I get: TypeError: __init__() got an unexpected keyword argument 'maxfra' What's wrong? -
how to get queryset with .filter(ifsc_startswith) , where ifsc is input value, in django?
class BankViewSet(PaginateByMaxMixin,viewsets.ReadOnlyModelViewSet): """ API endpoint that allows users to be viewed. """ queryset = Branches.objects.filter(ifsc__startswith='') serializer_class = BranchSerializer pagination_class = MyLimitOffsetPagination filter_backends = [SearchFilter, OrderingFilter,DjangoFilterBackend] search_fields = ['ifsc','branch','city','district','address','state'] filterset_fields =['ifsc'] ordering_fields = ['ifsc'] max_paginate_by = 100 I have this view of my api. I thought filter(ifsc_startswith) parameter will give back querries starting from input values but to my surpise it doesnt. instead it shows results like filter(ifsc_contains). how to solve this problem? -
How to implement Django multiple user types, while one user can have different role according to the project he/she is working on?
I couldn't find a solution to my problem and would appreciate comments/help on this. I would like to develop a multiple user type model in Django, along the lines of this video where the author is using Django Proxy Models. Situation I have a list of XX projects (proj01, proj02 , projXX, ...). All these projects have their specific page that can be accessed through a specific url mysite/projXX/ I have multiple users: Adam, Bob, Caroline, Dany, Ed, ... Each user can have several roles according to the project they are working on (e.g. manager, developer, documentarist, reviewer, editor, ...) A user can have a different role according to the project. E.g. Adam can be reviewer on proj01 but editor on proj02 while Bob can be editor on proj01 but reviewer on proj02, etc.. I started defining multiple user types in the models.py file below (only reviewer and editor roles): # accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ class User(AbstractUser): class Types(models.TextChoices): EDITOR= "EDITOR", "Editor" REVIEWER = "REVIEWER", "Reviewer" base_type = Types.EDITOR type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=base_type ) name = models.CharField(_("Name of User"), blank=True, max_length=255) def … -
how to login with twitter in django-allauth
TypeError at /accounts/twitter/login/ startswith first arg must be bytes or a tuple of bytes, not str Request Method: GET Request URL: http://127.0.0.1:8000/accounts/twitter/login/?process=login Django Version: 3.2.4 Exception Type: TypeError Exception Value: startswith first arg must be bytes or a tuple of bytes, not str Exception Location: C:\DjangoApps\myvenv12\lib\site-packages\requests\sessions.py, line 738, in get_adapter Python Executable: C:\DjangoApps\myvenv12\Scripts\python.exe -
CircleCI Exit Code 137 after upgrading Docker-Compose Container of MySQL from 5.7 to 8.0.2
Good day, everyone. Hope you're doing well. I've been stuck with this for quite a while now. I'm not really sure what can I do to Debug, because I'm a newbie in CircleCI. What I've done is that I've narrowed down an Exit Code 137 from CircleCI to a change in the version of MySQL container in Docker Compose. That error is usually related to OOM, but I've already bumped up the memory of CircleCI to 8GB with resource_class: large and the error keeps happening. Let me be clear this is NOT happening locally. All my containers run and work fine. Here are my Docker-compose and CircleCI config files. First, docker-compose.test.yml version: "3.8" services: app: build: context: . target: dev command: bash -c 'python3 manage.py collectstatic --noinput && python3 manage.py runserver 0.0.0.0:7777' depends_on: - mysql env_file: # stuff that don't matter... mysql: image: "mysql:8.0.2" # image: "mysql:5.7" # Upgrade from 5.7 to 8.0.2 restart: always volumes: - proj-mysql:/var/lib/mysql-8.0.2 # - proj-mysql:/var/lib/mysql # Upgrade from 5.7 to 8.0.2 expose: - "3306" networks: - # More stuff that doesn't matter volumes: proj-mysql-8.0.2: # proj-mysql <- Old 5.7 And config.yml: version: 2.1 orbs: python: circleci/python@0.2.1 eb: circleci/aws-elastic-beanstalk@1.0.0 commands: setup-build-environment: steps: - checkout - … -
Exclude a field from validation upon submission in django view
This is my model class Food: category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="foods" ) name = models.CharField(max_length=255) This is my form class FoodForm(forms.ModelForm): location = forms.ModelChoiceField( choices=CHOICES required=True ) class Meta: model = Food fields = ( "name", "location", "category" ) Upon update, I don't need to save the location. I just need it in the filtering of the category since it depends on it, but I don't have to save it. upon submission for the update, it throws the error 'Food' object has no attribute 'location'. Is there any way I can exclude this field upon submission? This is my view class FoodUpdateView(BaseUpdateView): form_class = forms.FoodForm def get_queryset(self): return Food.objects.all() def form_valid(self, form): return super().form_valid(form) def form_invalid(self, form): return redirect(self.get_success_url()) -
why my form labels donesnt work with UpdateView?
django labels doesnt work with UpdateView, but labels from another model and Views works perfectly. forms.py class Meta: model = Vacancy fields = "__all__" labels = { 'title': 'Название', 'skills': 'Требования', 'description': 'Описание', 'salary_min': 'Зарплата от', 'salary_max': 'Зарплата до', } views.py class VacancyEdit(UpdateView): model = Vacancy template_name = 'vacancies/vacancy-edit.html' fields = ['title', 'skills', 'description', 'salary_min', 'salary_max'] pk_url_kwarg = 'vacancy_id' success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Applications'] = Application.objects.filter(vacancy_id=self.kwargs['vacancy_id']) return context