Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize a list of data in ManyToMany relantionship in Django RESTful API and properly create nested objects?
i think is a silly question but for few days I cann't hadle with it... I've go a a two models: Book and Authors. Book can have many Authors, and Authors can have many Book(s). I;m POST-ing a new Book, and i'm passing a "title" and a list of Authors (i'm passing a list of dictionaries like in example below). I want to create new Authors from this list but wihout overwriting old ones. models.py: class Authors(models.Model): name = models.CharField(max_length=50, blank=True) class Book(models.Model): title = models.CharField(max_length=60, blank=False, null=False) authors = models.ManyToManyField(Authors) serielizers.py: class AuthorsSerializer(serializers.ModelSerializer): class Meta: model = Authors fields = '__all__' class BookSerializer(serializers.ModelSerializer): authors = AuthorsSerializer(many=True) class Meta: model = Book fields = ['id', 'title', 'authors'] depth = 1 def create(self, validated_data): authors_data = validated_data.pop('authors') book = Book.objects.create(**validated_data) for autor in authors_data: Authors.objects.create(book=book, **autor) return book views.py: class BooksList(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer urls.py: book_list = BooksList.as_view({ 'get': 'list', 'post': 'create', }) book_detail = BookDetails.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}) authors_list = AuthorsList.as_view({ 'get': 'list', 'post': 'create'}) urlpatterns = format_suffix_patterns([ path('books/', book_list, name='book_list'), path('books/<int:pk>', book_detail, name='book_detail'), path('authors/', authors_list, name='authors_list'), ]) When I'm POST-ing a new object in webrowser in RESTful API like this: { … -
I got an error in my project when I want start django
I'm making a project in my school and works well in the school pc, but today when I'm pass the project to my pc and type: python manage.py runservice This appears: (venv) PS C:\> cd MiColegio (venv) PS C:\MiColegio> python manage.py runservice Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\venv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\DANIEL\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'admin_interface' (venv) PS C:\MiColegio> Any Idea? -
Saving to values to model that extends the user model when creating a new record
I have a model that extends the default Django User model. It is intended to store user information pulled from an API, particularly the UUID associated with the user. This is the model: # Django dependencies from django.contrib.auth.models import User from django.db import models class Oid(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) oid = models.UUIDField() class Meta: db_table = 'auth_user_oid' constraints = [ models.UniqueConstraint(fields=['oid'], name='unique_oid') ] This is where to record is being created: # serializers.py email = user_validations['graph_response']['mail'].lower() first_name = user_validations['graph_response']['givenName'] last_name = user_validations['graph_response']['surname'] oid = user_validations['graph_response']['id'] obj, created = models.User.objects.get_or_create( username = email, first_name = first_name, last_name = last_name, email = email, is_staff = True, oid = oid ) The oid = oid is just one of a number of different things I've tried. This iteration in particular just says: ValueError: Field 'id' expected a number but got 'UUID'. I'm just wondering: how an I'm supposed to be saving records to the extended model when a new User record is being created? -
Filtering Datetime field by date not working in Django
I'm trying to filter a Datetime model field by date only and have tried: Content.objects.filter(created_at__date=params.get("event_date")) The event_date parameter is formed like 2021-04-07. I've tried creating a datetime object and have also tried this: search_params["created_at__lte"] = datetime.datetime(int(date[0]), int(date[1]), int(date[2]), 0, 0, 0) search_params["created_at__gte"] = datetime.datetime(int(date[0]), int(date[1])+1, int(date[2]), 0, 0, 0) However, all of these methods return an empty query set and they should return one result. The result has a Datetime field (2021-04-07 23:00). -
how can i get always data based on the logged user?
I'm Working with Django / Rest Framework and I have multiple applications and I would like to avoid repeaters in my situation, I would like to get the logged user data without repeating this line each time : queryset = queryset.filter(user = self.request.user) -
How to convert raw queryset to queryset?
The raw query itself is correct and I am able to get retrieve the raw query set from the db. I need to convert this into query set for further processing and I am facing below error. Creating corresponding django query was hard for me and that is why I created SQL query, got the raw query set and now attempting to convert it to query set for further processing. I have changed django model names and table names for anonymity. Here is the output of what I tried in django shell. The "test3.value" will be dynamically set and I am doing that in the raw query statement. from django.db.models.expressions import RawSQL from xyz.models import * value = '1.2.3.4' queryset = Test1.objects.filter(id__in=RawSQL("SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS (SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id AND test3.value = {} JOIN test4 ON test2.test4_id = test4.id AND test4.test1_id = test1.id) ORDER BY test1.start_time DESC".format(value))) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __init__() missing 1 required positional argument: 'params' For readability I have formatted the raw sql query used above. SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM … -
request.POST.get(variable) returns None when trying to receive by id
Ok so, help me out here I'm going crazy! I have 4 questions each with a radio button name set to the question id and the value set to the answer id to get the answer's id and use it to get the user's submitted answer to check if it is correct or not. views.py def sampleQuestions(request): if request.method == 'POST': user = request.user userInformation = UserInformation.objects.get(user=user) allAnswers = Answers.objects.all() allQuestions = Questions.objects.all() i = 0 for q in Questions.objects.all(): print(q.id) #returns 1 answerID = request.POST.get(q.id) #returns None print(answerID) answer = Answers.objects.get(id=answerID) print(answer) template.html {% for q in questions %} <table> <tr> <td> {{q.question}}</td> </tr> {% for a in answers %} {% if a.answerForQuestion == q%} <tr> <td> <input type="radio" name = "{{q.id}}" value="{{a.id}}"> {{a.answer}}</td> {{q.id}} </tr> {% endif %} {% endfor %} </fieldset> </table> {% endfor %} -
django ckeditor codesnippet is not responsive
I am using the Django-CKEditor and the problem that I have is that the code area (codesnippet plugin) is not responsive and some of the code gets out of the highlighted area as I make the page smaller. Also, I am using bootstrap in my project too. It's okay on larger screens: But as I make the size smaller The problem happens: I have done the following configuration in my settings.py and on the HTML page: INSTALLED_APPS = [ # other apps 'ckeditor', 'ckeditor_uploader', ] # ckeditor CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', # 'height': 300, # 'width': 960, 'width': 'auto', 'height': '600', 'extraPlugins': ','.join([ 'codesnippet', 'div', 'autolink', 'autoembed', 'embedsemantic', 'autogrow', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath', 'mathjax', ]), }, } {% load static %} <script type="text/javascript" src="{% static 'ckeditor/ckeditor-init.js' %}"></script> <script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script> <link rel="stylesheet" href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/default.css' %}"/> <script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script> <script>hljs.initHighlightingOnLoad();</script> And also I have collected the static files: Thank you for anything you can do to help. -
Using Bitcash Function on Django Queryset
I am using the Bitcash library and attempting to call the balance function on a private key. The problem is that I am storing the private key as a SlugField and retrieving it as a Queryset. How can I store is as a type of the Bitcash class PrivateKey? storing priv_key = models.SlugField(max_length=200, null=True) retrieving priv_key = KeyStore.objects.values('priv_key') how I want to use it bal = priv_key.balance the error message 'QuerySet' object has no attribute 'balance' the bitcash type that I would like to store <class 'bitcash.wallet.PrivateKey'> -
Restart django on linux
Ive deployed a django app on linux using nginx, supervisor and gunicorn. I have made updates (using GIT and manually in settings.py). The files changed but the application has not changed (i.e. it still functions the same as before the changes were added). I've tried lots of commands but none of them work e.g. //reload/restart nginx sudo service nginx restart sudo systemctl reload nginx sudo systemctl restart nginx //reload supervisor sudo supervisorctl reload //restart gunicorn (supervisor) sudo supervisorctl restart gunicorn //reboot ubuntu using systemctl sudo systemctl reboot //reboot ubuntu sudo reboot now //force reboot ubuntu sudo reboot -f Any help is greatly appreciated. -
How to force_authenticate in Django Rest Framework tests
I have problem with testing API built in DRF tutorial: https://www.django-rest-framework.org/tutorial/1-serialization/ I have view: class SnippetList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] queryset = Snippet.objects.all() serializer_class = SnippetSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) And test class for testing that view: class SnippetsList(APITestCase): def setUp(self): self.user = User.objects.create_superuser(username='testowy', password='test') self.client = APIClient() Snippet.objects.create(code="print('hello')", owner=self.user) Snippet.objects.create(code="print('world')", owner=self.user) self.payload = { "code": "print(edit)" } def test_get_snippets_list(self): response = self.client.get(reverse('snippet_list')) snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_post_snippets_list(self): self.client.force_authenticate(self.user) response = self.client.post(reverse('snippet_list'), json.dumps(self.payload), format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) When I run my tests with python manage.py test first test (for get method) is passing but for the second I get this output: self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 In manual tests after login in everything works perfectly, does anyone knows what am I missing here? -
Django - hide button if condition is true
Please help me solve a question! I'm using Django. I have a page where I listed all the questionnaires I made. Every questionnaires has a button next to it that links to a questionnaire on my main site. I like to make every questionnaires to can be filled just one time to every authenticated user but I can't figure out what is the best way to do this. Now I think that I create a hidden field into every questionnaires with a TRUE value and when the user clicks the submit button it stores in the db with the other answers. I query and retrieve the value and grab it with Javascript. If the value is TRUE it hides the button on the main site so it can't be clickable. Is this solutions good or it can be made easier? -
creating a profile for a user in django failed
I'm trying to create a profile for a user in django using signals when the user profile is created I need to create a profile automatically. from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(default='default.png',upload_to='profile_pics') bio = models.CharField(max_length=200,blank=True) def __str__(self): return self.user.username this is in the signals.py file: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender,instance,created,**kwargs): instance.profile.save() and here is the register view: def registerUserView(request): """ this is for registring a new user""" if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'your account has been created successfully! you are able to login') return redirect("login") else: form = UserRegisterForm() return render(request,"users/register.html",{"form":form}) now I don't know the error that has been occured this time. django version 2.2 and python 3.8. -
How come Apache2 isn't recognizing the Django module installed to a virtual environment?
I'm using Ubuntu 18.04, and have libapache2-mod-wsgi-py3 and apache2 installed. I have a Django project located at /home/usr/django_project/ and I created a python 3.8 virtual environment inside the django_project folder. I used pip3 install -r requirments.txt inside the virtual environment to install all the necessary dependencies. My settings.py is as follows: import os import json with open('/etc/django_personal_website-config.json') as config_file: config = json.load(config_file) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_personal_website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_personal_website.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ … -
Image media is not getting upload on AWS S3 media folder-CKEditor
When I was uploaded image from backend django admin then the image is not getting upload on aws s3 media folder with name django-ckeditor-5/example.img. It is creating one folder with name django-ckeditor-5 on local server. but Not uploading on aws s3 media folder. I have tried these both path but not working url(r'^ckeditor5/(?P<path>.*)/?$', include('django_ckeditor_5.urls')), and path("ckeditor5/", include('django_ckeditor_5.urls')), Click here to see the image of problems. below is my settings.py configuration for aws and media url STATIC_URL = 's3url/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT = "s3url/static/" MEDIA_URL = 's3url/media/' DEFAULT_FILE_STORAGE = '' PUBLIC_MEDIA_LOCATION = 'media' AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'SOME-bucket' AWS_S3_CUSTOM_DOMAIN = '' AWS_LOCATION = '' AWS_DEFAULT_ACL= None -
Django Dynamic Formsets Add Button Doesn't Work
I new in Django and in web development. I follow this tutorial https://engineertodeveloper.com/dynamic-formsets-with-django/ to implement a dynamic formset in my Django project. I don't know to much about Javascript yet, so can anyone help me? I wrote the same javascript code in my Django app and my template is very similar with the tutorial's template, I used the same id to identify the HTML tags, but the "Add Another Image" button isn't working for me. When a click on it, nothing happens, on the other hand, the "Delete" button is working fine. My main form and my formset are different than the tutorial's mainform and formset. My form and my formset have three fields each. Javascript by: https://engineertodeveloper.com/dynamic-formsets-with-django/ const imageForm = document.getElementsByClassName("image-form"); const mainForm = document.querySelector("#pet_form"); const addImageFormBtn = document.querySelector("#add-image-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_form-TOTAL_FORMS"); let formCount = imageForm.length - 1; function updateForms() { let count = 0; for (let form of imageForm) { const formRegex = RegExp(`form-(\\d){1}-`, 'g'); form.innerHTML = form.innerHTML.replace(formRegex, `form-${count++}-`) } } addImageFormBtn.addEventListener("click", function (event) { event.preventDefault(); const newImageForm = imageForm[0].cloneNode(true); const formRegex = RegExp(`form-(\\d){1}-`, 'g'); formCount++; newImageForm.innerHTML = newImageForm.innerHTML.replace(formRegex, `form-${formCount}-`); mainForm.insertBefore(newImageForm, submitFormBtn); totalForms.setAttribute('value', `${formCount + 1}`); }); mainForm.addEventListener("click", function (event) { if (event.target.classList.contains("delete-image-form")) … -
TypeError: __str__ returned non-string (type NoneType) in Django
I am pulling data with where conditions and trying to print the object but it's throwing error TypeError: __str__ returned non-string (type NoneType) in Django help me with this error as I am learning Django This is my function def example_view(request): if request.method == 'POST': abc = request.data.get('abc') xyz = request.data.get('xyz') for obj in User.objects.raw('select * from public."Example_App_user" where abc = %s and xyz = %s',[abc,xyz]): print(obj) -
I am getting user data which I need to manually validate and then send it to a django model to save in the database after manual validation
i am getting user data from a Django form which i need to validate manually and then save it to django model database, the problem is that validation might take 24-48 hours. How do i hold the data temporarily so that when validated that data can be sent to the database using django models automatically, is there any functionality in django which will allow me to do that, if not how to do it. -
Nuxt middleware - user is not authenticated with Django backend
I created a Nuxt frontend that uses Django for everything authentication related. I'm using the standard Django Session Authentication system, but i'm having a problem. I created a middleware that checks if the user is authenticated. In order to check if the user is authenticated, it sends a GET request to an API endpoint in my Django backend, and Django checks if the user is authenticated. Here is the code for the middleware: export default function (context) { return axios.get('http://127.0.0.1:8000/api/check') .then(response => { console.log(response.data['state']) }) } And here is the Django code: @csrf_exempt def check(request): response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) The problem with my code is that when i'm authenticated, this code returns False when the request is sent from the middleware, which means that according to Django i'm not authenticated. But if i send the same request after the page is loaded, Django will return True, so the user is authenticated. Why is that? Does it have anything to do with the SessionID cookie that Django sets? -
changes in models.py not reflecting on website even after running successful makemigrations and migrate commands
my models.py looks like this from django.db import models from django.urls import reverse class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Sterilisation', 'Sterilisation'), ('Cleaning Chemistry', 'Cleaning Chemistry'), ('Bacterial Barrier', 'Bacterial Barrier'), ('Waste Management', 'Waste Management'), ('Instrument Tracking', 'Instrument Tracking'), ('Validation', 'Validation') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name i changed the spelling of Sterilisation to Sterilization (replacing the 's' with 'z') i ran python manage.py makemigrations and it returned Migrations for 'website': website/migrations/0003_auto_20210407_1842.py - Alter field prod_category on product i then ran python manage.py migrate and it returned Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, website Running migrations: Applying website.0003_auto_20210407_1842... OK but i dont see the changes reflected on the website. the spelling still remains to be Sterilisation! What can be the reason for this? PS: I am using sqlite3 and the website is on Ubuntu 20.04x64 which is a VPS. -
Does Django ORM implement Builder pattern?
I'm not sure but it seems that Django ORM implements Builder pattern, right? Example of query making: Entry.objects \ .filter(headline__startswith='What') \ .exclude(pub_date__gte=datetime.date.today()) \ .filter(pub_date__gte=datetime.date(2005, 1, 30)) -
Django Filter Issue Many to Many
I am having a problem where my chained filter using many to many lookups are not performing as I expected. Here are the pertinent details: views.py def cs_edit_result(request, ctype=None, survey_id=None): #if POST request resume answering survey answers from a selected customer survey. if request.method == 'GET': sid = Survey.objects.get(pk=survey_id) if request.method == 'POST': sid = Survey.objects.get(pk=survey_id) form = CustomerSurveyForm(request.POST, instance=sid) #filter placeholders to only form data from customer survey: if form.is_valid(): cs_result = form.save() answers = SurveyAnswers.objects.filter(surveyid=sid.id) for x in answers: x.status=False x.save() print(form) citype = form.cleaned_data['institution_type'] cproducts = form.cleaned_data['products'] cpurchases = form.cleaned_data['purchase'] cservices = form.cleaned_data['services'] colb = form.cleaned_data['olb_vendor'] cph1 = SurveyAnswers.objects.filter(surveyid=cs_result).filter( Q(placeholder__purchase__in=cpurchases), Q(placeholder__institution_type__in=citype), Q(placeholder__olb_vendor__in=colb), models.py class PlaceHolder(models.Model): output_choices = [ ('link','Link'), ('plain text', 'Plain Text'), ('html', 'HTML') ] purchase = models.ManyToManyField(Purchase, related_name='purchase_place') institution_type = models.ManyToManyField(InstitutionType, related_name='itype_place') products = models.ManyToManyField(Product,blank=True, related_name='products_place') services = models.ManyToManyField(Service,blank=True, related_name='services_place') olb_vendor = models.ManyToManyField(OLB_Vendor,blank=True, related_name='olb_place') output_type = models.ManyToManyField(Output_Type) question = models.TextField(null=True, verbose_name = 'question/title') silvercloud_placeholder = models.CharField(max_length=50) output_type = models.CharField( max_length=100, choices= output_choices, default='Plain Text') answer = models.TextField(blank=True,null=True, verbose_name='url/answer') def __str__(self): return self.silvercloud_placeholder class Survey(models.Model): customer = models.CharField(max_length=50) purchase = models.ManyToManyField(Purchase) institution_type = models.ManyToManyField(InstitutionType) products = models.ManyToManyField(Product) services = models.ManyToManyField(Service,blank=True) olb_vendor = models.ManyToManyField(OLB_Vendor) def __str__(self): return ('{} Survey {}'.format(self.customer, str(self.id))) class SurveyAnswers(models.Model): #contributor = admin. surveyid … -
Django UniqueConstraint to check if value is unique in model property
I have two models: Header and TroopsType, which is used in OneToOneField in Header. What I am trying to achieve is to check if Header's name is unique, but not only in Header's name field, but also in TroopsType's one. That's because if you choose some value in troops_type, then name field is not required and it should, so to speak, inherit that name from TroopsType object to not duplicate values by copying it. Of course, if you keep troops_type NULL, then Header's name is required. How would you do so? To clearify my train of thought, I attach my current code which I am trying to modify - currently I just copy the name. models.py: class TroopsType(models.Model): name = models.CharField(max_length=32, unique=True) unit = models.ForeignKey(Unit, on_delete=models.RESTRICT) def __str__(self): return self.name class Header(models.Model): name = models.CharField(max_length=32, blank=True, unique=True) troops_type = models.OneToOneField( TroopsType, on_delete=models.CASCADE, blank=True, null=True ) data_type = models.ManyToManyField(DataType) class Meta: constraints = [ models.CheckConstraint( check=(~models.Q(name="")), name="%(app_label)s_%(class)s_required_name", ), ] def __str__(self): return self.name admin.py: class HeaderAdminForm(forms.ModelForm): class Meta: model = Header fields = "__all__" def clean(self): troops_type = self.cleaned_data["troops_type"] if troops_type: self.cleaned_data["name"] = troops_type.name elif not self.cleaned_data["name"]: raise forms.ValidationError("No name or troops type.") super().clean() @admin.register(Header) class HeaderAdmin(admin.ModelAdmin): form = HeaderAdminForm -
django-crispy-forms with jinja2 FormHelper support
This an expansion on an old question that does not fully answer my question (django crispy forms with jinja2). I am using django-crispy-forms with jinja2 and have already figured out how to get these two to work together using the answer provided in that link. What you lose when doing that is all support for FormHelper and Layout. Has anybody figured out a way to get this functionality with Jinja2? -
IntegrityError at /quizmaker/ (1048, "Column 'id_id' cannot be null")
I am trying to make quiz making application, since am new to django am unable to build the logic for saving foreign key field in database table. Someone please help me for the same. models.py In models.py , class quiztitle is for title of the quiz and id(foreign key,User model) of user who created that quiz. class question is for question along with 4 options and the correct answer. Quizid(foreign key,quiztitle model) and id(foreign key,User model) class answer is for the answer submitted by user who take the quiz. from django.db import models from django.contrib.auth.models import User class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] views.py from django.shortcuts import render,redirect,HttpResponseRedirect from .models import question ,quiztitle from django.contrib import messages from django.contrib.auth import …