Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms widgets Textarea is directly set to type hidden but need it visible
My problem is i set a form from a model to change the value of the field "description" of this model : Model : class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) profile_img = models.ForeignKey(Image,on_delete=models.CASCADE,related_name='images',null=True) description = models.TextField() Form : class ChangeUserDescription(ModelForm): class Meta: model = Profile fields = ['description'] widgets = { 'description': forms.Textarea() } labels = { 'description':'Description' } But in result of this code I obtain this : <input type="hidden" name="csrfmiddlewaretoken" value="brsd4oO0qhMw2K8PyCIgSgEMqy7QFvEjTHaR6wTJmyWffJaCX5XyOMDLrGldZ3ji"> <button type="submit">Save changes</button> The issue is that i get : type="hidden" in the input whereas i want it to be visible and i do not specified in the widgets that it must be hidden. -
Trying to add a comment section form to my Django app
I get 2 different errors the first one is Django Model IntegrityError: NOT NULL constraint failed: I checked the solution for this, people said I've to make my FK attributes null = true and blank = true so this solved that. The second error I got after that was in my views.py 'CommentForm' object has no attribute 'cleaned_data' My Views.py file: def project(request, pk): form = CommentForm() project = ProjectModel.objects.get(id=pk) contextt ={ "project": project, "form":form, } if request.method == "POST": form.save() return redirect(request, "/dashboard") else: return render(request, "projects.html", contextt) and my Models.py: class ProjectModel(models.Model): caption = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y", validators=[file_size]) ProjectName = models.CharField(max_length=50, ) ProjectDescription = models.TextField(max_length=1000,) Project_Background_picture = models.ImageField( upload_to=settings.MEDIA_ROOT, default='/static/img/default.png') Approved = models.BooleanField(default=False) Finished = models.BooleanField(default=False) Goal = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True) Pledges = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True) Number_of_investors = models.IntegerField(blank=True, null=True) FirstReward = models.TextField(max_length=1000, default=' 10$ ') SecondReward = models.TextField(max_length=1000, default=' 25$') ThirdReward = models.TextField(max_length=1000, default='50$') FourthReward = models.TextField(max_length=1000, default='100$ +s') def __str__(self): return self.caption class comment(models.Model): ProjectModel = models.ForeignKey( ProjectModel, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=255) CommentBody = models.TextField(default='comment here!', max_length=1000 ) date_added = models.DateTimeField(auto_now_add=True) def _str_(self): return '%s - %s' % (self.ProjectModel.caption, self.name) -
NoReverseMatch at / Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<name>[^/]+)/$']
I am a beginner in learning code and am working on making a simple django site where users can write comments but I keep getting this error My urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("profile/<str:name>/", views.profile, name="profile") ] views.py class NewPostForm(forms.Form): title = forms.CharField(label="Title") description = forms.CharField(widget=forms.Textarea) def index(request): if request.method == "POST": form = NewPostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] author = request.user post = NewPost(title=title, description=description, author=author) post.save() return HttpResponseRedirect(reverse("index")) else: return render(request, "network/index.html", { "form": form }) return render(request, "network/index.html", { "form": NewPostForm(), "posts": NewPost.objects.all() }) models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): title = models.CharField(max_length=32) description = models.CharField(max_length=256) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) and my index.html {% extends "network/layout.html" %} {% load static %} {% load crispy_forms_tags %} {% block body %} <div class="form-group"> <form method="post" action="{% url 'index' %}"> {% csrf_token %} {{form | crispy}} <button class="btn btn-primary"> Post </button> </form> </div> {% for post in posts %} <div class="card"> <div class="card-body"> Title: {{post.title}} </div> <div class="card-body"> Description: {{post.description}}</div> <p> {{post.author.username}} </p> <div class="card-body"> <a href="{% url … -
Group by column Django orm
I have a database table users that consists of 4 columns id,name,country,state I will like to run an sql query like SELECT id,name,state,country FROM users GROUP BY country please how do i accomplish this using Django ORM -
Django app RANDOMLY losing connection to Postgresql database
I've been looking everywhere but cannot seem to find anyone with my same problem. Here's my situation... Django App: Running on Centos7 Vagrant guest 10.0.0.2 connecting to DB Postgresql-10 DB: Running on Centos7 Vagrant guest 10.0.0.1 serving the Django app, also has pgAdmin4 running on it When I bring these vagrant machines up they are able to initially connect. I notice when I leave them idle for periods of time then the Django app cannot connect any longer to the DB. Even weirder, most of the time, but not all the time, I simply needed to restart the postgresql database service and it would be able to connect again. Right now that's not even the case so I can no longer ignore this problem by just restarting the DB service. Any ideas on what could be going on here? I've tried a couple things but nothing seems to work. My feeling is it's something on the database machine causing issues since like I said usually this just required a simple restart of the DB service to fix. I'm completely confused by how it just loses connection sometimes randomly. -
Django multi tenant database error on generic models
My current application is multi tenant, so I manage one schema by user, There are many parts on my app where the user can add comments, so I decided to use a generic model, something like this: class Comment(models.Model): date = models.DateTimeField( _('Date'), blank=False, auto_now=True, db_index=False ) comment = models.TextField( _('Comment'), blank=False, null=False ) user = models.ForeignKey( 'security.User', related_name='comments', verbose_name=_('User'), on_delete=models.CASCADE, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() It works well with a single user/schema it saves the comments correctly, but when I logged-in with a different user and tried to save a comment throw me the next error: Traceback (most recent call last): File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: insert or update on table "generic_comment" violates foreign key constraint "generic_comment_content_type_id_068f197c_fk_django_co" DETAIL: Key (content_type_id)=(2) is not present in table "django_content_type". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return … -
Trigger javascript function from Django server
I am working on IPN's. Whenever I receive an IPN in this url: https://www.mywebsitename.com/notifications, I would like to run a simple JavaScript function that displays some html content. I manage the IPN's from the server side, as follows: @csrf_exempt def notifications(request): if request.method == "POST": #some code I would like to trigger my JS function inside that block of code, but I can't come up with any way of doing this. Also I don't really know wether what I am asking is really possible or not, maybe there is another approach that I can't figure out by myself. -
How to iterate through Django model items in a ManyToManyField
Brand new to Django/Python and thought I'd start by building a simple blog app. I would like the User to be able to post book references that include the book name and a link to the book. My current References class in my models.py looks like this: class References(models.Model): link = models.URLField(max_length=150, default=False) title = models.CharField(max_length=100, default=False) def __str__(self): return self.title and my Post class looks like this: class Post(models.Model): title = models.CharField(max_length=31) content = models.TextField() thumbnail = models.ImageField() displayed_author = models.CharField(max_length=25, default=True) shortquote = models.TextField() reference_title = models.ManyToManyField(References) publish_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse("detail", kwargs={ 'slug': self.slug }) def get_love_url(self): return reverse("love", kwargs={ 'slug': self.slug }) @property def comments(self): return self.comment_set.all() @property def get_comment_count(self): return self.comment_set.all().count() @property def get_view_count(self): return self.postview_set.all().count() @property def get_love_count(self): return self.love_set.all().count() I understand that i'm only returning the title in my References class, I've tried returning self.title + self.linkbut this gives me both the title and link together when being called in the template. My template calling the references class looks like this: {% for title in post.reference_title.all %} <a href="{{ link }}"> <li>{{ title }}</li> </a> {% endfor … -
django registration and login on the same page
i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my views file #views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, ' Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'register.html', context) @unauthenticated_user def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'username or password is incorrect') context = {} return render(request, 'login.html', context) -
Unknown command: 'auth' Type 'manage.py help' for usage
I'm using django 3.1 and I'm unable to fix this issue. I'm running following command heroku run python manage.py auth zero. and getting this in return : Running python manage.py auth zero on ⬢ dotescrow... up, run.1867 (Free) Unknown command: 'auth' Type 'manage.py help' for usage. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'django_countries', 'bootstrap3', # 'wallets', # 'frontend', ] -
python Django db utils programming error (1064)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json NOT NULL, category_json json NOT NULL)' at line 1") occurs during the database migrations in python sharehosting -
Does Django use case sensitive filenames for FileField with MySQL backend?
I'm using Django 3.1.3 and have a model with a FileField field. When I upload a file with same name, but different case, the logic I have is reporting that it is a duplicate. For example: Files <QuerySet ['92/565/20191222_152213.jpg', '92/565/cs_731__DSC8110.jpg', '92/565/ADs-2.MP4']>, this 92/565/ADS-2.mp4 The logic is... other_pieces_in_room = Piece.objects.filter(room__id=self.room_id) other_files_in_room = other_pieces_in_room.values_list('file', flat=True) mylog.debug("Files {}, this {}".format(other_files_in_room, file.name)) if file.name in other_files_in_room: raise forms.ValidationError("...") Model (relevant fields) is: class Piece(models.Model): file = models.FileField(upload_to=media_location) room = models.ForeignKey(Room, on_delete=models.CASCADE) Any thoughts as to what is going on? -
sqlite3.OperationalError: no such table: django_site__old
I'm trying to make a webpage using python and mezzanine as its cms. but I got this error after successfully creating Superuser: Superuser created successfully. Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: django_site__old The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\annie\Documents\DMCproject\manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 61, in handle func() File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 109, in create_pages call_command("loaddata", "mezzanine_required.json") File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 115, in loaddata connection.check_constraints(table_names=table_names) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 276, in check_constraints cursor.execute( File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python39\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python39\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", … -
django allauth for confirm by phone
I want after signup page , user redirect to confirm with phone page .. How handle it in with allauth .. it redirect after signup page to confirm mail page in any case or redirect to page /account/inactive/ In the event that is-active default false -
Django Rest Framework - Create ForeignKey lookup fields
I'm trying to Create LikeSong which have Related Field with Song model In need to pass slug instead of pk class LikedSongSerializer(serializers.ModelSerializer): song = serializers.SlugRelatedField( queryset=Song.objects.all(), slug_field='slug' ) class Meta: model = LikedSong fields = [ 'song', 'media_type' ] def create(self, validated_data): liked = LikedSong.objects.get_or_create(user=self.context['request'].user, **validated_data) return liked but i got this error AttributeError: Got AttributeError when attempting to get a value for field `song` on serializer `LikedSongSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the tuple instance. Original exception text was: 'tuple' object has no attribute 'song'. [15/Jan/2021 21:24:00] "POST /api/music/like_song/ HTTP/1.1" 500 20927 -
Queries on multiple fields, each with a custom method, with django-filter
I have this filter: class MsTuneFilter(django_filters.FilterSet): def all_titles(self, queryset, name, value): return MsTune.objects.filter( Q(name__icontains=value) | Q(title__icontains=value) | Q(alt_title__icontains=value) ) def ind_1(self, queryset, name, value): return MsTune.objects.filter( Q(index_standard_1__startswith=value) | Q(index_gore_1__startswith=value) | Q(alt_index_gore_1__startswith=value) | Q(alt_index_standard_1__startswith=value) ) title = django_filters.CharFilter(method='all_titles', label="All title fields") index_standard_1 = django_filters.CharFilter(method='ind_1', label="Index 1") class Meta: model = MsTune fields = ['index_standard_1', 'title', ....] It all works well when I'm making queries which do not involve both 'title' and 'index_standard_1'. Nevertheless, if I'm searching for something with a specific title AND with a specific index, either the index search or the title is ignored, i.e. the query returns all the indexes or all the titles, ignoring a parameter of my search. What am I overlooking? -
"Reverse query name" in django model's use case
I need to know where the "Reverse query name" show's it self in django modeling(most common use case). -
How can i pass a dynamic url to another url
Im new to Django. So, my problem is that i want my dynamic url like this: website.com/password/2332 "2332" is the dynamic part to pass to this: website.com/password/2332/revealpassword urls.py: path("password/<str:link>", views.password), path("password/<str:link>/revealpassword", views.reveal_password, name="reveal_password") html file: <a href="{% url 'password:reveal_password' link %}">Reveal</a> the Problem is at the "link". How can i pass the stuff that is in the url to the new url -
Django forms checkbox required even if require:false in form attrs
how can i make my checkbox not required using django forms? my forms.py invoice = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'checkboxInvoice','required': 'False'})) my models.py invoice = models.BooleanField(default=False, blank=True, null=True) -
Django is having trouble finding static folder/css
I have a Django project in which I am getting a 404 on the CSS file. In my app (the only one I have) I have a template directory with a few different HTML files. I also have a static directory (found in the same directory as app) I have a CSS file saved as such /static/css/main.css/. See below for my settings.py file which sets the static folder: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5&-12%c=er64$=$0w6*0sc__s8k_4ldiq(mkowlmqdatn!!g!8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'feed' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'kahlo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'kahlo.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Django restframework and javascript - one of two identical calls not working
I am pretty puzzled about this error, and I cannot find the solution. I have two nearly identical models, which both work in the browser, but one of them does not work when accessed via JS: models: class Ad(models.Model): name = models.CharField("name", max_length = 32, unique = True) file = models.ImageField(upload_to = "ads") class Product(models.Model): name = models.CharField("name", max_length = 128) price = models.FloatField("price", null = True, blank = True) user = models.ForeignKey(User, on_delete = models.CASCADE) views: class AdDataViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = '/login/' def list(self, request): query = Ad.objects.all() try: results = AdSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as e: return Response(data = str(e), status = status.HTTP_400_BAD_REQUEST) class ProductDataViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = '/login/' def list(self, request): query = Product.objects.all() try: results = ProductSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as e: return Response(data = str(e), status = status.HTTP_400_BAD_REQUEST) serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["pk", "name", "price"] class AdSerializer(serializers.ModelSerializer): class Meta: model = Ad fields = ["pk", "name", "file"] urls: router = routers.DefaultRouter() router.register(r'products', views.ProductDataViewSet, basename = "products") router.register(r'ads', views.AdDataViewSet, basename = "ads") urlpatterns = [ path("", … -
Django Forms access fields using ajax or fetch
is there any way to access or "GET" Django forms fields using fetch or ajax? I am trying to sending the form using JsonResponse but know how can I do that? -
django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node
I'm trying to deploy my project on heroku ,i'm using django 3.1 and i'm unable to do that. I'm getting error due to migrations. Please i humble request you to give some time to this question to resolve this problem. Whenever i run the command heroku run python manage.py migrate ,it gives following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 255, in build_graph self.graph.validate_consistency() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node ('auth', '0023_remove_user_current_balance') migration dependency dependencies = … -
React build shows white page with Django
I am trying to load React build files in a Django template (serving the React build files via Django static files). I’ve had success using this approach in the past with other Django templates, but with this particular case, the React app is not attaching to my div in the Django template. The React app is created using create_react_app with minimal changes. My src/index.js file: (only changed the root element) import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('chat-root') ); reportWebVitals(); My public/index.html file: (only changed the root element) <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" … -
Best way to store/model game data on a Django website?
Please allow me to set up the environment for my question: On my website, users register for an account and then go to the game page Once 5 players load in to the game page, a new game starts. The game works as follows: Players guess numbers until they find the "magic number", which is a random number from 1-100 Once 3 players have guessed the magic number correctly, the other 2 are declared the losers and kicked from the page My question is as follows: what is the best way to store individual game information? In order for the game to operate correctly, the website needs to somehow hold information on the game; specifically, a counter that increments every time a player guesses the magic number correctly. Points of consideration: I would like to make it so multiple games could be going on at once (website.com/game could have multiple gaming sessions going on at once on it), so the solution should not inhibit that. I am running my website with Django, along with HTML/CSS/JavaScript This is (probably obviously) a simplified version of the game I am implementing online. In reality, the solution would be able to hold multiple dynamic …