Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django-smart-selects doesn't refresh the chained foreign keys after foreign key changes?
I'm using django-smart-selects to be able to handle some fields that depends on each other. Here is the details: In my models I have Faculty and Program. A faculty can have multiple programs and a program can belong to only one faculty. A Student has a faculty and program. from smart_selects.db_fields import ChainedForeignKey class Student(models.Model): ... faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE) program = ChainedForeignKey( Program, chained_field="faculty", chained_model_field="faculty" ) And say I have the following entries in my database: ├── Faculty 1 │ ├── Program a │ └── Program b └── Faculty 2 ├── Program x └── Program y Here is my problem: When I try to select faculty and program for a student for the first time, everything works as expected. But if I save it then come to the same page, when I change faculty from 1 to 2 dropdown for the programs are not updated (if Faculty 1 is selected initially I always see Program a and Program b in the dropdown even if I change the faculty). Is this intended behaviour? If not what should I do to make it work as I want? -
how can stop django automatically creating extra type in script link?
I am new to Django. Recently I have launched a project with django. I used bootstrap for frontend. While I am checking w3c validation it shows extra type tags in my js script link. Like following <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha3…Ff/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous" type="4fccca11a650fdab7a297279-text/javascript"> This extra type="4fccca11a650fdab7a297279-text/javascript is not created by me. How can i stop this. -
How to use a django variable to embed twitch stream
I'm trying to embed a twitch steam into my website, but I want the stream name to be inherited from a Django Model Variable. This is the HTML that I'm trying to get to work. {% extends 'base.html' %} {% block Title %} View Booth {% endblock %} {% load static %} {% block header %} <link rel="stylesheet" href="{% static 'css/booth_profile.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Redressed&display=swap" rel="stylesheet"> <script src="https://player.twitch.tv/js/embed/v1.js"></script> {% endblock header %} {% block body %} <h1 class="fullname">{{ booth.name }}</h1> <img src="{{ booth.cover_image.url }}" class="cover centered" alt="cover pic"> <div class="mb-4"> {% ifequal booth user.booth.first %} <a href="{% url 'new_artwork' booth.pk %}" class="btn btn-primary">New Artwork</a> {% endifequal %} Live Stream: <p id="demo">{{ booth.twitch_name }}</p> <div id="twitch-embed"></div> <script src="https://embed.twitch.tv/embed/v1.js"></script> <div id="twitch-embed"> {# <iframe#} {# id="chat_embed"#} {# src="https://www.twitch.tv/embed/lec/chat?parent=www.google.com"#} {# height="500"#} {# width="350">#} {#</iframe>#} </div> </div> <div class="details"> <b>Name:</b> {{booth.name}}<br> <b>Description:</b> {{ booth.description }} </div> {% for artwork in booth.artworks.all %} <br> Name: {{ artwork.name }}<br> Description: {{ artwork.description }}<br> <img src="{{ artwork.image.url }}" class="cover centered" alt="cover pic"> <br> Price: {{ artwork.price }}<br> {% endfor %} <script type="text/javascript"> var twitch_name = {{ booth.twitch_name }}; new Twitch.Player("twitch-embed", { width: 854, height: 480, channel: twitch_name }); </script> {% endblock %} The Booth Model: class … -
How to put favicon.ico in root directory in Django (not in STATIC_DIR)?
i can put my favicon in STATIC dir (STATIC_URL = '/static/') - it work. It work in html: <link rel="icon" type="image/x-icon" href="/static/marketability/favicon.ico"> <link rel="shortcut icon" type="image/x-icon" href="/static/marketability/favicon.ico"> It work in urls.py as Redirect: urlpatterns = [... ... path('favicon.ico', RedirectView.as_view(url='/static/marketability/favicon.ico', permanent=True)) ] but if i put favicon.ico in root - /patterns/ it does`t work: <link rel="icon" type="image/x-icon" href="/favicon.ico"> - not work and path('favicon.ico', RedirectView.as_view(url='/favicon.ico', permanent=True)) not work ??? I not want use urls.py as RedirectView becouse it return 301 code. The external service (search system) need 200 Ok code of site`s favicon. directory structure: myproject/myproject/marketability/patterns/favicon.ico (root with index.html) myproject/myproject/marketability/static/marketability/favicon.ico -
How to prevent current user from rating himself using Django model constraints
So I have a user model and each user should be able to rate other users but shouldn't be able to rate themselves. Model for rating is #Rating field in User model ratings = models.ManyToManyField('self', through='Rating', symmetrical=False, related_name='rated_by') #Rating model class Rating(models.Model): rating = models.IntegerField(validators=[validate_rating]) from_user = models.ForeignKey(User, related_name="from_people", on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name="to_people", on_delete=models.CASCADE) Is there a way I can make this functionality? I was thinking django model constraints will work but I do not know how to go about it. How do I filter a request to grab the specific user to prevent them from rating themselves? -
Django favicon.ico in the root directory of the site
i can put my favicon in STATIC dir (STATIC_URL = '/static/') - it work. It work in html: <link rel="icon" type="image/x-icon" href="/static/marketability/favicon.ico"> <link rel="shortcut icon" type="image/x-icon" href="/static/marketability/favicon.ico"> It work in urls.py as Redirect: urlpatterns = [... ... path('favicon.ico', RedirectView.as_view(url='/static/marketability/favicon.ico', permanent=True)) ] but if i put favicon.ico in root - /patterns/ it does`t work: - not work and urlpatterns = [... ... path('favicon.ico', RedirectView.as_view(url='/favicon.ico', permanent=True)) ] - not work ??? I not want use urls.py as RedirectView becouse it return 301 code. The external service (search system) need 200 Ok code of site`s favicon. directory structure: -myproject -myproject -marketability -patterns "..." "..." "favicon.ico" "index.html" -static -marketability "..." "..." "favicon.ico" -
Is it possible to pass the data that is retrieved from a Django form field onto a new form - or the same form?
I want to retrieve results from a Django form field and reuse the values in another field. This field could reside in the same form or in a new form. I have tried to achieve this by passing already obtained values to the form __init__() function. So I create a class FormDummy as: dummy.py from django import forms from django.forms.utils import ErrorList FRUITS = [('apple', 'Apple'), ('orange', 'Orange')] class FormDummy(forms.Form): fruit = forms.ChoiceField(widget=forms.RadioSelect, choices=FRUITS) fruits_chosen = None def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None): self.fruits_prev = [] if data is None else data.get('fruits_prev') self.fruits_prev = [] if self.fruits_prev is None else self.fruits_prev self.fruits_chosen_list = [] for f in self.fruits_prev: self.fruits_chosen_list.append((f, f.capitalize())) FormDummy.fruits_chosen = forms.ChoiceField(widget=forms.RadioSelect, choices=self.fruits_chosen_list) super().__init__(data=data, files=files, auto_id=auto_id, prefix=prefix, initial=initial, error_class=error_class, label_suffix=label_suffix, empty_permitted=empty_permitted, field_order=field_order, use_required_attribute=use_required_attribute, renderer=renderer) I have two different html-templates (which both extend a simple base.html-file): dummy.html {% extends 'base.html' %} {% block content %} <form action="/adb/add/dummy/" method="post"> {% csrf_token %} <div> {{ form.fruit }} </div> <div> <button type="submit">Submit</button> </div> </form> {% endblock %} dummy_2.html {% extends 'base.html' %} {% block content %} <form action="/adb/add/dummy/" method="post"> {% csrf_token %} <div> {{ form.fruit }} </div> <div> {{ form.fruits_chosen }} </div> <div> <button type="submit">Submit</button> </div> … -
Running Heroku for local and deployment with settings modules
I've set up a Django project using settings modules, a base.py, development.py, and deployment.py but I'm a little confused on how to run the project locally and remotely. So, I can run python manage.py runserver --settings=<project>.settings.development and everything goes alright but my doubt is: How can I run it through heroku local giving the settings option? It will also help to run it on remotely with deployment settings. -
How do I assign a nested JSON-Object to a simple class, where the nested objects get their own field in Django
I have the following JSON Object: { "header": {"bookid": 43, "title" : "MyTitle", "author" : "John Doe"}, "content" : "Book Content" } and I want to create a book object (see models.py) out of this json object. I am also using the serializer of the DRF that has to validate the json object first and then it has to create the book object, which is then saved into a database. However only the content field, gets its data. The header data has somehow to be preprocessed (because of its child object). How would one usually do that? In the serializer? or before it gets passed to the serializer? models.py class Books: bookid = models.PositiveIntegerField(default=0) title = models.Charfield(max_length=50, default='') author = models.Charfield(max_length=50, default='') content = models.TextField(blank=True, null=False) serializers.py class BooksSerializer(serializers.ModelSerializer): class Meta: model = Books fields = '__all__' @staticmethod def create(validated_data): return Books.objects.create(**validated_data) database entries id bookid title author content 5 0 <empty> <empty> Book Content expected database entries id bookid title author content 5 43 MyTitle John Doe Book Content -
How to get Many to many field values in DRF Serializer
In the below code , I need badge_color and badge_text should be shown under user_detail method Models.py class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.CharField(max_length=50, unique=True) user_badges = models.ManyToManyField(Badges,related_name='badges', null=True,blank=True,) class Badges(models.Model): badge_text = models.CharField(max_length=50) badge_color = models.CharField(max_length=50) class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=50, unique=False) date = models.DateTimeField("date of comment", default=timezone.now) comment_text = models.CharField(max_length=2500) Serializer for comments Class class CommentsSerializer(serializers.ModelSerializer): user_detail = serializers.SerializerMethodField() class Meta: model = Comments fields =[date,comment_text,user_detail] def get_user_detail(self, obj): if obj.user: return { "id": obj.user.id, "user_name": obj.user.user_name, "profile_pic": profile_pic, } else: return None Views.py .......... ............. qs=Comments.objects.all() comments=CommentsSerializer(qs, many=True) -
Docker image running in Elastic Beanstalk + Application Load Balancer Health Turns to Severe after a few minutes of working fine
Helping my wife on a project for one of her grad classes. Basically, she has to present on and demo containers and some cloud technology for a final. Helped build a super barebones Django application where the user can take a snapshot of themselves, submit it to Rekognition, and it responds with a drink recommendation based on their (perceived) mood. I have plenty of Azure experience, but not AWS. The extent of my AWS experience is helping her on this project for the past day. Ultimately what happens is the Health will be "OK" for several minutes, the application will work as expected, and then the Health will change to "Severe": From what I gather there are health checks EB performs in specified intervals, and if those fail, it breaks... even if the application is running fine. This only happens when I add an Application Load Balancer. I'm adding an Application Load Balancer because I need a SSL certificate, and per the documentation, that is the "... simplest way to use HTTPS with an Elastic Beanstalk." What has worked before adding the Application Load Balancer... Using my Dockerrun.aws.json to pull the image from Docker Hub, I build the application and … -
can i change django-all-auth: forms language
can i change django-all-auth: forms language , i want one language so i don't have to make translation how i can change placeholder and label name from English to other language in html login page i have this code : <form class="login form-group" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <input type="submit" value="login"> </form> when i open login page in browser it show email and pass input (box) in English i mean label name and placeholder how i can change it to other language -
django queryset - mysql : how to get distinct item w.r.t two columns
I have table as Model name: Test id col1 col2 1 A 1 2 A 1 3 A 3 4 B 1 5 B 1 6 B 4 7 D 2 8 D 3 9 D 3 10 F 3 11 B 4 I want to get all the rows with unique combination of col1 and col2 and the row with recent id id col1 col2 11 B 4 10 F 3 9 D 3 7 D 2 5 B 1 3 A 3 2 A 1 How can i get this i tried Test.objects.all().order_by('-id').distinct('col1','col2') But it says DISTINCT ON fields is not supported by this database backend -
Invalid input of type: 'Product'. Convert to a bytes, string, int or float first
I'm using redis version 6.2 This is the view which i'm working on: elif request.method == 'POST': user_key = request.user bid_price = request.POST.get('bid') retrieve_product = request.POST.get('product.id') product_key = Product.objects.get(id=retrieve_product) minimum_price = product_key.base_price if float(bid_price) >= minimum_price: if redis_instance.hexists(product_key, "highest_bid"): hb_value = redis_instance.hget(product_key, "highest_bid") else: redis_instance.hset(product_key, "highest_bid", bid_price) hb_value = bid_price if bid_price > hb_value: redis_instance.hset(product_key, user_key, bid_price) redis_instance.hset(product_key, "highest_bid", bid_price) messages.info('Your bid was successfully processed') return HttpResponse('successfully uploaded') else: return HttpResponse('Your bid is lower than current highest bid') else: return HttpResponse('Your bid is lower than minimum price') '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' This, instead, is the model: class Product(models.Model): name = models.CharField(max_length=200, null=True) base_price = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) digital = models.BooleanField(default=False, null=True, blank=True) start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField(default=one_day_hence) bidding_finished = models.BooleanField(default=False) def __str__(self): return self.name -
Angular category filtered screen
I am creating a ecommerce angular web app and I need some help. What I have I have created a parent categories component which lists all the categories that is in a table in my DB (I am using Django as my back end). In this component I have a child component that is responsible for the format of each category card that is created. Parent Component department.component.ts import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CookieService } from 'ngx-cookie-service'; import { ApiService } from 'src/app/api.service'; import { Category } from '../../models/Category'; @Component({ selector: 'app-department', templateUrl: './department.component.html', styleUrls: ['./department.component.css'] }) export class DepartmentComponent implements OnInit { categories: Category[] = []; constructor( private cookieService: CookieService, private apiService: ApiService, private router: Router) { } ngOnInit(): void { const urToken = this.cookieService.get('ur-token') if (!urToken) { this.router.navigate(['/auth']); } else { this.apiService.getCategories().subscribe( data => { this.categories = data; }, error => console.log(error) ); } } } department.component.html <section class="pt-5 pb-5"> <div class="container cards cards-hover"> <div class="row"> <div class="col-12 col-sm-6 col-md-4 m-0 p-0" *ngFor="let category of categories" routerLink="categoryList"> <app-department-item [categoryItem]="category"></app-department-item> </div> </div> </div> </section> Child Component department-item.component.ts import { EventEmitter, Input, Output } from '@angular/core'; import { Component, … -
"Expected a list of items but got type \"dict\".",
I have a list of users for whom I am trying to add to an event using the add_participants endpoint. My Django Viewset: class EventsCreationViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() authentication_classes = (TokenAuthentication, ) @action(detail=False, methods=['POST']) #detail means we want to accept details (a specific Movie), not just "/" def add_participants(self, request, pk=None): serialized = EventCreationSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data) else: return Response(serialized._errors) My React method: const CreateNewEvent = () => { #Create an entry for each user in list const eventParticipantPayload = eventParticipants.map((n) => JSON.stringify({ eventName: eventTitle, eventLocation: eventLocation, eventTime: date, eventParticipant: n, votingClosed: "False" })); console.log(JSON.stringify(eventParticipantPayload)) fetch(`http://127.0.0.1:8000/api/eventsCreation/add_participants/`, { method: 'POST', headers: { Accept: 'application/json', 'Authorization': `Token <some token>`, 'Content-Type': 'application/json' }, body: JSON.stringify({eventParticipantPayload}) }) .then(res => res.json()) .then(jsonRes => console.log(jsonRes)) .catch(error => console.log(error)); My request data from console.log ["{\"eventName\":\"Hjhjhjh\",\"eventLocation\":\"Gjhgjhgjhg\",\"eventTime\":\"2020-08-18T11:15:00.000Z\",\"eventParticipant\":2,\"votingClosed\":\"False\"}","{\"eventName\":\"Hjhjhjh\",\"eventLocation\":\"Gjhgjhgjhg\",\"eventTime\":\"2020-08-18T11:15:00.000Z\",\"eventParticipant\":1,\"votingClosed\":\"False\"}","{\"eventName\":\"Hjhjhjh\",\"eventLocation\":\"Gjhgjhgjhg\",\"eventTime\":\"2020-08-18T11:15:00.000Z\",\"eventParticipant\":3,\"votingClosed\":\"False\"}"] That fails with Object { "non_field_errors": Array [ "Expected a list of items but got type "dict".", ], } But.. when posting the below from POSTMAN, I get a 200 and my entries are added [ {"eventName":"swimming","eventLocation":"Xsport","eventTime":"2020-08-20T11:15:00.000Z","eventParticipant":2,"votingClosed":"False"}, {"eventName":"swimming","eventLocation":"Xsport","eventTime":"2020-08-20T11:15:00.000Z","eventParticipant":3,"votingClosed":"False"} ] So I don't think the issue is with my Django backend, but with how I am forming the list in the front end. -
Load django template dynamically
I've 2 section in my screen. Left section is for showing tabs and right is for displaying that tab template(as shown in screenshot). I'm not able to understand how to load different templates when I click these tabs For example, when I click change password, I should be able to load change_password.html template This is by far I've tried with code. <div class="nav"> <ul> <li class="active"><a href="#home" id="home" {% with section='home'%}{% endwith %}><i class="fa fa-home" aria-hidden="true"></i><span class="hidden-xs hidden-sm">Home</span></a></li> <li><a href="#change_password" id="change_password" {% with section='change_password'%}{% endwith %}><i class="fa fa-tasks" aria-hidden="true"></i><span class="hidden-xs hidden-sm">Change Password</span></a></li> <li><a href="#bookings" id="bookings" {% with section='bookings'%}{% endwith %}><i class="fa fa-bar-chart" aria-hidden="true" ></i><span class="hidden-xs hidden-sm">Bookings</span></a></li> <li><a href="#settings" id="settings" {% with section='settings'%}{% endwith %}><i class="fa fa-user" aria-hidden="true"></i><span class="hidden-xs hidden-sm">Settings</span></a></li> </ul> </div> I've tried to use with but no luck. I've just started with django, so if anything is missed let me know. Thanks for your help! Screenshot -
How to save CSV files in the MEDIA_ROOT in Django?
I have the following view with me def import_data(request): column_names = ['a', 'b', 'c'] with open('template_new.csv', 'w+', newline = '') as file: writer = csv.writer(file) writer.writerow(column_names) Now how do I save this particular CSV file in MEDIA_ROOT ? I cannot use return response though because I want to read this in another function. -
'bokeh.server.django' is not a valid Python identifier
I am trying to embed a bokeh server in a django server so as to run bokeh app inside a django app. I got the advice from this thread here, which leads me to a github repo here. When I extract the code from the repo and run as instructed in Readme file, I got this error django.core.exceptions.ImproperlyConfigured: The app label 'bokeh.server.django' is not a valid Python identifier.. So I check the app list in settings.py. There is a bokeh.server.django listed in there. And in the urls.py, there is an import of this as well: import bokeh from bokeh.server.django import autoload, directory, document, static_extensions This indicates that this app seems to be part of bokeh? So why is the error? Have I missed installing something? I have installed channels, panel, and of course bokeh. If someone could advise? Thanks. -
How to set a json object to the hidden input in Django
How to add json to hiddeninput? Works it, when input is visible but I wish it was hidden. I added a widget in form. Show me error. | (Hidden field geolokalizacja) This field is required. | forms.py class MapaForm(forms.ModelForm): class Meta: model = Mapa fields = ('geolokalizacja',) widgets = {'geolokalizacja': forms.HiddenInput()} html <form action='.' method='post' enctype='multipart/form-data'> {{ create_form.as_p }} {{ mapa_form }} {% csrf_token %} <p><input type="submit" value="Dodaj obiekt"></p> </form> <div id="map" style="height: 512px; width: 512px;"></div> js var popup = L.popup(); function onMapClick(e) { popup.setLatLng(e.latlng).setContent( e.latlng.toString()).openOn(map); var json = {'type': 'Point', 'coordinates': [e.latlng.lng, e.latlng.lat]}; $("#id_geolokalizacja").val(JSON.stringify(json)) } In DOM and Style Inspector displays this to me when Js pass json to input: <input type="hidden" name="geolokalizacja" value="null" id="id_geolokalizacja"> {"type":"Point","coordinates":[21.91454887390137,52.018592439773414]} </input> It looks like an ale has adopted. Please help -
Custom json formatted django error page with nginx & gunicorn
Currently working on a project and I'm almost done with just the custom error page that I'm trying to implement that's is giving me issues. This is my view for the error views from django.http import JsonResponse def error_404(request, exception): message=('The endpoint is not found') response = JsonResponse({'msg': message, 'status_code': 404, 'status': 'false'}) response.status_code = 404 return response def error_500(request): message=("An error occurred, it's on us :(") response = JsonResponse({'msg': message, 'status_code': 500, 'status': 'false'}) response.status_code = 500 return response This is my URLConf from django.conf.urls import url, handler400, handler404, handler403, handler500 ... handler400 = 'rest_framework.exceptions.bad_request' handler404 = 'utils.views.error_404' handler500 = 'utils.views.error_500' Nginx setup server { listen 80; server_name X.X.X.XXXX; keepalive_timeout 5; client_max_body_size 4G; location = /favicon.ico { access_log off; log_not_found off; } location ~* \.(eot|otf|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; root /home/glc/glc_project; } location /static/ { alias /home/glc/glc_project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } It works on my local machine even when Debug = False but doesn't work as should on Digitalocean. Please any help? -
page not found in django 404
I need help to solve a page not found issue on my code, so i created an app called pages inside which I created another folder named templates followed by the app name then i render the index html without issue but when I try to render the about.html file I get an error of page not found this is the app(pages)urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('about/', views.about_view, name='about'), ] then the views.py from django.shortcuts import render # Create your views here. def about_view(request): return render(request, 'pages/about.html') def index(request): return render(request, 'pages/index.html') then projects url.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('about/', include('pages.urls')), path('', include('pages.urls')), ] so the main issue is that i cant render a new html file because when i try i get the page not found error -
How to prevent permission records creation of external apps
I use a library called django-auditlog, by default the app migrate a model to database called auditlog_logentry and also generate default permission for view, add, change and delete. I need to prevent theses permission creation. I could remove all permissions related to the model in each migration, but I think it is not the correct way. -
Django - formset with crispy forms - missing management form data
I'm trying to render this form set: ProductFormSet = modelformset_factory( model=Product, fields='__all__', extra=5, ) class ProductFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.layout = Layout( Row( 'productCategory', 'name', 'measurement_unit', ) ) self.render_required_fields = True with this view: def product_create(request): helper = ProductFormSetHelper() context = { 'helper': helper, 'title': 'Nuovi Prodotti', } if request.method == 'GET': formset = ProductFormSet(queryset=Product.objects.none()) context['formset'] = formset elif request.method == 'POST': formset = ProductFormSet(request.POST) context['formset'] = formset if formset.is_valid(): formset.save() messages.success(request, 'Prodotti aggiunti correttamente', fail_silently=True) return HttpResponseRedirect(reverse('warehouse:products_list')) else: return render(request, 'warehouse/product_create.html', context) return render(request, 'warehouse/product_create.html', context) and this template: {% extends "masterpage.html" %} {% load static %} {% block headTitle %} <title>Nuovo Prodotto</title> {% endblock %} {% block contentHead %} {% endblock %} {% block contentBody %} {% load document_tags %} {% load custom_tags %} {% load crispy_forms_tags %} <FORM method="POST" autocomplete="off"> <div class="alert alert-info"> {{ title }} </div> {{ formset.management_form }} {% crispy formset helper %} <input type="submit" class="btn btn-primary margin-left" value="SALVA"> </FORM> {% endblock %} Problem is that when I submit the form I get the: ValidationError: management form data are missing! First of all, using crispy forms the management data should be included, second even if I explicitly call with … -
How do I access my MySQL DB through command line?
So I'm working on this Django project, with MySQL as DB engine. I made some sort of mistake, and now I have to drop a table I accidentally created. So I'm trying to access the DB through command line, but cannot figure out how. Could anyone help? Or is there a better way of dropping a table in MySQL DB?Thanks in advance.