Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set template variable <title> in Django?
I am very new to Django, trying to setup my first personal CMS website. Please apologize if it is obvious. I am transitioning from PHP, so it is little confusing at times. I would like to set the title of the website "Dashboard|MCA Portal". The sitename comes from MySQL Database MySQL query : select value from options where `param`='sitename' Any idea how to do it ? Thanks Kiran -
Typeerror: __init__() takes 1 positional argument but 2 were given. I have seen many solutions for this error but none of them match my case
I have seen many solutions for this error but none of them match my case. I know for sure that the init class is getting more than one parameter, but I don't know how to resolve this. My page has a form which is a dropdown menu. After seleecting a value from the dropdown a list of regions appear in the form of a list. When I click on a item from that list a graph should appear on the same page. So what i have done is, I have created a initial form (class MonthlySalesGraphs) which when filled will render the next page i.e. the view MonthlSalesGraphs_2 which is the same as MonthlySalesGraph but only difference is it displays graphs. But clearly this in not working as this error pops up. Traceback: Traceback (most recent call last): File "C:\Users\Test\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\Test\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Test\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Test\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Test\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\views\generic\base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "D:\hemanth\intern2\intern\sales\views.py", line 329, in get form … -
Create class based Celery task for reusable app in Django project
Creating function based task is quite clean for Django project. Just create tasks.py in django app and start writing task like this example which is taken from official celery documentation at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y But sometimes function based tasks are tightly coupled and not very reusable. So i wanted to create class based celery task which is documented in official site. After following https://github.com/celery/celery/issues/3874 I could create sample task but I am not sure if its proper way to create class based task. from __future__ import absolute_import, unicode_literals from celery import shared_task, Task import time from celery import current_app @shared_task def add(x, y): time.sleep(5) return x + y @shared_task def mul(x, y): return x * y # Sample class based task for testing class AnotherTask(current_app.Task): name = 'tasks.another_task' def __init__(self, x, y): self.x = x self.y = y def run(self): time.sleep(5) return self.x + self.y # We need to manually register this class based task current_app.tasks.register(AnotherTask(3, 4)) I am able to call this task but each call result value is same (workflow) alok@alok-MacBookAir:~/exp/expdjango/mysite$ ./manage.py shell Python 3.6.3 … -
Django logging does not write debug.log file issue
I just set up new server and while I'm checking it, I got 500 error. I expect that debug.log file has error message, However, when I check the file the file was empty. Nothing was written. So I changed the loggers settings may times, but still the file is empty and I can't fix the error because what is wrong with it... This is my views.py logger = logging.getLogger(__name__) put this line to do logging. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'simple': { 'format': '%(asctime)s %(filename)s:%(lineno)d %(message)s', } }, 'handlers': { 'file': { 'level': 'DEBUG', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/service/debug.log', 'formatter': 'simple', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, } } if DEBUG: del LOGGING['loggers']['django'] del LOGGING['handlers']['file'] if not os.path.exists('log'): os.makedirs('log') -
Django creating record into a model with multiple foreign key fields
So i basically have a model called Designations that derives foreign keys from 3 other models (curricula, role and staff) and i am trying to save a new record into the Designations model, the code below shows the Designations and Staffs model. class Designations(models.Model): designation_id = models.AutoField(primary_key=True) curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE) role = models.ForeignKey(Roles, on_delete=models.CASCADE) staff = models.ForeignKey(Staffs, on_delete=models.CASCADE) class Meta: db_table = "arc_designations" unique_together = ('curriculum', 'role', 'staff') verbose_name_plural = "Designations" ordering = ['designation_id'] def __str__(self): return '%s of %s %s (%s)' % (self.role.role_name, self.curriculum.course_period.course.course_abbreviation, self.curriculum.module_period.module.module_abbreviation, self.staff.staff_full_name) class Staffs(models.Model): staff_id = models.AutoField(primary_key=True) admission_number = models.CharField(max_length=5, unique=True, help_text="Enter 5 digits", validators=[numeric_only, MinLengthValidator(5)]) staff_full_name = models.CharField(max_length=70, help_text="Enter staff's full name", validators=[letters_only]) created_by = UserForeignKey(auto_user_add=True, editable=False, related_name="staff_created_by", db_column="created_by") created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_by = UserForeignKey(auto_user=True, editable=False, related_name="staff_updated_by", db_column="updated_by") updated_at = models.DateTimeField(auto_now=True, editable=False) roles = models.ManyToManyField(Roles, through='Designations') class Meta: db_table = "arc_staffs" verbose_name_plural = "Staffs" ordering = ['staff_id'] def __str__(self): return '%s (S%s)' % (self.staff_full_name, self.admission_number) I have made a forms.py to get the admission_number(field in Staffs model) class AssignRolesForm(forms.Form): admission_no = forms.CharField(max_length=40, widget=forms.TextInput( attrs={'class': 'form-control', 'aria-describedby': 'add-btn'})) heres my html: <form action="{% url 'setInstructor' %}" method="POST" role="form"> {% csrf_token %} <div class="form-group"> <div class="input-group"> {{ form.instructor }} <span class="input-group-btn"> <button type="submit" class="btn … -
Django url template with query parameters
I'm trying to pass query parameters via my view into a link, but it escapes me on how to actually achieve this in a good way. My template is as following: <a class="link-button" href="{% url 'videos:index' %}?tag={{ tag }}&page={{ next }}">Next</a> This returns what I want: http://127.0.0.1:8000/videos/?tag=1&page=2 While this works, it's quite fragile, does not handle None values and there must be a better way of doing this. I tried to pass this via the urltemplate tag but it did not seem to be what I was looking for since it requires url config changes for path: {% url 'videos:index' page=next tag=tag %} Is there an actual way of doing this or a template tag I can use to get the parameters? I tried searching for this but it gave me a lot of old results and more path urls, like: /videos/page-1/tag-1/ which I'm not looking for. I was hoping to do something like: <a href="{% url 'videos:index'}?{% params page=next tag=tag %}">Next</a> -
MultiValueDictKeyError on select field django GET
I'm trying to pass a select option value to views.py using GET however i'm getting MultiValueDictKeyError at /app/dashboard/ "'yearfilter'" HTML <select title="yearfilter" name="yearfilter" id="yearfilter" class="year"> <option value="2018">2018</option> <option value="2017">2017</option> <option value="2016">2016</option> <option value="2015">2015</option> </select> Views.py def dashboard(request): yearfilter=request.GET['yearfilter'] today = datetime.date.today() projects_count = Project.objects.filter(is_deleted=False,start_date__year=yearfilter).count() -
django 2.0 how to show the filtered list of products
I am new to python and django. I am trying to create a shopping site. I have a few categories and each category has subcategories. From the home page, when i click on a category, i want to see the subcategory related only to that category. Currently i am seeing a list of all subcategories (not just one category's subcategory but all the subcategories). Please guide me how to achieve this. My models.py is as follows: from django.db.models import CASCADE class Category(models.Model): image = models.ImageField(upload_to='images/', blank=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_absolute_url(self): return '/category/{slug}/'.format(slug=self.slug) def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategory', on_delete=CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name My admin.py is as follows: from django.contrib import admin from .models import Category, Subcategory admin.site.register(Category) class SubcategoryAdmin(admin.ModelAdmin): list_display = ['__str__', 'slug'] prepopulated_fields = {'slug':('name',)} class Meta: model = Subcategory admin.site.register(Subcategory, SubcategoryAdmin) My views.py is as follows: from django.views.generic import ListView from .models import Category, Subcategory class CategoryListView(ListView): queryset = Category.objects.all() template_name = 'category/home.html' class SubcategoryListView(ListView): … -
Django many-to-one related query with "and" condition
I have the following models struct: class Drive(models.Model): car_name = models.CharField(max_length=3,blank=True, null=True,choices=sp.CAR_NAMES ,help_text="The name of the car") class DataEntity(models.Model): parent_drive = models.ForeignKey(Drive,models.CASCADE) type = models.IntegerField(blank=True, null=True,choices=sp.DATA_ENTITY_TYPES, help_text="The Type of the data") And i'm trying to get all of the Drives that have DataEntity.type = 3 and DataEntity.type = 4 I tried to use the following: query_set = Q{(AND: ('dataentity__type', 3), ('dataentity__type', 4))} Drive.objects.filter(query_set).distinct() but i got empty list... I had a look on the sql statement: SELECT ••• FROM `drive` INNER JOIN `data_entity` ON (`drive`.`id` = `data_entity`.`parent_drive_id`) WHERE (`data_entity`.`type` = 3 AND `data_entity`.`type` = 4)) subquery The Django system put the condition inside the WHERE statement, and it cause the problem (there is no data DataEntity that contain the both types) How can i make the right queryset in reason to get Drives that contain DataEntity.type = 3 and DataEntity.type = 4 ? Thanks -
Django change automatic table name for models of existing Oracle DB
I am trying to more elegantly express my database tables in a Django instance connecting to an existing Oracle database. We have a large number of existing tables, which I would like to concisely express as Django models. Currently, I have an abstract base class, which all other models inherit from. For example, class PlatformTable(models.Model): id = models.IntegerField(primary_key=True) creation_date = models.DateTimeField() last_modified_date = models.DateTimeField() class Meta: abstract = True db_tablespace = 'platform' managed = False And then we have an actual Account inheriting from this abstract table. I generate the correct table name in the class Meta for Account. class Account(PlatformTable): ext_ref = models.CharField(max_length=40) class Meta(PlatformTable.Meta): db_table = table_name("Account") def table_name(name): """Will convert a CamelCase class name to CAMEL_CASE so we can use it for oracle table names.""" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) table_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper() return u'"{schema}"."{table_name}"'.format(schema=SCHEMA, table_name=table_name) Is there a way to change the abstract model to automatically generate the correct table name in the Meta when it's subclassed like this? Ideally my Account model would look like class Account(PlatformTable): ext_ref = models.CharField(max_length=40) So far I've found this, which is not a good solution, and this, which doesn't work. Is it possible to extend the database … -
Django: Mail not getting sent through view
I am trying to send my mail through django views but it is getting printed in console and I am not getting any mails in my mailbox, but when I tried through same settings from python shell I get the mail. Settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mygmailusername@gmail.com' EMAIL_HOST_PASSWORD = 'mygmailpassword' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = 'mygmailusername@gmail.com' views.py: def login_view(request): #print (request.user.is_authenticated()) title="Sign in" form=UserLoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username, password=password) subject='Test registration' message='New user registered.\n Welcome to DD.' from_email=settings.EMAIL_HOST_USER to_list=[user.email, settings.EMAIL_HOST_USER] send_mail(subject,message,from_email,to_list,fail_silently=True) login(request,user) # print (request.user.is_authenticated()) return redirect("/index") return render(request, "form.html", {"form": form, "title" : title}) Just for testing purposes I have kept it in login view. Thanks!!! -
Django form failing validation and .save(commit=False) crashes
I am trying to use ModelForms, but I really seem to be making a meal of it. The models are various subclasses from 'Answer.' class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class Meta: abstract = True ordering = ['user'] class Brainstorm(Answer): brain_bolt = models.CharField(max_length=200, default="") responds_to = models.ForeignKey('self', models.SET_NULL, blank=True, null=True) class Meta: ordering = ['-pk', ] The ModelForms all follow this pattern: class BrainstormForm(ModelForm): class Meta: model = Brainstorm fields = '__all__' There are three possible patterns for Answers defined in the Question model: MULTIPLE_ENTRY_OPTIONS = ( ('S', 'Single Entry'), # single pk. User changes are final. ('T', 'Change-Tracked Single Entry'), # multiple-pks, but only the most recent is presented to the user ('M', 'Many answer instances are valid'), # question requires many answers - suitable for brainstorming ) A page may have multiple questions of different answer types and hence different forms, so rather than use a formset, I differentiate them individually with a prefix string of the question primary key and the answer primary key, which can then be unpacked again to get the question and Answer objects. I have two function-based views for each page: page_view (responds to get) and answer (responds … -
`psycopg2` is installed in `Django Virtualenv` but still showing error
PSYCOPG2 is installed in my virtualenv but still its showing error that no module named psycopg2 (blog_env) PS D:\django\blog_env\mysite> pip install psycopg2 Requirement already satisfied: psycopg2 in d:\django\blog_env\lib\site-packages (2.7.5) But still showing this Trace_Back Error when i run my project C:\Users\HP\AppData\Local\Programs\Python\Python36\python.exe D:/Django/blog_env/mysite/populate.py D:\Django\blog_env\mysite Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\postgresql\base.py", line 20, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/Django/blog_env/mysite/populate.py", line 5, in <module> django.setup() File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\options.py", line 205, in … -
Django makemessages doesn't collect javascript string inside of template
The current Django project where this problem occurs uses Internationalization and translation in several ways: In template files, translation of content text In Javascript files located inside the static directory In Javascript functions defined inside of template files Currently 1 and 2 are working fine without any problems. Running Django-admin makemessages -l en generates translations for the template contents and Django-admin makemessages -l en -d djangojs generates translations for strings located in the static javascript files. I'm currently struggling with number 3 and have not yet been able to find any documentation that directly addresses this use case. What currently happens is that when I run either of the makemessages commands Django does not find the new strings, when I manually add them to my translation files the translation does work just fine thereafter until I run makemessages again. Why is makemessages not detecting these translations strings and how can I get it to do so? urls.py: path('i18n/', include('django.conf.urls.i18n')), path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), snippet from dashboard.html: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> <!-- some HTML content here --> <script> <!--Intro JS--> function startIntro(){ var intro = introJs(); intro.setOptions({ showProgress: true, showBullets: false, doneLabel: gettext('intro_done'), steps: [ { intro: gettext("intro_dashboard_01") }, { … -
How to create django model dependencies ?
I'm creating a django rest api for wiki application, for now i'm thinking of creation of 3 models: 1. MainCategory -> Linux or Windows 2. SubCategory for each operation system with list of categories 3. WikiContent for each SubCategory My problem that i don't know how to do in the right way because I want that for each category I will see only categories that depends on and not all the categories and WikiContent will see depends on which category the user chose . Thanks for help. -
How to connect all related DB with FK in Django?
I got problem in making Queries. In the shell I all the time faced 'user' has no split error. and want to know how to make query about those models. select i.id, i.name, i.email, i.memo, g.id, g.name, i.birthday, i.regdt, n.number, t.name, t.id from webcontact_info as i inner join webcontact_number as n on i.id = n.info_id inner join webcontact_group as g on i.group_id = g.id inner join webcontact_type as t on n.type_id = t.id; this query in mysql. how can i change into query for Django? please help me about this. those are models.py class Group(models.Model): name = models.CharField(max_length=20) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Type(models.Model) : name = models.CharField(max_length=20) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Info(models.Model): name = models.CharField(max_length=20) email = models.EmailField(null=True, blank=True, unique=True) memo = models.CharField(max_length=200, null=True) birthday = models.CharField(max_length=12,null=True, blank=True) group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) regdt = models.DateTimeField(auto_now_add=True) updatedt = models.DateTimeField(auto_now_add=True) class Number(models.Model): number = models.CharField(max_length=11) info = models.ForeignKey(Info, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) regdt = models.DateTimeField(auto_now_add=True) updatedt = models.DateTimeField(auto_now_add=True) -
django formset within a form / dynamic arrays within forms
I have a platform with completely different json configs. Any user can create a new json config that is completely different. Hence I cannot model this staticly. I am trying to make a dynamic form for these json configs. Some of the json configs have array of values or objects. Visually, I will need these to be a list of inputs with an 'add more' button. I see that formsets are the generally accepted way to add arrays of values in django forms. (I'm already using mysql so I can't switch to postgres ArrayField). However from django examples, multiple formsets are initialized separately and passed into the view. Since my configs are dynamic, I don't know what formsets to initialize and further, the order of fields intermingle between formsets and the form. For example I am following this link and creating my form classes dynamically like so: class FieldHandler(): formfields = {} def __init__(self, fields): for field in fields: options = self.get_options(field) f = getattr(self, "create_field_for_" + field['type'])(field, options) self.formfields[field['name']] = f def get_options(self, field): options = {} options['label'] = field['name'] options['help_text'] = field.get("help_text", None) options['required'] = bool(field.get("required", 0)) return options def create_field_for_text(self, field, options): options['max_length'] = int(field.get("max_length", "20")) return … -
Retrieve image with Django Rest
I'm a newbie in Django, and I want to ask how to fetch images with Rest Api for Django. Currently I have a model with an ImageField and I have no trouble uploading images, or fetching the json for my item but when it comes to fetching it I don't have any clue how. I save the images in src\image\ inside the django app root folder. How do i fetch the image with an url like: localhost:8080/src/image/image1.jpg? -
Django: Passing url slugs to formset queryset
I am trying to change the queryset of my formset with this 'alternative approach': Alternatively, you can create a subclass that sets self.queryset in init: from django.forms import BaseModelFormSet from myapp.models import Author class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Author.objects.filter(name__startswith='O') Now my problem is, that I have to pass variables into this queryset. Therefore I tried to adjust BaseAuthorFormSet in my forms.py like that: class BaseAssignAttendeeFormSet(BaseModelFormSet): def __init__(self, order_reference, access_key, *args, **kwargs): self.queryset = Attendee.objects.filter( order__order_reference=order_reference, order__access_key=access_key, ) My function-based-view in views.py starts like that: def assign_attendee(request, order_reference, access_key): order_reference and access_key are slugs that come from the url. Anyone knows the way to pass these two to my queryset? -
Django template tag slice not working for form slicing
What's wrong with this code? I am trying to slice this but it's not working. Django version 2.x and Python version 3.5 <form method="POST" action="{% url 'boats:list-first' %}"> {% csrf_token %} {% for field in form|slice:":3" %} <tr> <td> {{fields.label_tag }} </td> <td>{{field}}</td> </tr> {% endfor %} <input type="submit" value="Submit"/> </form> -
Celery Flower UI is up but can't click on worker subtabs
I have a DJANGO>RabbitMQ>Celery site. The app runs, exept for the flower module. I can see the workers, I can see tasks arriving, but I tasks stay as 'STARTED' even after the tasks are completed (I receive emails after completion). The Monitor tab displays empty charts. When I click into a worker, I get stuck in the 'Poo' subtab. I cant browse any of the subtabs (Broker, Queues, Tasks, Limits, Config, System). I'm not too sure where to begin troubleshooting. I have a vagrantbox and Flower runs flawlesly in there. -
What does high level framework means? [django]
Django is a high-level web framework, what does 'high-level' means here? -
django.db.utils.IntegrityError: NOT NULL constraint failed: polls_article.reporter_id
I'm following Django's official documentation for Many-to-one relationships. Create a new article, and add it to the article set: >>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=date(2006, 1, 17)) models.py include: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) but when I tried to execute I got error message: django.db.utils.IntegrityError: NOT NULL constraint failed: polls_article.reporter_id traceback: >>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) Traceback (most recent call last): File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: polls_article.reporter_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/student/PycharmProjects/DjangoGetStarted/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, … -
ValueError at /account/custreg/ invalid literal for int() with base 10: ''
I see this error when I try to register in my django project. However, the User gets registered. Here is the screenshot of the error i am having -
Django when i create one user, one database created
I often look for answers on this website,this time my question was not answered. I have a question: when i create one user in web font end,i want to create a database at this point. the database name according to username. I didn't find the first pass.who can give me a reference example.thanks a lot.