Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"error": "Could not connect to websocket endpoint wss://api-such.andsuch.xyz/graphql/. Please check if the endpoint url is correct."
I recently deployed a project I'm working on to production. I use this great library and I have GraphQL Playground set up via django-graphql-playground. Everything works fine locally - there are no issues whatsoever. However, when I deployed I get the error below when I hit the Play button in Playground: { "error": "Could not connect to websocket endpoint wss://api-such.andsuch.xyz/graphql/. Please check if the endpoint url is correct." } I use Gunicorn with a Uvicorn worker class in production. I even used the Gunicorn command locally to see if the issue could be from there but it works. One thing to note is that the application is dockerized. Could it be from there? I don't think so because it works locally. Here's what my docker-compose file looks like: version: '3.7' services: nginx: container_name: nginx image: nginx restart: always depends_on: - web volumes: - ./web/dev.nginx.template:/etc/nginx/conf.d/dev.nginx.template - ./static:/static - ./media:/media ports: - "8080:80" networks: - SOME_NETWORK command: /bin/bash -c "envsubst \"`env | awk -F = '{printf \" $$%s\", $$1}'`\" < /etc/nginx/conf.d/dev.nginx.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" web: container_name: web restart: always build: ./web networks: - SOME_NETWORK depends_on: - postgres - redis volumes: - ./web:/usr/src/app/ environment: - REDIS_HOST=redis - REDIS_PORT=6379 β¦ -
Django ModelFormset: Using two separate models, one to render survey question, one to save responses
I am new to Django, and am stuck. I am creating a survey using two models: one to describe the survey question, and one to store the response (either a choice of answers defined by QUESTION_ANSWER_CHOICES, or a text field): class PassengerRequirement (models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... question_number = models.CharField(max_length=12, default=0, unique=False) question_text = models.TextField(max_length=256, null=True, blank=True, help_text="Put the question in this field.") ... class PassengerRequirementMeasurement (models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) survey_question = models.ForeignKey('PassengerRequirement', related_name='passenger_requirement_answer', on_delete=models.CASCADE) survey_instance = models.ForeignKey('SurveyInstance', related_name='passenger_requirement_measurements', on_delete=models.CASCADE, null=True) answer_choice = models.CharField(max_length=1, choices=QUESTION_ANSWER_CHOICES, default=YES) answer_text = models.TextField(max_length=256, null=True, blank=True, help_text="Add Details") Then using the modelformset_factory a formset in forms.py: prFormSet = modelformset_factory(PassengerRequirementMeasurement, fields=('answer_choice', 'answer_text'), extra=0 ) And my view: def passenger_requirements_pretravel(request): surveyquestions = PassengerRequirement.objects.filter(...) if request.method == 'POST': formset = prFormSet(queryset=PassengerRequirement.objects.filter(...), data=request.POST) if formset.is_valid(): print('no problem') else: print(formset.errors) ... else: formset = prFormSet(queryset=PassengerRequirement.objects.filter(...) return render(request, 'surveys/passenger_requirements_pretravel.html', {'formset': formset, 'surveyquestions': surveyquestions}) The issue is, I can't get past the is_valid() method; it always returns a list of: [{'id': ['This field is required.']}, {'answer_choice': ['This field is required.'],... for each question in the list. I've tried an approach modelled after this question but still get something similar: <ul class="errorlist"><li>answer_choice<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Any suggestions? Thank β¦ -
gte is only showing objects for this month (equal to) and not greater than
I'm going to try to show you this without exposing customer data Query: Booking.objects.filter(startTime__year__gte=2020, startTime__month__gte=7,startTime__day__gte=27, depositPaid=True).order_by('startTime') This should show all bookings from July 27, inclusive, onward into the future with no bounds. However, the bounds is on the 8th month. None of the bookings for August are showing. If I run: Booking.objects.filter(startTime__year__gte=2020, startTime__month__gte=8,startTime__day__gte=1, depositPaid=True).order_by('startTime') Then I do get all the bookings in August. I don't understand why startTime__month__gte=7 doesn't show August. -
Django Mutllevel foreign keys Admin Editor
I have Country/State/City models. class Country(models.Model): name = models.CharField(max_length=127) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=127) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=127) All of them are registered. I want to add/edit/delete all of them in Admin Editor. Now, when I want to add a new City, I naturally would have to select the State and Country from the drop-down list. But in the current condition, if I select a particular Country, all the States are showing up including those that do not belong to the selected Country. I want the available options in the drop-down lists to abide by the selections. How can I achieve that for the Admin in the simplest way? Thanks -
AttributeError: module 'hello.views' has no attribute 'index' in Django while trying to create a helloWorld page
so I have been trying to follow the CS Harvard course thing but I'm stuck on lesson three lmao. they are using django to make a website I think? and I've run into this problem because I'm copying exactly what the instructor is doing but i still cant make my other part show up. What its supposed to do is have the basic website IP thing and then if i add /hello it should say hello world but it doesnt. The only files ive changed are these urls.py in lecture3 from django.contrib import admin from django.urls import include, path #added import include and path hello line urlpatterns = [ path('hello/', include("hello.urls")), path('admin/', admin.site.urls), ] urls.py in hello from django.urls import path from hello import views urlpatterns = [ path("", views.index, name="index") ] views.py in hello from django.http import HttpResponse from django.shortcuts import render Create your views here. def index(request): return HttpResponse("Hello, world!") and then in settings.py, the only line i added was 'hello', inside of the installed apps part. and the error message i keep on getting is File "/Users/matc/Dev/cfehome/lecture3/hello/urls.py", line 7, in path("", views.index, name="index") AttributeError: module 'hello.views' has no attribute 'index' any help would be greatly recommended! -
JS code doesn't work when passing from a "script" tag to a separate js file in Django
I am working with css and javascript files to improve the presentation of my page but I have problems executing my javascript code. The file structure of my application is as follows: prj_dj_uno/ βββ db.sqlite3 βββ manage.py βββ media βββ prj_dj_uno β βββ settings.py β βββ urls.py βββ repositorio β βββ admin.py β βββ apps.py β βββ migrations β βββ models.py β βββ static β β βββ repositorio β β βββ css β β β βββ base.css β β βββ js β β βββ subfamilia_list.js β βββ templates β β βββ base.html β β βββ repositorio β β βββ subfamilia_list.html β βββ tests.py β βββ urls.py β βββ views.py βββ static βββ admin β βββ fonts β βββ img βββ repositorio βββ css β βββ base.css β βββ subfamilia_list.css βββ img β βββ img_ref_350x300.svg β βββ java_logo.png β βββ logo_python.png βββ js βββ subfamilia_list.js the template i am using is this (subfamilia_list.html): {% extends "base.html" %} {% load static %} {% block title %}<title>Cactaceae</title>{% endblock %} {% block content %} <div class="container"> <h2 class="text-center my-3">Cactaceae</h2> {% if object_list %} <div class="row"> <div class="list-group col-md-8"> {% for obj in object_list%} <a href="{{ obj.get_absolute_url }}" class="list-group-item list-group-item-action"> {{ obj.subfamilia }}</a> {% endfor β¦ -
Celery and Django on production machine
/opt/fubar/fubar/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fubar.settings') app = Celery('fubar') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) /opt/fubar/fubar/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app', ) /etc/supervisor/conf.d/celeryworker.conf [program:fubar-celery] command=/opt/fubar/env/bin/celery worker -A fubar --loglevel=INFO directory=/opt/fubar user=www-data numprocs=1 stdout_logfile=/var/log/celery/fubar/worker.log stderr_logfile=/var/log/celery/fubar/worker.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 $ service rabbitmq-server status β rabbitmq-server.service - RabbitMQ Messaging Server Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2020-07-26 06:19:47 UTC; 19h ago Main PID: 21884 (rabbitmq-server) Tasks: 92 (limit: 4915) CGroup: /system.slice/rabbitmq-server.service ββ21884 /bin/sh /usr/sbin/rabbitmq-server ββ21905 /bin/sh /usr/lib/rabbitmq/bin/rabbitmq-server ββ22073 /usr/lib/erlang/erts-9.2/bin/epmd -daemon ββ22185 /usr/lib/erlang/erts-9.2/bin/beam.smp -W w -A 64 -P 1048576 -t 5000000 -stbt db -zdbbl 32000 -K true -B i ββ22299 erl_child_setup 65536 ββ22372 inet_gethost 4 ββ22373 inet_gethost 4 $ celery worker -A fubar --loglevel=INFO on localhost returns [tasks] . fubar.celery.debug_task . apps.raptor.tasks.launchraptor . apps.raptor.tasks.nolaunch while I see no tasks in the log file in production Apache error log shows: mod_wsgi (pid=26854): Exception occurred processing WSGI script '/var/www/fubar/fubar.wsgi'. ... celery.exceptions.NotRegistered: 'apps.raptor.tasks.launchraptor' I installed supervisor with pip install supervisor to get v4.2.0 What can I β¦ -
Linking a Context from one model to another a specific User in Django
I have a minor issue and I am stuck about how to fix it. I am trying to add a link to Post model related to a specific user (designer) context to a page with Item context for this particular user (designer). To explain more, in my project, a user can add a post and add an item each is a different app with different models and they can be the same users. So, in the 1st app called Score with a Post model, there is UserPostListView list view, I have my posts looped related only to a designer name. I want to add a link another page related to the items of this particular designer. Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template <a class="btn btn-primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Check now items</a> -
How to show cards after given day?
I have an app of flashcards that show me all cards of a given topic for me to study, but I want to have basicaly two buttons, one to show me the card again after 7 days (hard topic), and other to show me again after 28 days (easy topic), and, if possible, link this to a user. what I have is this: models.py: class Deck(models.Model): description = models.CharField(max_length=510, null=False, blank=True) is_active = models.BooleanField(default=False) def __str__(self): return self.description def get_number_of_cards(self): ''' Returns the number of cards in the decks related card_set ''' return self.card_set.count() get_number_of_cards.short_description = 'Card Count' class Card(models.Model): parentDeck = models.ForeignKey(Deck, on_delete=models.CASCADE) front = models.TextField() back = models.TextField() def __str__(self): return self.front def has_prev_card(self): ''' Returns true if card is not thee first card in the deck. ''' first_card_in_deck = self.parentDeck.card_set.first() if self == first_card_in_deck: return False return True def get_prev_card(self): ''' Return previous card in deck ''' return self.parentDeck.card_set.filter(id__lt=self.id).last() def has_next_card(self): ''' Returns true if card is not the last card in the deck. ''' last_card_in_deck = self.parentDeck.card_set.last() if self == last_card_in_deck: return False return True def get_next_card(self): ''' Return next card in deck ''' return self.parentDeck.card_set.filter(id__gt=self.id).first() views.py: def viewDeck(request, deck_id): ''' Gets the deck from the β¦ -
django random CSRF token failure
I am using django CSRF token's in a form, the usual way outline in this answer How to use Django CSRF token correctly?. Sometimes when I submit the form the csrf token randomly fails, and when I click the back button and submit again, it works. Has this happened to other people and how do I go about fixing this? -
Django modelformset is_valid method retrieves entire model from database
I have a modelformset when is_valid method is called the entire model objects of the underlying form is retrieved from the database which is not efficient if the database table contains hundred of thousands records, I believe Django was not designed with this deficiency and there must be something wrong with my code, When is_valid is called these queries are sent to the database, the first query has no WHERE clause which means it will retrieve the entire table!: [{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'}, {'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'}, **{'sql': 'SELECT `npr`.`rid`, `npr`.`PID`, `npr`.`rel`, `npr`.`CID` FROM `npr` ORDER BY `npr`.`rid` ASC', 'time': '0.037'}** {'sql': 'SELECT `person_details`.`ID`, `person_details`.`firstName` FROM `person_details` WHERE `person_details`.`ID` = 198 LIMIT 21', 'time': '0.001'}, {'sql': 'SELECT `person_details`.`ID`, `person_details`.`firstName` FROM `person_details` WHERE `person_details`.`ID` = 1243 LIMIT 21', 'time': '0.000'}, {'sql': 'SELECT `npr`.`rid`, `npr`.`PID`, `npr`.`rel`, `npr`.`CID` FROM `npr` WHERE `npr`.`rid` = 1377 LIMIT 21', 'time': '0.000'}, {'sql': 'SELECT (1) AS `a` FROM `person_details` WHERE `person_details`.`ID` = 198 LIMIT 1', 'time': '0.000'}, {'sql': 'SELECT (1) AS `a` FROM `person_details` WHERE `person_details`.`ID` = 1243 LIMIT 1', 'time': '0.000'}, {'sql': 'SELECT (1) AS `a` FROM `npr` WHERE (`npr`.`CID` = 1243 AND `npr`.`PID` = 198 AND NOT (`npr`.`rid` β¦ -
Get the latest instance of a foreign key in django models
Hi I am facing difficulty with a query in Django ORM: I have two models: class Student(models.Model): name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class choices: CHOICES = {(0, "Present"),(1, "Absent")} class Attendance(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='attendance') date = models.DateField() state = models.PositiveSmallIntegerField(choices=choices.CHOICES) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want to get all the students who were present on the latest date. -
How to fix matchong query does not exist error?
I have been working on a like system using django and ajax, this like system is very similar to instagram's one. After finishing with the code I started to get a Post matching query does not exist error which has been a pain. I dont see the wrong in my code but I think the problem is on the views.py file because the traceback is triggering a line there. How can i fix this error? models.py class Post(models.Model): text = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE, default='username') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') def __str__(self): return str(self.id) views.py (upload view uploades the form, home displays the uploaded form, like_post is the view in charged of liking and unliking posts and home_serialized os the one that contains the json so that the page doesnt reload when the like button is clicked) def upload(request): print("toro") if request.method == 'POST': print("caballo") form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('home') print('succesfully uploded') else: form = PostForm() print('didnt upload') return render(request, 'home.html', {'form': form}) def home(request): contents = Post.objects.all() args = { 'contents': contents, } return render(request, 'home.html', args) def like_post(request): user = request.user if request.method == 'POST': pk = β¦ -
GCP: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I'm unable to run django app on gcp app engine. logs, gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> at reap_workers (/layers/google.python.pip/pip/gunicorn/arbiter.py:525) at handle_chld (/layers/google.python.pip/pip/gunicorn/arbiter.py:242) at _releaseLock (/opt/python3.8/lib/python3.8/logging/__init__.py:223) -
How are tags organized in HTML Table in DJango?
I am trying to orgainize an HTML table, however my intended rows are coming out in the same columns. Is their an additonal tag I should use to fix this? Here is my html code and django template tags.. ''' <table> <thead> <th>height</th> <th>birthday</th> </thead> <tr> {% for ht in height %} <td>{{ ht.heightft }}' {{ ht.remainingInches }}</td> {% endfor %} </tr> <tr> {% for b in bday %} <td>{{ b.bday }}</td> {% endfor %} </tr> </table> ''' -
Django get_template error message. Can't run load.get_template()
In Python shell, I enter the following code: >>> from django.template import loader >>> template = loader.get_template('app/template_name.html') But this gives me an error message (note I have truncated the path): OSError: [Errno 22] Invalid argument: '...\project\\:\\app\\template_name.html' I get the same error message with other templates. Note that my templates are saved in app/templates/app. Also, this is my settings.py code: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], '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', ], }, }, ] Please can someone help me solve the problem? -
How can i get my button to be inside my image?
**What am trying to do is get my "Click here!" button to be in the bottom of my image but everything I tried hasn't worked so far and am kinda confused on why I can't get my button to the bottom of my image I have also tried to move it from my App.css file and still noting ** import React from 'react'; import Car from './car_lot.jpg' import Header from './logo.png' import Paperwork from './doc_sign.png' import Car_Galleryimg1 from './jeep.jpg' import Car_Galleryimg2 from './bmw.jpg' import Car_Galleryimg3 from './toyota.jpg' import ImageGallery from 'react-image-gallery'; const images = [ { original: Car_Galleryimg1, thumbnail: Car_Galleryimg1, }, { original: Car_Galleryimg2, thumbnail: Car_Galleryimg2, }, { original: Car_Galleryimg3, thumbnail: Car_Galleryimg3 }, ]; function Home() { return ( <div className="home"> <img src={Header} className="logo.png"/> <h1>Welcome to Exclusive Auto Sales</h1><link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet"/> <img src={Paperwork}className="doc_sign.png"/><button>Click here!</button> <h2>Get your dream car today we are here to help you!</h2> <ImageGallery items={images} /> </div> ); } export default Home; Here is the App.css file also .App { text-align: center; background-color: white; } .home { align-items: center; min-height: 100vh; } .home .Header { text-align: center; margin-top: 5px; margin-bottom: -20px; margin-left: 45px; margin-right: 45px; } .home h3 { font-size: 55px; font-family: 'Sora', sans-serif; text-align: center; margin-top: 5px; β¦ -
docker build network error when trying to pip install
I am building my first docker install as part of learning django. I have my docker install working. docker info is ok. and hello-world says successfull. But when I run the Dockerfile suggested by the turorial in my Django 3.0 Pro Book by Will Vincent. I get what look like a network dns error. ################ Error: Step 6/7 : RUN pip install pipenv && pipenv install --system ---> Running in 585e5020f53a WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f339144df10>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/pipenv/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f3391f05a90>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/pipenv/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f3391f05e90>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/pipenv/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f3391f05ad0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/pipenv/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object β¦ -
It is ok to use multiple one-to-one relationships for one table?
I want to add a translation feature for a Django application. The core app has some standard texts in different tables as CharFields. I want to build this feature in another app, so I can copy it to similar projects. I have the following idea: Core app: Business Table 1: name (OneToOne: CoreText) Business Table 2: name (OneToOne: CoreText) CoreText Table: key (simple identifier for humans) value (default text) Translation's app Translations Table: core_text (FK: CoreText) language value The CoreText table would work as an interface between the core and translation apps. It's good to mention that BusinessTable 1 and 2 don't grow over time, but the texts related used to change. The relationship between BTs and Texts would be done one time during configuration. I've been reading some 'not good' opinions about one-to-one relationships so I would like to know if this approach is ok. -
Rest auth / allauth Django
I am using rest auth with Facebook and Google login/sign up. I can't find how I can mark inside my user model how user was registered. How can I add field something like platform where I will set if user is using Facebook or Website to sign up. Thanks -
How do I increment data in Django?
I try to do increment in data that comes by request. I tried that first time with F model but I couldn't save data also, I tried to save the data by (create) and also the request occurs but no data didn't save match_statics/views.py from django.shortcuts import render, get_object_or_404, redirect from match.models import Main from .models import Statistics from .forms import StaticForm from django.db.models import F def player_statics(request, pk): form = StaticForm() if request.method == 'POST': form = StaticForm(request.POST) if form.is_valid(): if 'short_pass' in request.POST: # short_pass = Statistics.objects.filter(main__id=pk).update(short_pass=F('short_pass') + 1) s = Statistics.objects.create( main_id=pk, short_pass=form.cleaned_data['short_pass'] + 1 ) print(s) return redirect('match_statics:player_statics', pk=pk) context = {'form': form} return render(request, 'match_statics/player_statics.html', context) match_statics/models.py from django.db import models from match.models import Main class Statistics(models.Model): main = models.ForeignKey(Main, on_delete=models.CASCADE, related_name='static_field') short_pass = models.PositiveIntegerField(default=0) long_pass = models.PositiveIntegerField(default=0) danger_pass = models.PositiveIntegerField(default=0) not_danger_pass = models.PositiveIntegerField(default=0) cross = models.PositiveIntegerField(default=0) flat = models.PositiveIntegerField(default=0) foul_goal = models.PositiveIntegerField(default=0) foul_try = models.PositiveIntegerField(default=0) foul_none = models.PositiveIntegerField(default=0) corner_goal = models.PositiveIntegerField(default=0) corner_try = models.PositiveIntegerField(default=0) corner_none = models.PositiveIntegerField(default=0) tackl_ok = models.PositiveIntegerField(default=0) tackl_none = models.PositiveIntegerField(default=0) dribble_try = models.PositiveIntegerField(default=0) dribble_none = models.PositiveIntegerField(default=0) g_keeper_safe = models.PositiveIntegerField(default=0) g_keeper_danger = models.PositiveIntegerField(default=0) block_good = models.PositiveIntegerField(default=0) block_bad = models.PositiveIntegerField(default=0) match_static/player_statics.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Player Statics</title> </head> <body> <div β¦ -
Why does Block Content doesn't display but only base.html does?
I'm trying to inherit a base.html template to another one, but the thing is that when I extend it, it only shows the base.html but it doesn't show the block content, here's the code. from django.contrib import admin from django.urls import path from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.register, name = "register") ] from django.shortcuts import render # Create your views here. def register(request): return render(request, 'app1/register.html') <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>lalala</h1> </body> </html> {% extends "app1/base.html" %} {% block content %} <ol> <li>hola</li> <li>hola</li> <li>hola</li> </ol> {% endblock %} The thing is that it doesn't show the ol, it only shows the h1 from the base.html -
Linux deployment: Native Ubuntu vs WSL
I am trying to become a full-stack web-developer and i an currently using and learning Django. I am very close to the point where i have to deploy my first website. I have been coding the website on my macbook, where i am running a dualboot with Ubuntu.. But i also have a windows laptop where i got WSL installed. To explain my question further more, i was wondering if there is any difference on deploying my website to a linux server(ubuntu) from a native ubuntu system or from WSL. I have tried to search on google on the difference, but i haven't seen an answer that i was satisfied with. -
How to access a foreign key field in a sqlite model?
I'm working in an auction web app in Django. I'm designing the database and would like to reference the username attribute from User() model in my Listing() model. class User(AbstractUser): pass class Listing(models.Model): ## some fields owner = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="listing") def __str__(self): return f"Owner: @{self.owner.username}" The User class, in AbstractUser there is a username field, i checked. But somehow I'm getting this error: 'ManyRelatedManager' object has no attribute 'username' -
unique_together is not working with self referencing foreign key?
class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey("self", blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = [ ('parent', 'name'), ] In this model I am able to create multiple objects with Category.objects.create(name="cat1", parent=None) # Category.objects.create(name="cat1", parent=None) # unique_together constraint should not allow this object's reaction, but it is; behavior is the same even when the parent is not None. Django version I am using is 3.0.8