Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to I simply set a default url parameter in a django redirect?
So I have an app, that people login and it shows them a list of data. We recently made some filters and it would be nice if some of the filters were just on by default, which is simple in the code but I want the url to reflect the GET variables Im using for user sanity. So, I have this: #settings.py ACCOUNT_LOGIN_REDIRECT_URL = "status_dashboard" and #urls.py path( r"dashboard/?status=in_progress", DashboardView.as_view(), name="status_dashboard"), it would work but it escapes the ? in the url for safety, there must be a way to do this thats dead simple but I can only find things on passing POST variables to the view, which I dont need. -
Django Query / Template Language Confusion
I have an issue with my code and I am not sure why it works this way. I have a model which is an order, and then order item which is like a link in between the product and the order itself. The issue is I am creating a completed order page for my website in order for people to leave a review on a product. I originally used a get query and then was able to connect through to other tables with the template language object.items.all because I am using a many to many field. But with multiple things ordered my get query returns more than 1 object and an error is produced. To solve this I then tried to switch the query to .filter() but then I am unable to use object.items.all in the template and I am confused as to why? I will link the models and template. Sorry for this terrible explanation, I hope the models clear up any misunderstanding. Models class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) … -
Since i removed sessionid, django is not creating new one
While i was creating shopping cart which depends on sessionid included in cookie files I once removed sessionid in my browser to test something and then i realised that django don't want to recreate new one. I was looking for solution in internet but i didn't found any equal problem to my and solution to it. By looking on the django docs. i wrote to setting.py hoping that it would help: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True but still sessionid in cookies doesn't occur. I read post that sessionid should be generated by django while there is request which require sessionid, and it would be in my situation solution on this problem but in the context_processors.py I wrote that i require sessionid globally: def basket(request): try: customer = request.user.customer except: device = request.COOKIES['sessionid'] customer, created = Customer.objects.get_or_create(device=device) order, created = Order.objects.get_or_create( customer=customer, complete=False) return { 'order': order, } And beacouse of the context_processors sends request for sessionid and it can't get one, this error occurs: Any solutions? -
WTF is up with Django?
So my template is throwing this error:This is the error But I KNOW that the object exists. I check the one in question in the photo: This is the object it says is there It wont let me migrate because it thinks that there is a "Post" model with a null field it cant fix: Says the Post model field TAGS is there But I freaking deleted and still got the same thing. So I tried deleting the WHOLE post model and yet it thinks its still there: nope...not there. So it thinks something is gone that isnt and that something is there that is gone. WHAT THE FUUUUUUUUUUUUUUUCCKKK!!!?!?!?!?!?!?!?!??! -
filter to pagination django
implemented sorting and pagination on the product page, but sorting gets confused when moving to the next page. How do I apply a filter to all pagination pages?and i got smth weird with dropdown selection: after moving to next pages it starts act like crazy,after choosing a filter and refreshing the page, it returns to the default value and seems to be changing places (exmp: $$-$ -> $-$$ and vice versa , and i must guess who is who :) ) template <div class="product-sorting d-flex"> <p>Sort by:</p> <form name="selectForm" action="{% url 'shop' %}" method="get"> <label for="orderby"></label> <select name="orderby" id="orderby" onchange="selectForm.submit();"> <option value="price">price: $$ - $</option> <option value="-price">price: $ - $$</option> </select> <input type="submit" class="d-none" value="submit"> </form> </div> views class Shop(ListView): template_name = 'essense/shop.html' context_object_name = 'items' paginate_by = 9 allow_empty = False model = Item def get_context_data(self, *, object_list=None, **kwargs): ***context*** def get_ordering(self): return self.request.GET.get('orderby', ) -
Get separate serializer response for each nested serializer
Stuck with serializer where I need to have serialized response based on the nested serializer. Models.py : class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children') child_name = models.CharField(max_length=80) Serialziers.py class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class ParentSerializer(serializers.ModelSerializer): child = serializers.SerializerMethodField() def get_child(self, obj): childs = Child.objects.filter(parent=obj) return ChildSerializer(childs, many=True).data class Meta: model = Parent fields = '__all__' I am getting output like below where I am getting nested childs: { id : 1, name : "Parent1", child: [ 0: {id : 1, child_name : "child1"} 1: {id : 2, child_name : "child2"} ] } But for some business purpose I need output to be something like below, where serializer should be based on child. i.e. for each child there should be separate Parent serializer. Doesn't matter if it has same id and other fields. : { 0:{ id : 1, name : "Parent1", child: [ 0: {id : 1, child_name : "child1"} ] } 1:{ id : 1, name : "Parent1", child: [ 0: {id : 2, child_name : "child2"} ] } } Also please let me know if I can filter based on the child serializer. i.e. childs I will be passing … -
Not able to activate debug in VS-code for Django project (Django in virtual environment)
I have an issue running the Debug environment for Django application in VS-code: my python is not in the virtual environment, while my django is. Therefore, the solution I see everywhere with adding to the launch.json settings the line "pythonPath": "${workspaceRoot}/.venv/bin/python2.7", does not fit, and I end up having the following error: Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? When working on the application, I launch the setting environement using the following command: .\venv\Scripts\activate.ps1 Can anyone help me out to declare my virtual environment the proper way in the launch.json file? -
How to change serializer field name with python forbidden character
I need to have a serializer that returns data with illegal character inside dictionary key, what I would like is : class MyModel(models.Model): my_field = model.TextField() ... serializer = MySerializer(django_object) serializer.data # returns {'my-field' : "value"} I have tried using serializers.SerializerMethodField but target field name must be Python valid. class MySerializer(serializers.Serializer): my-field = serializers.SerializerMethodField(method_name="get_my_field") # ^ this fail to be interpreted by Python def get_my_field(self, obj): return obj.my_field using source as an argument to any Serializer fails for the same reason. -
Reverse for 'customer' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P<pk>[^/]+)/$']
I am getting this error when I'm trying to pass a dynamic URL in Django. please Help. dashboard.html {% for i in customers %} <tr> <td><a class="btn btn-sm btn-info" href="{% url 'customer' customer.id %}">View</a></td> <td>{{i.name}}</td> <td>{{i.phone}}</td> </tr> {% endfor %} urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk>/', views.customer, name="customer"), ] views.py def customer(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() total_order = orders.count() context = {'customer': customer, 'orders': orders, 'total_order':total_order} return render(request, 'accounts/customer.html', context) -
Djang select and delete posts
I am making a blog based on Django on guides. I have a list of posts that you can change and delete. How to make it possible to select multiple posts and delete? I don't even know which side to approach the problem. -
using `django-push-notifcations` package; How does `active` state change on the `push_notifications_gcmdevice` table.; getting sent messages count
I use django with the django-push-notifications package to send push notifications with the Legacy FCM. When sending push notifications, I would like to know which users did/didn't get the message. Due to the way my DB is built and the messaging logic I'm using, I can not just use the devices.send_message() func to send to all users at once. That would have been great, since I would get the success count in the HTTP Response like this: { "multicast_id": 108, "success": 1, "failure": 0, "results": [ { "message_id": "1:08" } ] } Instead I need to loop through a queryset of users and send each one separately, by calling device.send_message(). Now, I know I can save the response from each message and tally them with a counter of some sort, but that really won't work as I use a separate thread to deal with sending the messages, and waiting for thousands of messages to send is going to defeat the purpose of using a thread. Currently I use this code after sending the notifications to know how many were sent/not sent: all_users = queryset.count() active_fcm = GCMDevice.objects.filter(user_id__in=queryset.values_list('id', flat=True), active=True).count() return Response({ 'sent': active_fcm, 'not_sent': all_users - active_fcm }, status=status.HTTP_201_CREATED) I … -
Creating Relational database with user model in Django. I think i have created relational database but i don't know whats going wrong
I think i have successfully created relation between user model and another table called shop_details but the data is not been inserted. i don't know what is going wrong. the code is here. models.py from django.db import models from django.contrib.auth.models import User class Shop_Details(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) shop_name = models.CharField(max_length=50) shop_street = models.TextField() shop_area = models.TextField() city = models.CharField(max_length=50) state = models.CharField(max_length=50) pin_code = models.TextField() my views.py is here views.py def shop_detils(request): if request.method == "POST": shop_name = request.POST['shop_name'] shop_street = request.POST['shop_street'] shop_area = request.POST['shop_area'] city = request.POST['city'] state = request.POST['state'] pin_code = request.POST['pin_code'] if(len(str(pin_code))!=6): messages.info(request,"please provide a valid address pin-code") print("niceee...........................") return render(request,'shop_details.html') else: if(is_number(int(pin_code))): shop = Shop_Details(shop_name=shop_name,shop_street=shop_street,shop_area=shop_area,city=city,state=state,pin_code=pin_code,user=request.user) shop.save() messages.info(request,"Shop Details Updated") shop_data = Shop_Details.objects.filter(user = request.user) print(shop_data[1]) print("congrats...........................") return redirect('home',{'data':shop_data}) else: messages.info(request,"please provide a valid address") print("nice2222222222222222222222222") return render(request,'shop_details.html') else: return render(request,'shop_details.html') my shop_details.html is here shop_detsils.html enter code here {% extends 'layout.html' %} {% csrf_token %} {% if user.is_authenticated %} {% csrf_token %} {% load static %} {% csrf_token %} <meta name="viewport" content="width=device-width, initial-scale=1"> {% csrf_token %} <body align="center"> {% csrf_token %} {% csrf_token %} {% csrf_token %} {% block content %} <form action="shop_detils" method="POST"> {% csrf_token %} <div align="center" class='resp_code frms'> {% csrf_token %} <p … -
How to get data from the database and assign it to a serializer Django
I'm working on a django rest program. I have two apps, product and order. Now on the order app, i have two models, order and order unit. What I need to do is figure out a way that when I create an order and an order unit (they should be created together), I need to get the price from the product to display on the order unit when I choose the product there. So for example, I choose the product and I want the price of that product to be automatically filled in, hope I was clear enough. Now this is the code and what I've tried so far. Models of order: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits_orders', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField Serailizers: class OrderUnitSerializer(serializers.ModelSerializer): class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] class OrderSerializer(serializers.ModelSerializer): orderunits_orders = OrderUnitSerializer(many=True) class Meta: model = Order fields = [ 'id', 'code', 'code_year', 'date_registered', 'customer', 'creator', 'orderunits_orders' ] Views: class OrderListCreateAPIView(ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes … -
Can I include two different urls to the same url pattern? Example [ path('api/', include('quiz.urls')), path('api/', include('user.urls')) ]
127.0.0.1:8000/api/ Is containing only urls from the second app, but I linked both url modules to the same pattern. Is it even possible to do that? first app: from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', viewset=views.UserProfileViewSet) urlpatterns = [ path('', include(router.urls)) ] second app: from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'question', viewset=views.QuestionViewSet) router.register(r'review', viewset=views.ReviewViewSet, basename='review') urlpatterns = [ path('', include(router.urls)) ] main: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('quiz.urls')), path('api/', include('user.urls')) ] -
Django formset - validate_min=False being ignored
I'm pretty new here, this is my first question but hopefully someone will be able to help me. I've made a inlineformset in Django. I've set "min_num" at 6 with valide_min=False, but when I fill in less than 6 forms in the formset, the data is not inserted in the database, it seems like the formset.is_valid() is False. Can someone help me out? (filtered) code below. Thanks! views.py from django import forms from django.forms import inlineformset_factory from django.shortcuts import render, redirect from actie import Actie from inzetlijst import Inzetlijst from medewerker import Medewerker def index(request, actie_id): actie = Actie.objects.get(pk=actie_id) LanguageFormset = inlineformset_factory(Actie, Inzetlijst, fields=('taaknummer', 'voertuig', 'medewerker'), extra=2, can_delete_extra=False, min_num=6, validate_min=False) if request.method == 'POST': formset = LanguageFormset(request.POST, instance=actie) if formset.is_valid(): formset.save() return redirect('create_inzetlijst', actie_id=actie.id) formset = LanguageFormset(instance=actie) for form in formset: form.fields['voertuig'].empty_label = "" form.fields['medewerker'].queryset = Medewerker.objects.exclude(youforce=0).order_by('team', 'achternaam') form.fields['medewerker'].empty_label = "" try: form.fields['DELETE'].widget = forms.CheckboxInput() form.fields['DELETE'].label = 'Wissen' except: pass return render(request, 'odin/actie/inzetlijst_aanmaken_form.html', {'formset': formset}) template.html {% block content %} {% block content_form_title %} {% endblock content_form_title %} {{ form.non_field_errors }} <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset.forms %} <div class="row"> <div class="col s4 m2"> {{ form.taaknummer.errors }} <label for="id_taaknummer">{{ form.taaknummer.label }}</label> {{ … -
Django | Annotate objects to query
I am currently struggling to figure out how to deal with the following problem: Imagine I got this two models: class author(models.Model): name = models.CharField(mac_length=50) ... and class book(models.Model): author = models.ForeignKey('author', on_delete=models.CASCADE) ... Now I want to create a view which list all authors with all their book's. This could look something like this: Joanne K. Rowling: Harry Potter and the Philosopher's Stone ... J. R. R. Tolkien: The Hobbit ... Question: How should the Django Query look like to access the Books in the template? ` authors = authors.objects.all() This gives me the set for the authors, but not their belonging books. Is there a way to annotate or aggregate Dict's to the Queryset? I feel like this beeing Rookie stuff, but it would still be nice if you could help me out. -
DRF - how to pass a value to a serializer, omitting user's request body
Imagine we have such a simple model: class Tag(models.Model): owner = models.ForeignKey(to=User, on_delete=models.CASCADE) title = models.TextField() and a serializer for it: class TagSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( many=False, write_only=True, queryset=User.objects.all(), ) title = serializers.CharField() class Meta: model = Tag fields = ("owner", "title") validators = [ UniqueTogetherValidator( queryset=Tag.objects.all(), fields=["owner", "title"], message="", ) ] Well, the task sounds quite simple: how to pass the owner instance (or it's primarykey) from a view, but to keep the field invisible for a user? I mean, it hasn't be rendered by drf-yasg, and a user's request like {"owner": 1, "title": "cats"} must be discarded because of unknown field "owner". Is there only a single way - to pass the value via context, and then rewrite serializer's validate & update & create methods to support it? I hope you know better approaches. -
profiling clery tasks and functions in django
I'm working on a Django application with some algorithmic routines that I manage them using celery. I have a lot of DB queries in my algorithms and obviously, query optimization is really critical for performance. However, I can't find any packages for celery task profiling, just like Django debug toolbar or Django silk that works on HTTP requests. Is there a solution for investigating a particular function in my code (e.g logic())? I need some reports like execution time, similar or duplicate queries and etc. -
Django url can't work after i move it down from the list
I am making a blog app using Django. In my blog app, i have 6 paths. This is my app urls.py from . import views from .views import AddPostView from django.urls import path from .feeds import LatestPostsFeed urlpatterns = [ path('', views.PostList.as_view(), name='home'), # path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('upload/', views.image_upload_view, name="upload"), path('add_post/', AddPostView.as_view(), name='add_post'), path('<slug:slug>/', views.post_detail, name='post_detail'), path("feed/rss", LatestPostsFeed(), name="post_feed"), ] The app is working perfectly, but whenever i try to move the path('<slug:slug>/', views.post_detail, name='post_detail') up from the add_post url (code below) and try to open add_post from . import views from .views import AddPostView from django.urls import path from .feeds import LatestPostsFeed urlpatterns = [ path('', views.PostList.as_view(), name='home'), # path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('upload/', views.image_upload_view, name="upload"), path('<slug:slug>/', views.post_detail, name='post_detail'), path('add_post/', AddPostView.as_view(), name='add_post'), path("feed/rss", LatestPostsFeed(), name="post_feed"), ] suddenly i have an error saying : Page not found (404) No Post matches the given query. Request Method: GET Request URL: http://localhost:8000/add_post/ Raised by: blog.views.post_detail Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='home'] upload/ [name='upload'] <slug:slug>/ [name='post_detail'] The current path, add_post/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and … -
Django trailing slashes in urls are not working correctly
While testing my django app I'm receiving 302 status code instead of 200. In manual check I discovered that initially instead of slash at the end of url browser doesn't see it and redirects to url with trailing slash. Part of urls.py: path('add/', add_product, name='add_product') Function which tests it: def test_add_product_view_pass(self): user = User.objects.create_superuser(username='test_user', email='test_user_email@email.com') user.set_password('test') user.save() c = Client() response = c.post(reverse('log_in'), {'username': 'test_user', 'password': 'test'}) user = get_user(c) self.assertTrue(user.username, 'test_user') self.assertEqual(user.is_superuser, True) response = self.client.get(reverse('add_product')) self.assertEqual(response.status_code, 200) So basically I need to log superuser to have access to this part of app. There's form which allows to create model object. APPEND_SLASH is on default True setting. After running this test I'm getting AssertionError: 302 != 200. -
How do you handle database queries when you have millions of records
I am currently developing an application using Django. In my application, you have several users and each user has its own friends list. Now each user can add certain "events" (like going to the movies tonight). Now the friends of this user each have their own feed where that activity will now be displayed. Currently, all events are stored in a db table and they all have a field that keeps track of the user that created the event. Now a db query will be executed for each friend and it will check for all the events and will select those that are of friends. Although this works quite nicely on a small scale, it got me wondering how you would do something if you had for example 10 million users. 10 million users will each create multiple events, and for every user, you have to check all events to see if an event is made by a friend. I can imagine that your running time will reduce drastically. Similarly, what if you want to display all events to a user that are within a 10 km radius, and you have let's say 100 million events. You can't compare the … -
Django model trouble
Hello everyone, maybe someone has encountered such a problem. I'm trying to create a UserProfile model using a One-To-one relationship with the User table from django.contrib.auth.models. class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE), age = models.IntegerField(null=True, blank=True) status = models.TextField(null=True, blank=True) avatar = models.ImageField(null=True, blank=True) But when I create a migration the user field does not exist class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('age', models.IntegerField(blank=True, null=True)), ('status', models.TextField(blank=True, null=True)), ('avatar', models.ImageField(blank=True, null=True, upload_to='')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'Профиль пользователя', 'verbose_name_plural': 'Профиль пользователя', 'ordering': ['-created_at'], }, ), ] what am I doing wrong?) django version 3.2.4 thank you in advance) -
Django model translation strings containing accents are ignored
I'am building a simple web application using Django. I wanted to translate the site for three languages (EN, DE, HU). The texts on the page are stored in the database as I might want to change them later. I found a solution: Django model translation (https://django-modeltranslation.readthedocs.io/en/latest/). I followed the tutorial, and now it is working, but when I fill the hungarian text in the admin it shows the english text on the page. If I remove for example the letter 'ú' from the text it switches back to the hungarian. This is my model: class AboutUs(models.Model): main_text_heading = models.CharField(max_length=255, default='Trilogic Solutions') main_text = models.TextField(default=lorem) cloud_text_heading = models.CharField(max_length=255, default='Felhőalapú megoldások') cloud_text = models.TextField(default=lorem) web_app_text_heading = models.CharField(max_length=255, default='Wesbes alkalmazások') web_app_text = models.TextField(default=lorem) platform_text_heading = models.CharField(max_length=255, default='Platformfüggetlen') platform_text = models.TextField(default=lorem) partners_text_heading = models.CharField(max_length=255, default='Partnereink') partners_text = models.TextField(default=lorem) contact_text_heading = models.CharField(max_length=255, default='Kapcsolat') contact_text = models.TextField(default=lorem) And this is my translations.py @register(AboutUs) class AboutUsTranslationOptions(TranslationOptions): fields = ( 'main_text_heading', 'main_text', 'cloud_text_heading', 'cloud_text', 'web_app_text_heading', 'web_app_text', 'platform_text_heading', 'platform_text', 'partners_text_heading', 'partners_text', 'contact_text_heading', 'contact_text' ) required_languages = ('en', 'de', 'hu') And I simply render the texts in the templates. <h1 class="major">{{ main_text_heading }}</h1> <p>{{ main_text }}</p> Also if I put the letter 'ú' in all the translations (EN, DE, HU) … -
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