Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throws a Foreign Key IntegrityError with a valid ForeignKey
I am creating a project in Django for a multiplayer battleship game, I am trying to set up my database so I can record games, players and user actions, here is the app/model.py code from django.db import models # Create your models here. class Player(models.Model): username = models.CharField(max_length=10,primary_key=True) password = models.CharField(max_length=10) class GameBoard(models.Model): size = models.IntegerField(default=10) state = models.CharField(max_length=500,default='') class Game(models.Model): game_id = models.AutoField(primary_key=True) player1 = models.ForeignKey(Player,related_name='player1',blank = True,null=True,on_delete=models.SET_NULL) player2 = models.ForeignKey(Player,related_name='player2',blank = True,null=True,on_delete=models.SET_NULL) board = models.ForeignKey(GameBoard,related_name='game_board',on_delete=models.CASCADE) def __str__(self): return f'Game: {self.game_id}, player1: {self.player1}, player2: {self.player2}, board {self.board}' class Action(models.Model): GAME_ACTIONS = ( ('a', 'Attack'), ('s', 'Surrender'), ) player_action = models.ForeignKey(Player,related_name='player_action',null=True,on_delete=models.SET_NULL) action = models.CharField(max_length=3, choices=GAME_ACTIONS) game = models.ForeignKey(Game,related_name='played_in',on_delete=models.CASCADE) Then I run makemigrations and migrate to update the database. Finally I try to test the code by using manage.py shell: from battleship.models import * p1 = Player1('Alice','password1') p2.save() p2 = Player1('Bob','password') p1.save() b = GameBoard() b.save() g = Game(player1 = p1,player2 = p2,board = b) g.save() When I run this code I receive the following error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I also tried to save a game with no players: g = Game(player1 = None,player2 = None,board = b) g.save() The previous code is able to execute without error, I … -
Which one is the best between deploying django drf and reactjs on the same server and domain or seperate
I am planning to have a website and mobile app which i want to develop it in django DRF for backend and frontend in reactjs with firebase for realtime notification on mobile and chatting. The mobile app is going to be webview base on the react webapp which i plan to deploy the frontend separately i.e mobile.xxxx.com, but web part will be with django, the question is that is their any implication to this or i should host my frontend for both mobile and web separately and just create a sub domain like api.xxxx.com which will do the serving. I am a startup entrepreneur trying to deploy something for public use, and am using Linode cloud $5 for a start. please what is the best practice. Thank you all -
'User' object has no attribute 'notifications'
Can anyone explain why I got this error: 'User' object has no attribute 'notifications' I have new model Notification and write in file context_processors.py next one: def notifications(request): if request.user.is_authenticated: count = request.user.notifications.filter(is_viewed=False).count() return { 'notifications_count': count } else: return dict() def notify(request): if request.user.is_authenticated: notifications = Notification.objects.all() return { 'notifications': notifications } else: return dict() My model Notification in the same app that is a User and my models looks like this: class User(AbstractUser): class Roles(models.IntegerChoices): ...... class Notification(models.Model): user = models.ForeignKey('User', models.CASCADE) message = models.TextField('Message', max_length=250, default=None) is_viewed = models.BooleanField('Seen', default=False) created_at = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f"{self.message}" class Meta: verbose_name = 'MSG' verbose_name_plural = 'MSG' ordering = ['-created_at',] Please help me to unserstand what is the problem with User object in context_processors.py -
How Should I Login Admin With Email And Password Where as User With Phone Number
Model.py class User(AbstractBaseUser): user_id = models.AutoField(primary_key=True) phone_regex = RegexValidator( regex =r'^\+?1?\d{9,14}$', message ="Phone number must be entered in the format: '+999999999'. Up to 14 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=17, unique=True, null=True) name = models.CharField(max_length = 20, blank = True, null = False) first_login = models.BooleanField(default=False) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] if i change my USERNAME_FIELD = 'email'. i get error because i am not taking email from the user. suggest me the solution. thank you in advance. -
User field is getting changed to Null everytime I update the form
Everytime I select a complaint and edit it, the user field in the admin panel changes to Null "----" Can someone please give me a solution for this. Because of this whenever I go back to the my-history page I can't see the edited complaints views.py: class EditComplaint(UpdateView): model = Complaint form_class = ComplaintForm template_name = 'newcomplaint.html' success_url = '/My-History/' def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( user=self.request.user ) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': … -
How can I create a complete video tube site using Django?
I would like to create a video tube site like YouTube using the Django framework. I read about the VideoJS plugin. It works fine. But, I'm not able to add an option to select the video quality. Can you give me some references where I can find more information about creating a complete video site using Django? -
How to use logging for print statements inside a python package?
I am working on a Django project which uses some packages that print statements out to the console (some of these packages are by made me). These print statements represent important info and cannot be removed just by commenting out the prints. Can someone guide me as to how to redirect such print statements to a logger? Also what would be the best practice for printing stuff to console while developing a package? -
How can i get list of Django ManyToManyField like this?
msgs <QuerySet [<Msg: home : Dusra msg from admin>, <Msg: home : good>, <Msg: home : k>, <Msg: home : k>, <Msg: home : hi>, <Msg: home : Yello>, <Msg: home : Good>, <Msg: home : lets se>]> msgs.values('content','likes') # likes is a ManyToManyField <QuerySet [{'content': 'Dusra msg from admin', 'likes': UUID('472ab5e5-ddda-4d18-b229-67f7d0f3d7fb')}, {'content': 'Dusra msg from admin', 'likes': UUID('8bbb16f2-11a7-4d52-818b-acbdcf518810')}, {'content': 'Dusra msg from admin', 'likes': UUID('d1499fb6-4fd6-4ec1-abda-a507c1339d93')}, {'content': 'good', 'likes': None}, {'content': 'k', 'likes': None}, {'content': 'k', 'likes': UUID('36d0c720-9169-4d66-8afa-2ff2ffb30166')}, {'content': 'hi', 'likes': None}, {'content': 'Yello', 'likes': None}, {'content': 'Good', 'likes': None}, {'content': 'lets se', 'likes': UUID('36d0c720-9169-4d66-8afa-2ff2ffb30166')}, {'content': 'lets se', 'likes': UUID('68f85e0c-fda1-4856-894c-b9c52fda5669')}, {'content': 'lets se', 'likes': UUID('d1499fb6-4fd6-4ec1-abda-a507c1339d93')}]> I want to convert above output to like below one <QuerySet [{'content': 'Dusra msg from admin', 'likes': ['472ab5e5-ddda-4d18-b229-67f7d0f3d7fb', '8bbb16f2-11a7-4d52-818b-acbdcf518810', 'd1499fb6-4fd6-4ec1-abda-a507c1339d93')}, {'content': 'good', 'likes': None}]} -
Invalid block tag 'endwith' Django
I have a Django template which is quite minimal but still throws an error at me, here it is : {% load static %} {% with somevar="somethingcool" %} {% extends 'myapp/ElementBase.html' %} # some html {% endwith %} I get the error "Invalid block tag on line 5: 'endwith'. Did you forget to register or load this tag? " which makes no sense to me. Any idea what i'm missing here ? -
How to improve unit test migration setup with Django?
I have created a Django project, which has more than 150 migration files. While running the unit tests, the setup itself is very much time consuming because Django first drops the database and creates a new test database and runs all migrations. I have tried using --keepdb flag, but with this approach the problem is that ensuring the base setup is clean is not guaranteed. One approach I can think of is using the --keepdb flag along with 2 additional steps- Before starting test, drop database, re-create from a database dump. Which will be way faster than running the migrations Run tests with --keepdb flag Is there any other approach we can take to reduce the total setup time? -
django migrate error raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError
I am a bit new to python and django Please adice me on how to resolve this issue in django after running python manage.py migrate /lib/python3.7/site-packages/django/db/migrations/graph.py", line 274, in ensure_not_cyclic raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: app_features.0001_initial, authtoken.0001_initial, authtoken.0002_auto_20160226_1747, authtoken.0003_tokenproxy my requirements.txt below Django==3.1.3 pytz==2021.1 sqlparse==0.4.1 dj-database-url==0.5.0 django-cors-headers==3.6.0 django-rest-swagger==2.2.0 djangorestframework==3.12.2 drf-yasg==1.20.0 gunicorn==19.9.0 ruamel.yaml==0.16.13 ruamel.yaml.clib==0.2.2 whitenoise==5.0.1 psycopg2-binary==2.8.6 django-hashid-field==3.2.1 requests even runserver is not working anymore Is there a conflicting field value in my models? Can someone please tell me what I have to do to fix this Thanks in advance -
Django postgres django.db.utils.OperationalError by running from Git Repo
I have pushed my Django Projekt with Postgres DB in GitHub and want to run it on a Windows Server. On the server Postgres was installed, in cloned Git Repo DB connection settings were adjusted. However, by running the django server it crashes with an error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError Postgres is running at the time, all libs are installed. My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Name', 'USER': 'User', 'PASSWORD': 'PW', 'HOST': 'localhost', 'PORT': '5432', } } On the server there is another Django Project connected to the same DB, but i have read that it should not be a problem to share the same User and DB between 2 projects. Maybe someone encountered the same problem? -
sorting of store goods
I'm using ListView in my Class Based Views and I want to sort the goods by the selected field by the user, but I couldn't find the information I needed view class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False def get_queryset(self): return Item.objects.all() def get_context_data(self, *, object_list=None, **kwargs): ***context*** return context def get_ordering(self): ordering = self.request.GET.get('orderby',) print(ordering) return ordering template <form action="{% url 'shop' %}" method="get" id="sortProduct"> <div class="product-sorting d-flex"> <p>Sort by:</p> <select type="submit" name="select"> <option type="submit" name="orderby" value="price">Price: $$ - $</option> <option type="submit" name="orderby" value="-price">Price: $ - $$</option> </select> <input type="submit" class="d-none" value=""> </div> </form> -
Django throwing error 404 while connecting with stripe webhook
Hey guys I am keep getting 404 error on while using Stripe webhook in my Django app. Really appreciate your help my urls.py urlpatterns = [path('my_webhook/', views.my_webhook, name='my_webhook')] views.py @csrf_exempt def my_webhook(request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except: return HttpResponse(status=400) if event.type == 'payment_intent.succeeded': payment_intent = event.data.object elif event.type == 'payment_method.attached': payment_method = event.data.object else: print('Unhandled event type {}'.format(event.type)) return HttpResponse(status=200) Error: [20/Jul/2021 14:28:36] "POST /my_webhook HTTP/1.1" 404 3816 Not Found: /my_webhook -
Django-Elasticsearch-Dsl does not create an index
I am working on a project and want to index an existing models.Model class to search for it. Here is my code of the corresponding Document class: @registry.register_document class LiteratureDocument(Document): class Index: # Name of the Elasticsearch index name = 'literature' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Paper # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'title', ] I then rebuilt the search index and started the elasticsearch server properly but it does not recognize my index. When searching for something, I get an index_not_found_exception. Thanks -
Dajngo Rest Framework how to set field to no required
I have this code and i want to set content field to be not required. type = serializers.ReadOnlyField(default=ComponentType.MediaComponent.value) content = ContentSerializer() class Meta: model = MediaComponent fields = ['id'] + ComponentSerializer.Meta.fields + ['type', 'content'] -
Django model form field initials not updating
Here my intention is to show pass the analysis_start_date value as year and month only(%Y-%m), below in my form class allowed_date_formats = [ '%m-%Y', '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%Y-%m' ] class PropertyForm(forms.ModelForm): analysis_start_date = forms.DateField( input_formats=allowed_date_formats, help_text="Choose the starting month", ) def __init__(self, *args, **kwargs): if self.instance: date = self.instance.analysis_start_date kwargs.update(initial={ 'analysis_start_date': date.strftime('%Y-%m') }) but in the but in the output form it shows date including the day, thanks in advance for any solutions :) -
How to make Django modifiy JSONField value effictively
With MySQL as database backend, I make Django ORM to update the following JSONField value { "01-task1": {"data":"huge data here"} } just add a new element , "02-testing": {} but I got the following sql log (0.000) UPDATE `by_jsontree_store1` SET `store_type` = 1, `user_id` = 2, `data` = '{\"01-task1\": {\"data\": \"huge data here\"}, \"02-testing\": {}}' WHERE `by_jsontree_store1`.`id` = 1; args=(1, 2, '{"01-task1": {"data": "huge data here"}, "02-testing": {}}', 1) It looks like Django rewrite the whole content of that JSONField. Imaging if the original content is huge, like 100MB, what could happen. Is there any trick could handle that effectively? -
KeyError at /admin/quiz/client/2/change/
I m getting this error when i m trying to change the model using Django Admin: "Key 'id' not found in 'ClientForm'. Choices are: denumire, email, is_active, is_client, is_staff, password, quizCompleted." ----- models.py ------ class CustomAccountManager(BaseUserManager): def create_superuser(self, email, denumire, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, denumire, password, **other_fields) def create_user(self, email, denumire, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, denumire=denumire, **other_fields) user.set_password(password) user.save() return user class Client(AbstractBaseUser, PermissionsMixin): denumire = models.CharField(max_length=300, default=' ', verbose_name='denumire') email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_client = models.BooleanField(default=False) quizCompleted = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['denumire'] def __str__(self): return self.denumire ----- admin.py ------ class UserAdminConfig(UserAdmin): model = Client search_fields = ('id','email', 'denumire', ) list_filter = ('id','email', 'denumire', 'is_active', 'is_staff', 'is_client', 'quizCompleted') ordering = ('-denumire',) list_display = ('email', 'denumire', 'is_active', 'is_staff', 'is_client', 'quizCompleted') fieldsets = ( (None, {'fields': ('id', 'email', 'denumire',)}), ('Permissions', {'fields': ('is_staff', 'is_active', 'is_client')}), ('Personal', {'fields': ('quizCompleted',)}), ) formfield_overrides = { models.TextField: {'widget': … -
What do I put in the success_url in my django view. Right now, this isn't saving the edited form nor redirecting the page
I don't know what to use or how to use the success_url in the django views. I tried reading online but did not understand, also tried doing a few things told by others but that is not working. I am pretty sure I am doing something wrong but I don't know what and how to solve it. views.py: class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint form_class = ComplaintForm template_name = 'newcomplaint.html' success_url = reverse_lazy('Complaint') def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( user=self.request.user ) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) urls.py: urlpatterns = [... path('Complaint/<int:pk>/edit/', accounts.views.EditComplaint.as_view(), name='Complaint') ] -
Format Column with Django-Tables2 based on another boolean column
I have a table whith a few columns amongst them one is called commune and has a string type and another is confiance_commune which is a boolean value. I would like commune to be rendered bold and green if confiance_commune is true. Here is my code : models.py class Mrae(models.Model): titre = models.TextField(blank=True, null=True) lien = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) type_projet = models.TextField(blank=True, null=True) pv_mentionne = models.BooleanField(blank=True, null=True) commune = models.TextField(blank=True, null=True) commune_m = models.TextField(blank=True, null=True) departement = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) confiance_commune = models.BooleanField(blank=True, null=True) index = models.AutoField(primary_key=True) class Meta: managed = False db_table = 'mrae' tables.py from django_tables2 import tables from django_tables2.columns import URLColumn from .models import Mrae class MraeTable(tables.Table): lien = URLColumn("Lien") class Meta: model = Mrae attrs = {"class": "table table-responsive"} fields = ['titre', 'lien', 'pv_mentionne', 'date', 'commune', 'departement'] tamplate_name = "django_tables2/bootstrap-responsive.html" -
Update the same template without refreshing from different views in Django
I am implementing a geospatial web app where everything is contained within one template in Django. At the moment I want to update a div in the template to display a Plotly graph, which is most easily created with Python and then passed to the template as a template variable. Is there a way I can update the variables returned, and then update the displayed template without refreshing, from a different view which renders the template initially? -
Style Form with django-filters
How can I modify the render of my form ? I followed the tutorial from django-tables2 considering table filtering. My actual code : filters.py import django_filters from .models import Mrae class MraeFilter(django_filters.FilterSet): titre = django_filters.CharFilter(lookup_expr='icontains', field_name='titre', label='Titre') annee = django_filters.NumberFilter(lookup_expr='year', field_name='date', label='Année') class Meta: model = Mrae fields = ['titre', 'pv_mentionne', 'date', 'date', 'commune', 'departement'] index.html <section class="container-fluid"> {% load render_table from django_tables2 %} {% load bootstrap4 %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='sr-only' %} {% bootstrap_button 'Filtrer' %} </form> {% endif %} {% render_table table 'django_tables2/bootstrap.html' %} </section> models.py class Mrae(models.Model): titre = models.TextField(blank=True, null=True) lien = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) type_projet = models.TextField(blank=True, null=True) pv_mentionne = models.BooleanField(blank=True, null=True) commune = models.TextField(blank=True, null=True) commune_m = models.TextField(blank=True, null=True) departement = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) confiance_commune = models.BooleanField(blank=True, null=True) index = models.AutoField(primary_key=True) class Meta: managed = False db_table = 'mrae' The Result : If I look at the resulting html, here is the code : <form class="form form-inline" action="" method="get"> <div class="form-group"> <label for="id_titre"> Titre </label> <input type="text" name="titre" class="form-control" placeholder="Titre" title="" id="id_titre"> </div> <div class="form-group"> <label for="id_pv_mentionne"> Pv mentionne </label> <select name="pv_mentionne" class="form-control" title="" id="id_pv_mentionne"> <option value="unknown" selected="">Inconnu</option> <option … -
Add links to non-model items in Django admin
I have a few utility tools within my existing Django app, eg. a view which allows Django admin users to send an email to users, or generate embed codes for external websites, etc. I want to add links to these tools to the Django admin index – what's the best way to go about this? I know I can override the admin index template and (presumably) manually add a list of URLs, but this doesn't feel very "Django". The URLs for these utilities live in my app's urls.py – should I try extracting them out into their own app somehow? I really just want to add a box like the one shown here, which links to three or four URLs – there must be a way! -
Django makemigration breaks when model query is run in form - Why?
I am using Django 3.2 I want to populate a form select field as follows: from .models import Post, BlogPostSubscriber, PostCategory # This causes makemigrations to break !!! # categories = [x for x in PostCategory.objects.all().order_by('slug').values_list('name', 'name')] categories = [('',''),] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['category', 'title', 'content','tags'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control input'}), 'category': forms.Select(choices=categories, attrs={'class': 'form-control input'}), 'content': forms.Textarea(attrs={'class': 'form-control editable medium-editor-textarea'}), 'tags': forms.TextInput(attrs={'class': 'form-control input'}), } When I run python manage.py makemigrations, I get the following error: Relation blog_postcategory does not exist Why? and how do I fix this error?