Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get ride of this error, "Unknown column 'history_change_reason'"?
Hello stackoverflow community, I am running into this error when I try to write to my database. I can't seem to find column history_change_reason in my database through mysqlWorkbench. Anyone else dealt with this before? File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/base.py", line 822, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/base.py", line 861, in _do_insert using=using, raw=raw) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/query.py", line 920, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 963, in execute_sql cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/opt/anaconda3/envs/py2/lib/python2.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) OperationalError: (1054, "Unknown column 'history_change_reason' in 'field list'") -
How to get a information from a model in Django via it's user id in the url?
I'm trying to fetch the Player information that has a certain user_id directly in my url. I know I can get info by the Player id by simply passing a number, but how can I get the player based on its user_id? Is this possible? fetch(`http://localhost:8000/api/players/PASS_USER_ID_HERE_NOT_PLAYER_ID`) class Player(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) national_id = models.CharField(max_length=10, unique=True, blank=False) class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = '__all__' -
SEO and Django with title and description tags
I have a base.html for the base template for my files. Inside of it, I have tag where I define both title and description tags. I also have my home page that is home.html that doesn't need a specific title or description and the general one for the whole website would do. I also have detail.html which is the HTML that I use for every blog post where I am trying to improve SEO with using these tags <meta name="description" content="{{ blog.formatted_summary|striptags }}"> <title>{{ blog.title|safe }}</title> First off in HTML, it is not in the tag as it is already used. Secondly, I am basically defining both title and description twice and I can't think why that would be a good idea. How do I insert the title and description into the base.html so if it is a blog post that I can specify to take the body or the summary as a description without defining the properties again? -
passenger_wsgi.py error in apache django vps
I have am trying from last three days to configure simple django application on my vps using plesk with centos 8 , and its been very frustrated to do it. I am receiving passenger_wsgi.py error . I have followed this tutorial How to allow installing and install Django applications? and this How to set up Django Hosting on the latest Plesk Onyx both worked out in centos 7 but not in 8. This is my server logs 2020-10-22 17:35:17Error162.158.165.79500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 KApache access 2020-10-22 17:45:44Error162.158.166.232500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 K Apache access 2020-10-22 17:45:45Error162.158.166.154500GET / HTTP/1.0 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 4.53 Apache access Error ID: 6cd697b9 Details: Web application could not be started by the Phusion Passenger application server. Its because of internal server error but how to resolve this ? this is the passenger_wsgi.py file import sys, os ApplicationDirectory = 'tayyab' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) … -
How to show only 1 image from an image list/set on the homepage in django html homepage template?
I am trying to show only 1 image from a list of images on the homepage. I am using django and its template engine. I use a formset to upload images onto the database, now the problem is when I loop through the list in the homepage, it shows all the images, I want to show only the first image from the set in the homepage. How to implement that? This is the code I have. {% for image in post.postimage_set.all %} <img class="" style="content: center" height="300" width="300" src="{{ image.images.url }}" /> {% endfor %} Thank you! -
Access to M2M self 'through' object
Specifying a through='' model for django's ManyToManyField seems fairly straight-forward, however when setting to 'self', I'm not understanding how queries should realistically look. Say for example I have these models: class Person(models.Model): name = models.CharField(max_length=120) friends = models.ManyToManyField('self', through='Friendship') class Friendship(models.Model): person_one = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person_one_friendships") person_two = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person_two_friendships") date_created = models.DateTimeField(auto_now_add=True, blank=True) This becomes complicated because of fields person_one and person_two. When doing reverse lookups, I'd need to query against both fields for finding the friendship between two persons. Here's an example of where it should be really easy to retrieve the through object of Friendship between two persons, but instead I have to use Q() objects or use both reverse lookups: person = Person.objects.filter(name="Kevin").first() for friend in person.friends.all(): # Approach 1: Use Q() objects on Friendship model person_1_q = Q() person_1_q |= Q(person_one=person) person_1_q |= Q(person_two=person) person_2_q = Q() person_2_q |= Q(person_one=friend) person_2_q |= Q(person_two=friend) friendship = Friendship.objects.filter(person_1_q, person_2_q).first() # Approach 2: Use both reverse_lookups on Person object friendship = friend.person_one_friendships.filter(pk=person.pk).first() if not friendship: friendship = friend.person_two_friendships.filter(pk=person.pk).first() Both approaches seem like a lot more work than necessary. Am I overlooking something? -
How to get mongoDB data in Django when i insert the data from python
i was insert JSON file to MongoDB from python file And i want to read and create an Django API for the selected data i inserted. For example, i was insert 3 data from python (JSON) to mongoDB "person": { "name": "person1", "gender": "female", "phoneNum": [{ "phoneOp": "SIM_A", "phoneNum": "+658123321122" }, { "phoneOp": "SIM_B", "phoneNum": "+658123321122" }] } In Django, how can i read that all data and create API for the selected data ? for example : i want to create API to get only the person name and gender Really need your help, thank you for helping :) -
Django 2.2.9: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin
I'm working on a big project for which I need to breakdown my application into different maintainable modules and I keep getting this error whenever I'm doing imports across different modules of the application. django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin for now I have a module named asset_herarchi and another module name db_configurations In asset_herarchi I've the following two models: from db_configurations.models import TableDataReferenceConfiguration class Attribute(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) table_datareference_config = models.ForeignKey(TableDataReferenceConfiguration, related_name="data_reference_where_conditions", on_delete=models.CASCADE) class Unit(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=150, blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) formula = models.CharField(max_length=50, blank=True, null=True) In db_configurations I've got the following model. from asset_herarchi.models import Unit class TableDataReferenceConfiguration(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) table_name = models.CharField(max_length=100, null=False, blank=False, unique=False) result_column_name = models.CharField(max_length=100, null=False, blank=False, unique=False) unit_of_measure = models.ForeignKey(Unit, related_name="UOM_Table_Data_Reference_Configuration", on_delete=models.SET(None) ) behavior_rule = models.CharField(choices=Rule, null=False, blank=False, max_length=20) behavior_order_by = models.CharField(max_length=100, null=True, blank=True, unique=False) behavior_order_sorting = models.CharField(choices=Sorting, null=True, blank=True, max_length=20) As I've mentioned earlier I'm splitting the application into different modules for easy maintenance For some business logic requirements I need to import the Unit model into the db_configurations.model file to create a relationship with TableDataReferenceConfiguration and … -
Adding and removing friends with CustomUser model
now i have some troubles with launching add/remove views for my friends functional. Tha main error is 'WSGIRequest' object has no attribute 'CustomUser' I also have troubles with displaying a list of users on page. I am sure that problem is in using custom user model, but I couldn`t find the appropriate solution for it. These are always error strings: Friends.make_friend(request.CustomUser, new_friend) Friends.make_friend(request.CustomUser, new_friend) Here`s my code: views.py: def change_friends(request, operation, pk): new_friend = CustomUser.objects.get(pk=pk) if operation == 'add': Friends.make_friend(request.CustomUser, new_friend) elif operation == 'remove': Friends.lose_friend(request.User, new_friend) return redirect('posts:all') models.py: from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): class Gender(models.TextChoices): MALE = 'MR', _('Mister') FEMALE = 'MS', _('Misis') class AvatarType(models.TextChoices): WARRIOR = 'WR', _('Warrior') ELF = 'EL', _('Elf') GUARDIAN = 'GD', _('Guardian') HEALER = 'HL', _('Healer') SNIPER = 'SR', _('Sniper') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) position = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.MALE) avatar_type = models.CharField(max_length=2, choices=AvatarType.choices, default=AvatarType.ELF) email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Friends(models.Model): users = models.ManyToManyField(CustomUser, related_name = 'friend_set') current_user = models.ForeignKey(CustomUser, related_name = 'owner', null = True, on_delete = models.CASCADE) … -
Mac OS Django-admin startproject mysite receives syntax error
I'm trying to follow the tutorial on https://docs.djangoproject.com/en/3.1/intro/tutorial01/ and have made it to the step where you are supposed to run django-admin startproject mysite in the command line. I have tried running the followings: django-admin startproject mysite django-admin.py startproject mysite django-admin startproject.py mysite $ django-admin startproject mysite and $ django-admin.py startproject mysite and all of them receive SyntaxError: invalid syntax either with a ^ under the "t" in "startproject" or under the $ when I've tried that. I've searched through about ten different posts trying to figure out how to proceed, and none of the answers provided have worked for me. They all continue to receive SyntaxError: invalid syntax I would really appreciate any insight into why this is happening and how to fix it. -
How to write regular expression url for list parameter in django urls
We have a django function with name and the following parameters @api_view("GET", "POST") def data(request, process, wo=[]): pass where process is interger and wo is list of integers and my django url path is something like this re_path(r"^wo_pai/(?P<process>[\d]+)/(?P<wo>[\d]+)", data), How can i modify the url in such a way that it will accept the list -
Pattern where python django view would respond back with 'Task still running' if the task take longer than a specified time
This is not about async or long-running job that can be run through Celery. Not often, but a few times, some of our web requests take longer, and if the Django view is still processing, our gateway will return a time-out to the front-end. I am looking for any established pattern in django where we can return the response saying 'Task still running' (HTTP code 100 or 102) if it goes beyond a certain time, but the task/thread continues execution. This way, we can handle the UI in front-end through some messaging, instead of giving an API time-out experience returned by our gateway. I am not looking for polling or the API sending another response, it just returns 102 response, but let the actual task execution continue. -
Django users under admin model
My project has operators and users. i want to map the users to operator.when someone logs in from operator account he/she can see users mapped to his account. E.g. Operator A and Operator B 5 users where user 1,3,5 are linked with Operator A and rest users are linked with operator B. Now when operator A cheks his admin panel, users 1,3,5 data can be reflected in his admin panel. Same thing goes with operator B and users 2,4. Please help how i can design the model or any other technique to achieve the goal. Thanks in advance. -
Create a permission in Django that can be optionally applied to superusers
I want to create a permission (or something that achieves the same thing) that can be applied to all users optionally, including super users. I can create a custom permission very easily: ct = ContentType.objects.get_for_model(MyModel) Permission.objects.create( name='optional permission', codename='optional_permission, content_type=ct) However, this will always return True for superusers user.has_perm('my_app_label.optional_permission') My use-case is: I'd like to create a queryset manager function that only returns Draft articles for users in Groups that have optional_permission applied. I'd like superusers to be exempt from seeing these draft articles if they want. -
NOT NULL constraint failed: home_profile.user_id
I have written an extension of the Django auth.user model which adds middle_name and phone fields to the model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) middle_name = models.CharField(max_length=20, blank=True) phone = models.CharField(max_length=10, blank=True) def __str__(self): return(f'{self.user.username} profile') I am using the following forms to accept input from the user. class RegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username', 'password1', 'password2'] class ProfileForm(forms.ModelForm): phone = forms.CharField(max_length=10, min_length=10) middle_name = forms.CharField(max_length=20, required=True) class Meta: model = Profile fields = ['middle_name', 'phone'] The view for the register route is as follows: def register(request): if request.method == 'POST': user_form = RegistrationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data.get('username') user_form.save() profile_form.save() messages.success(request, f'Welcome { username }! Your account has been created. Sign in to continue.') return redirect('login') else: return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form }) else: user_form = RegistrationForm() profile_form = ProfileForm() return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form }) This is contents of the signals.py file from django.contrib.auth.models import User from django.db.models.signals import post_save 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 save_profile(sender, instance, **kwargs): instance.profile.save() The issue … -
Django cannot connect to mysql
So i put my django app and mysql inside docker container. Here is what i do Docker file FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app and here is my docker-compose-yml version: '3' services: db: image: mysql:latest ports: - "3306:3306" environment: - MYSQL_DATABASE=django_example - MYSQL_USER=root - MYSQL_PASSWORD=123456 - MYSQL_ROOT_PASSWORD=123456 volumes: - "./db:/var/lib/mysql" web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/app - /tmp/app/mysqld:/run/mysqld Then i run it with docker-compose up I get this error MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Here is my database setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_example', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '3306', } } My docker ps --all CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c61ac60bc037 mysql:latest "docker-entrypoint.s…" 2 minutes ago Up 34 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp py_rest_api_db_1 f00857755a46 py_rest_api_web "python manage.py ru…" 5 minutes ago Up 34 seconds 0.0.0.0:8000->8000/tcp py_rest_api_web_1 So how can i fix it ? did i miss something? -
Django Dependent/Chained Dropdown List - Select A Valid Choice Error
I have implemented a Dependent dropdown list within Django but when I try to submit the form I get the following error 'Select a valid choice. That choice is not one of the available choices.' I have spent a while looking on the web for the answer and have tried a few with little avail. From my understanding and reading, this is an error because I render the form with a queryset of none. Then I use ajax to fill in the options. Even though I have updated the dropdown list, the form validation is checking my submitted answer against a queryset of none - thus the error. So i'm hoping someone can help me to update the choices the form will accepted on form submission. views.py # stage6 is where I render my view and check validation def stage6(request): form_deal = DealForm(request.POST or None, prefix='inst') if form_deal.is_valid(): form_deal.save() messages.success(request, 'Deal added successfully.') form_deal = DealForm() context = { 'dform': form_deal, } return render(request, 'stages/stage6/stage6.html', context) # This is used for my ajax request def load_offers(request): property_process_id = request.GET.get('propertyprocess_link') offers = Offer.objects.filter(propertyprocess_link=property_process_id).order_by('id') return render(request, 'stages/stage6/offers_dropdown_list.html', {'offers': offers}) forms.py class DealForm(forms.ModelForm): deal_date = forms.CharField( label='', widget=forms.TextInput(attrs={'type': 'date'}) ) target_move_date = forms.CharField( … -
Django templates {% include %} fallback value
I'm trying to dynamically load a template like so: {% include 'some-folder/'|add:var|add:'.html' %} But these templates are not always present. So I would like to add a fallback value/default template to be loaded if one being requested is not found. Is this possible? If not (out-of-the-box), how can I write a custom templatetag that does so? -
How to get user information from database when the only thing in client browser is the AuthToken?
Building my first app with a real backend. In my app, when a user registers or logs in (with username and password), a token is saved to the cookies of their browser. After registration (or when logging in), I can easily return information pertaining to this particular user (name, id, etc.). # Django REST backend for loggin in and getting user token class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'user_type': user.user_type, }) Next time the user accesses the app in the same device, the token will be there and I can make the http requests for which a token is necessary. However, since I won't be logging the user in again (not asking for username and password every single session), I won't get that user's additional information. In my React app I would like to have the user set in state at all times, e.g. user = {first_name: 'john', user_type: 'p'} but I don't know how to get the user info when the only thing I have is their token. I am more than welcome to criticism to … -
How to redirect for last page visit DJANGO PYTHON
good evening! Hope everything is great! Well, I have a little problem with redirect in Django, I was trying to make a comment section for my web app but after "posting" the comment, I can only redirect the user to my homepage (through return redirect ('/') Models.py: class Task(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) responsable = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name="author", default=author) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','HR'),('L','Legal'),('F','Finances'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') is_public = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("task-detail", kwargs={"pk": self.pk}) class Comment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) body = models.TextField(help_text='Add a comment') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('-created',) def __str__(self): return '%s - %s' % (self.task.title, self.author) Views.py: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): form.instance.task_id = self.kwargs['pk'] form.instance.author = self.request.user form.instance.created = timezone.now() form.save() return redirect('/') urls.py from django.urls import path, include from . import views from .views import (DashboardTaskAppView, TaskDetailView, TaskCreateView, TaskUpdateView, DashboardTaskAppViewPublic, TaskDeleteView, CommentCreate) urlpatterns = [ … -
NameError: name 'Profile' is not defined
here is my models.py code. im trying to run the python3.8 manage.py migrate command to create the tables for the database but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Image(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null='True', blank=True) image = models.ImageField(upload_to = 'pics/') name = models.CharField(max_length=50,blank=True) caption = models.CharField(max_length=250, blank=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, ) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): comment = models.TextField() image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True ) name = models.CharField(max_length=100, blank=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True ) created = models.DateTimeField(auto_now_add=True, null=True) class Profile(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/', default='default.png') bio = models.TextField(max_length=500, default="My Bio", blank=True) followers = models.ManyToManyField(User, related_name="followers", blank=True) following = models.ManyToManyField(User, related_name="following", blank=True) -
How to set post_id to resolve error : 'django.db.utils.IntegrityError: NOT NULL constraint failed: posts_comment.post_id'?
Well I am using django and i am trying to add commenting with ajax. when i am clicking on the comment submit button that is performing no action but in the terminal it showing me 'django.db.utils.IntegrityError: NOT NULL constraint failed: posts_comment.post_id' error. I have double checked my models.py but still didn't get how to solve it. model.py class Comment(MPTTModel): author = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE, default=None, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') post = models.ForeignKey(Post ,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) view.py def single_post(request ,*args, **kwargs): slug=kwargs.get('slug') print(slug,'slug') pk=kwargs.get('pk') print(pk,'pk') post = get_object_or_404(Post,pk=pk,slug=slug) allcomments = post.comments.filter(status=True) comment_form = CommentForm() return render( request, 'posts/post_test.html', { 'post': post, 'comment_form': comment_form, 'allcomments': allcomments, } ) def addcomment(request): if request.method == 'POST': comment_form = CommentForm(request.POST) print(comment_form) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('body') user = request.user.username user_comment.author = request.user user_comment.save() return JsonResponse({'result2': result, 'user': user}) urls.py urlpatterns = [ path('test/<int:pk>/<str:slug>/',views.single_post,name ='post_detail'), path('commented/',views.addcomment,name='addcomment'), ] if more information is require than tell me in a comments session. I will update my question with that information. Thank you ! -
Form is always not valid/Cannot assign instance
I've been struggling with my issue for a while. It continues my previous question: How to handle data from two forms in one view? I figured out that the problem is in this form: class TranslatorChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(TranslatorChoice, self).__init__(*args, **kwargs) self.fields['owner'].queryset = Translator.objects.all().filter(owner = self.user_id) owner = forms.ModelChoiceField(queryset = None) class Meta: model = Translator fields = ('owner', ) Its' model: class Translator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='created_translators' ) def __str__(self): return str(self.user) And the view: def link_translator(request): if request.method == 'POST': form = TranslatorChoice(request.POST) if form.is_valid(): pass return redirect('dashboard') else: form = TranslatorChoice(user_id=request.user) With the code above the form gives me options to choose from but whenever I hit submit the form asks me to select a valid choice. However, if I change Translator.objects.all().filter(owner = self.user_id) to Translator.objects.all() form.is_valid() gives me true but another error appears: ValueError at /linkt/ Cannot assign "<Translator: rawkymonk>": "Translator.owner" must be a "User" instance. My guess that the main problem is ModelChoiceField so if there's an alternative to it please tell me. -
You have 29 unapplied migration(s). Your project may not work properly for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django
I wasn't sure how to set up Doccano on my computer to perform sequence labeling tasks so I followed the instructions from this website. While following the instructions and running the code on git bash, I encountered some errors. Could you please explain what these errors mean and how to rectify them? Thanks $ python manage.py createsuperuser (this is the error below after running this code on git bash) You have 29 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auth_user -
Django How to pass a checkbox value into a function
I have created a table in django, each rows has a id and a checkbox. I have assigned the value for each checkbox as the id of the row. When the user clicks on the checkbox I want it to call a function and pass in the id number as well as whether that checkbox is now checked. sets.html: <td class="text-center"> {% if set.status %} <input type="checkbox" checked name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'"> {% else %} <input type="checkbox" name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'"> {% endif %} </td> views.py def set_update(request): print(request.GET.getlist('inputs')) return redirect('dashboard:sets')