Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm getting an IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id
Im trying to remove the dropdown so that the user can only see his/her username.Image of the author dropdown.[Image that i want to happen][2] The code -
Using django-dbbackup with parameters not working in view
I am trying to make a view for my user to save and restore database using django-dbbackup. I need my user to be able to decide the name of file for saving and the file to be restored using FormView. But commands dbbackup and dbrestore are not accepting parameters when I call them with call_command in view.py, but doing manage.py dbbackup -o mycopy in terminal works. Still learning. error in backup: raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'dbbackup -o mycopy' Is there another way to restore and backup without using terminal? -
Template Not Found
Hey i am new to django and I am almost done with my first project but I am getting a problem when I open my Site with heroku using heroku open in the terminal when the Site open I get an error that my base template is missing. Settings BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] any html {% extends "learning_logs\base.html" %} ......... error TemplateDoesNotExist at / learning_logs\base.html django.template.loaders.filesystem.Loader: /app/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/learning_logs/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/bootstrap4/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/templates/learning_logs\base.html (Source does not exist) If any other code might help please tell me. -
Django makemigrations not finding tables
I have a Django APP that work perfectly fine. I downloaded the repository from Github to a new laptop, but when I try to run: python manage.py makemigrations runserver etc I get django.db.utils.OperationalError: no such table: catalog_categorias_producto Already tried: Deleted db.sqlite3 Deleted all migration files (except __init__) Tried makemigrations again No difference. Any clues? Thanks! -
Deploy Django Server with a built-in Vue.js App built with Wepback on Heroku
I am stuck in the deployement of a vue.js django together on heroku. I have tried to load the code on heroku and the is deployed correctly. The problem is that the frontend isn't loaded correctly but, when I click on view, I receive the the message: "An error occurred in the application and your page could not be served" Following the tips "heroku logs --tail", the terminal shows the messages 2020-11-10T22:08:40.000000+00:00 app[api]: Build succeeded 2020-11-10T22:08:40.477011+00:00 app[web.1]: 2020-11-10T22:08:40.477025+00:00 app[web.1]: > frontend@0.1.0 start /app 2020-11-10T22:08:40.477026+00:00 app[web.1]: > node bundle.js 2020-11-10T22:08:40.477026+00:00 app[web.1]: 2020-11-10T22:08:40.516540+00:00 app[web.1]: internal/modules/cjs/loader.js:969 2020-11-10T22:08:40.516541+00:00 app[web.1]: throw err; 2020-11-10T22:08:40.516542+00:00 app[web.1]: ^ 2020-11-10T22:08:40.516542+00:00 app[web.1]: 2020-11-10T22:08:40.516542+00:00 app[web.1]: Error: Cannot find module '/app/bundle.js' 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15) 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 { 2020-11-10T22:08:40.516544+00:00 app[web.1]: code: 'MODULE_NOT_FOUND', 2020-11-10T22:08:40.516544+00:00 app[web.1]: requireStack: [] 2020-11-10T22:08:40.516545+00:00 app[web.1]: } 2020-11-10T22:08:40.520609+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2020-11-10T22:08:40.520813+00:00 app[web.1]: npm ERR! errno 1 2020-11-10T22:08:40.521710+00:00 app[web.1]: npm ERR! frontend@0.1.0 start: `node bundle.js` 2020-11-10T22:08:40.521801+00:00 app[web.1]: npm ERR! Exit status 1 2020-11-10T22:08:40.521915+00:00 app[web.1]: npm ERR! 2020-11-10T22:08:40.522006+00:00 app[web.1]: npm ERR! Failed at the frontend@0.1.0 start script. 2020-11-10T22:08:40.522077+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging … -
How to get object with largest number of related objects in django
I have model A(Post): class Post(models.Model): title = models.CharField(max_length=30) and model B(Like): class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) How would I retrieve the Post object with the largest number of likes? -
crispy form not populating with data from primary key
I have a form that I want to send data to from another page. The data is definitely sending as I have a test template tag which populates based on the FK but the form itself won't populate the data. models.py class Project(models.Model): curr_choices = ( ('USD', 'USD'), ('GBP', 'GBP'), ('EUR', 'EUR'), ) production_title = models.CharField(max_length=200, unique=True) budget = models.FloatField() currency = models.CharField(max_length=3, choices=curr_choices, default='USD') distributor = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, upload_to="static/images") proj_media = models.CharField(max_length=200) licencee = models.CharField(max_length=200) rating = models.CharField(max_length=20) release_date = models.DateField() synopsis = models.TextField() term = models.CharField(max_length=20) territory = models.CharField(max_length=20) writer_spot = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.production_title views.py def update_project(request, pk): update = Project.objects.get(id=pk) if request.method == "POST": form = ProjectForm(request.POST, request.FILES, instance=update) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('projects') else: form = ProjectForm() context = { 'form': form, 'update': update } return render(request, "projectsync/create_project.html", context) forms.py class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( PrependedText('production_title', "", placeholder="Example Title"), PrependedText('licencee', "", placeholder="Example Licencee"), PrependedText('distributor', "", placeholder="Example Distributor"), PrependedText('writer_spot', "", placeholder="Example Writer of Spot"), PrependedText('synopsis', "", placeholder="Example Synopsis"), Row( Column('currency', css_class='form-group col-md-2 mb-0'), Column(PrependedAppendedText('budget', "", '.00'), css_class='form-group col-md-10 mb-0'), css_class='form-row' ), Row( Column(PrependedText('term', … -
Django Multiple Forms One Page
I have two forms on one page (enquiry / make a booking). At any one time only one of these two forms will be submitted. This is my current views.py. def contact_us(request): if request.method == 'POST': # booking form if 'timezone' in request.POST: # timezone field only in booking_form booking_form = BookingForm(request.POST, request.FILES) if booking_form.is_valid(): booking_form.save() return redirect('thankyou') else: enquiry_form = EnquiryForm(request.POST, request.FILES) if enquiry_form.is_valid(): enquiry_form.save() return redirect('thankyou') else: booking_form = BookingForm() enquiry_form = EnquiryForm() context = { 'booking_form' : booking_form, 'enquiry_form' : enquiry_form, } return render(request, 'contact_us/contact_us.html', context) It works fine apart from when the form validation fails and it should return an error (for example, I have a datefield and if the user enters a date outside of the accepted range). When this happens I get the following error: local variable 'enquiry_form' referenced before assignment Any help would be greatly appreciated. Thank you. -
Django loses connection to MySQL db after initialization (Docker)
I'm starting to work with Docker, I'm running a Django app in a container, and a MySQL db in another one. Both of them are connected through a docker-compose.yml file. After building the containers, Django migrations run successfully and the application starts properly. However, if I connect to the Django container and execute a command (i.e. python manage.py createsuperuser) an OperationalError is raised saying that it is not possible to connect to the database. What can be the problem? The picture below shows that tables are created in the database (at some point Django does have access to the db) Accessing the 4rs_backend container (Django) with docker exec -it <container id> sh and executing python manage.py createsuperuser raises: docker-compose.yml: version: '3' services: db: image: mysql:5.7 ports: - "7000:3306" environment: MYSQL_PORT: 3306 MYSQL_USER: admin_test MYSQL_ROOT_PASSWORD: '*****' MYSQL_PASSWORD: '*****' MYSQL_DATABASE: forrealstate container_name: mysql_db api: build: backend command: bash -c "BUILD_TYPE='DOCKER' python manage.py makemigrations && BUILD_TYPE='DOCKER' python manage.py migrate && BUILD_TYPE='DOCKER' python manage.py runserver 0.0.0.0:8000" container_name: 4rs_backend volumes: - ./backend:/backend ports: - "8000:8000" depends_on: - db DATABSE config in Settings.py: BUILD_TYPE = os.environ.get('BUILD_TYPE') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'forrealstate', 'USER': 'admin_test' if BUILD_TYPE == 'DOCKER' else 'root', 'PASSWORD': '********', 'HOST': … -
Prepolate django model form
I have an Event Model and a Nominate Model. The Event Model is a Foreign Key in the Nominate Model. I want my form to be pre-populated with the current event. Any help on how to handle it with the forms or model will be appreciated. class Event(models.Model): """ Model used to store events """ name = models.CharField(max_length=256) class Nominate(models.Model): name = models.CharField(max_length=256) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="nominees") -
How do I query django parent and child by a one to many relationship?
So I am fairly new to django and I am trying to create a website keeps a log of who took out their families' dogs last. I have made my models to include tables for each individual post, dog, and their actions that correspond with the posts themselves. I want to make it so that a list of posts will be placed in order of latest to earliest post followed by all of the actions that each dog did (i.e. if there are two dog objects then there will be two action objects that accompany the post). models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Dog(models.Model): name = models.CharField(max_length = 20) class Post(models.Model): walker = models.ForeignKey(User, on_delete = models.CASCADE) time_posted = models.DateTimeField(default = timezone.now) issues = models.TextField(max_length = 300) class Action(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) dog = models.ForeignKey(Dog, on_delete = models.CASCADE) peed = models.BooleanField(default = False) pooped = models.BooleanField(default = False) views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Post, Dog, Action from django.http import HttpResponse class ActionList(ListView): def home(request): context = { 'posts': Post.objects.all(), 'actions': Action.objects.all(), 'dogs': Dog.objects.all() } return render(request, 'dog_log_app/home.html', context) main.html: <!DOCTYPE html> … -
My project is not finding my django module
Here is my project's git: https://github.com/DieterClaessens67/SOA I keep getting this error when I do python manage.py runserver: despite executing pip install django in de venv As I already mentioned I am using virtual environments. Here is a quick overview of my project structure for clarity: Can anyone please tell me what is going wrong here? -
Django get OAuth user id while submitting a form (This field is required while uploading)
I'm trying to make an "upload avatar" form for users that are registered through OAuth. If I only have 'avatar' as my choice of fields for the form I get "This field is required" as the response every time. I need a way to get the currently logged in user and submit his id alongside the uploaded avatar. forms.py from django import forms from django.core.files.images import get_image_dimensions from soc_auth.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile #fields = '__all__' fields = ['avatar'] #def __init__(self, user, *args, **kwargs): #self.user = user #super(UserProfileForm, self).__init__(*args, **kwargs) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not … -
How to change Django views into Django rest framework views?
hi I'm coding a shopping cart and I write the cars session but I couldn't write the view .I searched and found a code that had the view but it was for django and had forms could you please help me to change the views into django rest framework??? actually my problem is the cart_add function in views this is the code??? #cart CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['total_price'] = int(item['price']) * item['quantity'] yield item def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def add(self, product, quantity): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def get_total_price(self): return sum(int(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[CART_SESSION_ID] self.save() #views.py def detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart':cart}) @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddForm(request.POST) if form.is_valid(): cd = … -
Send back data changed on backend
I made a POST method to send data from user input , recive it with Django views.py . Now i want to do some changes(ex. calculate return on invest) on that data and then send it again to display it on my page. Im stuck in it right now. I would really appreciate some help. views.py def valid(request): if request.is_ajax(): request_data = request.POST.getlist("invest")[0] investment = calculate_return_on_invest(request_data) return JsonResponse(investment, safe=False) script.js function ajaxdata(){ let invest = document.getElementById('investment').value; $.ajax({ method:'POST', url:'/valid/', data: { 'invest': invest, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data){ alert("works"); }, error: function(data){ alert("doesn't work") } }); }; -
how to order by 1 in Django template
I have this Django template, which works template = '%(function)s(%(expressions)s ORDER BY "col_name")' However, I want to replace "col_name" with 1, e.g. template = '%(function)s(%(expressions)s ORDER BY 1)' This does not do the ordering properly what can I do? -
Django backend authentication with NextJS frontend form - best practices
I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices. Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue. React const login = async () => { let token = await axios.post('/api/accounts/', { email: email, password: password }).then(r => r.data.token).catch(function (error) { console.log(error) }) if (token) { router.push({ pathname: '/home/', query: { token: token }, }) } } nexjs server api/accounts export default async (req, res) => { if (req.method === 'POST') { try { // retrieve payment intent data const {data} = await axios.post('https://website/api/api-token-auth/', req.body) res.status(200).send(data) } catch (err) { res.status(500).json({ statusCode: 500, message: err.message }) } } else { res.setHeader('Allow', 'POST') res.status(405).end('Method Not Allowed') } } Django API @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def obtain_auth_token(request): email = request.data.get("email") password = request.data.get("password") if email is None or password is None: return Response({'error': 'Please provide both email and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(email=email, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) Once … -
How to implament teacher student functionality into django?
Hi im working on a school project. I am supposed to make a teacher control panel that lets the teacher group students and stuff. How do i do such thing? Is there anything implamented in django. Also i cant just use the admin panel build into django because it should be a admin more of a like moderator. Hopefully you have some answers. -
Unable to import installed package in Python
I'm attempting to use the following Python package: https://github.com/amadeus4dev/amadeus-python I have installed it as a global package via the pip3 install amadeus command and can see that it has been installed correctly, as reported by pip3 list Despite it being installed, I am receiving the following error when trying to import it into a Django view: Unable to import 'amadeus'pylint(import-error) Troubleshooting Uninstalled the package and reinstalled using sudo pip3 install amadeus Uninstalled the package and reinstalled using python3 -m pip install amadeus Checked that the package has been installed within a directory in my system path. I'm currently all out of ideas for why it won't work for me and would be grateful if somebody had any ideas? Thank you! -
Django - running both Functional and Unit test in a single test file
I am using Django 3.1 and Python 3.6 I have an app that I want to run both functional and unit tests for, by running ./manage.py test myapp /path/to/project/myapp/test.py import os from django.test import TestCase from selenium import webdriver from django.contrib.staticfiles.testing import StaticLiveServerTestCase import time # Create your tests here. class FunctionalTestCase(StaticLiveServerTestCase): fixtures = ['user_test_data.json','foo_test_data'] @classmethod def setUpClass(cls): super().setUpClass() loc='/path/to/some/loc/' chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("user-data-dir=/home/morpheous/") # cls.browser = webdriver.Chrome(os.path.join(loc, 'chromedriver'), chrome_options=chrome_options) @classmethod def tearDownClass(cls): cls.browser.quit() super().tearDownClass() def test_functest_one(self): pass def test_functest_two(self): pass # Create your tests here. class UnitTestCase(TestCase): def test_some_unit_test(self): pass When I run ./manage.py test myapp It only run the functional tests and says two tests failed (as expected). How do I run BOTH the functional and unit tests? -
customizing django admin tabular inline using smart_selects chained select field
I am trying to implement dependent select field called ChainedForeignKey (dependent on another select field) using smart_selects . I have followed the documentation (https://django-smart-selects.readthedocs.io/en/latest/index.html)but they do not consider (Django admin) templates where you have no {{ form.as_p }} tag. I'm pointing this out because one of the implementation steps is to include {{ form.media.js }} tag before your {{ form.as_p }}. However django tabular inline template (located in pathtodjango\contrib\admin\templates\admin\edit_inline\tabular.html) looks as following; {% load i18n admin_urls static admin_modify %} <div class="js-inline-admin-formset inline-group" id="{{ inline_admin_formset.formset.prefix }}-group" data-inline-type="tabular" data-inline-formset="{{ inline_admin_formset.inline_formset_data }}"> <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}"> {{ inline_admin_formset.formset.management_form }} <fieldset class="module {{ inline_admin_formset.classes }}"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2> {{ inline_admin_formset.formset.non_form_errors }} <table> <thead><tr> <th class="original"></th> {% for field in inline_admin_formset.fields %} {% if not field.widget.is_hidden %} <th{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }} {% if field.help_text %}&nbsp;<img src="{% static "admin/img/icon-unknown.svg" %}" class="help help-tooltip" width="10" height="10" alt="({{ field.help_text|striptags }})" title="{{ field.help_text|striptags }}">{% endif %} </th> {% endif %} {% endfor %} {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %} </tr></thead> <tbody> {% for inline_admin_form in inline_admin_formset %} {% if inline_admin_form.form.non_field_errors %} <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr> {% endif %} <tr class="form-row {% cycle "row1" "row2" %} … -
Django: javascript variable intermittently not being passed (variable undefined after assignment)
I'm hoping someone can spot what I'm doing wrong here. I have a dropdown list which triggers a javascript function to change the language. It works exactly as expected maybe 19/20 times, but every so often, one variable (always the same one) is undefined after assignment. I've trapped the code with an alert statement to make sure the HTML is rendered ok on the page - it is. I flip between two languages over and over, fine then suddenly, with no changes, I get the variable undefined error. In the Django-rendered HTML: <div class="collapse navbar-collapse flex-grow-0 float-right" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Català </a> <div class="dropdown-menu" role="menu" id="language-list" aria-labelledby="navbarDropdownMenuLink"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <link rel="alternate" hreflang="es" href="http://localhost:8000/es/noticias/el_segundo_elemento" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="es" data-next="/es/noticias/el_segundo_elemento"> <img src="/static/es.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Español </a> <link rel="alternate" hreflang="en" href="http://localhost:8000/en/news/the_second_item" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="en" data-next="/en/news/the_second_item"> <img src="/static/en.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;English </a> <link rel="alternate" hreflang="fr" href="http://localhost:8000/fr/nouvelles/le_deuxieme_element" /> <a class="dropdown-item" href="/i18n/setlang/" data-language-code="fr" data-next="/fr/nouvelles/le_deuxieme_element"> <img src="/static/fr.png" class="d-inline-block align-middle pb-1" alt="" loading="lazy"> &nbsp;Français </a> </div> </li> </ul> </div> The data-next tag is the one giving me the … -
Django REST Framework: Type Error When Trying To Update Using Nested Serializer
I am trying to use a nested serializer in Django Rest Framework. I basically want to update my instance in a single shot. When I send my response, it throws an error saying- save() got an unexpected keyword argument 'id'. I tried popping "id" but then it just repeats the same error with a different attribute. Here is my model: models.py class Language(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) serializers.py from ..models import Language, Lead, Genre, Business from rest_framework import serializers class LanguageSerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Language fields = "__all__" class LeadSerializer(serializers.ModelSerializer): id = serializers.IntegerField() language_id = LanguageSerializer(many=True) class Meta: model = Lead fields = "__all__" def update(self, instance, validated_data): language_ids = [item['id'] for item in validated_data['language_id']] for language in instance.language_id.all(): if language.id not in language_ids: language.delete() for item in validated_data['language_id']: if item.get("id", None) is not None: lang = Language.objects.get(id=item["id"]) lang.save(**item) #This throws an error else: lang = Language.objects.create(**item) instance.language_id.add(lang) validated_data.pop("language_id") validated_data.pop("id") instance.save() return instance -
Django template simple {% block %} and {% extends '' %}
So guys, i'm trying basics from django and {% block %} statement seems not to work for some reason... this is my forms.html: <body> {% include "homepage/navbar.html" %} <div class="container-fluid"> {% block content %} {% endblock content %} </div> {% include "homepage/footer.html" %} </body> and this is my form_model.html: {% extends 'forms/forms.html' %} {% block content %} <h1>Hello world</h1> {% endblock content %} Settings.py in templates: 'DIRS': [BASE_DIR, '/homepage/' '/boards/' '/forms/' ], -
Integrity & NotNull errors for null value in DateField column, but null=True, and blank=True
I'm currently using a Django backend, with a React/Redux frontend. When I try to add a new "Day" to my database, I get: psycopg2.errors.NotNullViolation: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). django.db.utils.IntegrityError: null value in column "day_date" ... violates not-null constraint DETAIL: Failing row contains (2, null, Tu). This shouldn't be an issue because in my model, day_date is a DateField: class Day(models.Model): day_id = models.AutoField(primary_key=True) day_date = models.DateField(blank=True, null=True) day_str = models.CharField(max_length=30, blank=True) class Meta: db_constraints = { 'CHK_DayNotNull': 'CHECK (day_date IS NOT NULL OR day_str <> "")' } I thought maybe it was an error with my constraint, but when I deleted the constraint I get the same error. I tried playing with the inputs of the day_date field in the model; I tried all the combinations and get the same error which makes me think something is wrong with how my database is being updated. I'm using PostgreSQL for my database. I tried clearing cache. deleting all my migrations, and then running, python3 manage.py flush python3 manage.py makemigrations python3 manage.py migrate but I'm still getting the exact same error.