Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Specific email required during signup
Django 2.1.5 Python 3.7 I'm trying to have my signup form only accept .edu emails. Right now it accepts any kind of email that has an @ sign in it. -
Which model relationship should I be using?
I have the following in my models.py class items(models.Model): name = models.CharField(max_length=255) item_image = models.ImageField(upload_to='itemimage/', default=None, blank=True) price = models.DecimalField(decimal_places=2, max_digits=100) class comparelist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item1 = models.ForeignKey(items, on_delete=models.CASCADE, null=True, blank=True) item2 = models.ForeignKey(items, on_delete=models.CASCADE, null=True, blank=True) item3 = models.ForeignKey(items, on_delete=models.CASCADE, null=True, blank=True) item4 = models.ForeignKey(items, on_delete=models.CASCADE, null=True, blank=True) The idea is to allow a user to add 4 different items to their account so they can compare them. But when I makemigrations, I get the following error: compareapp.comparelist.item1: (fields.E304) Reverse accessor for 'comparelist.item1' clashes with reverse accessor for 'comparelist.item2'. HINT: Add or change a related_name argument to the definition for 'comparelist.item1' or 'comparelist.item2'. I'm assuming ForeignKey is not the relationship field to use here. I tried reading django docs on relationship fields but I can't get my head around it. Can someone give me a simple explanation on the 3 different relationship fields? And which one should be used in this situation? -
Django ImportError: cannot import name 'render_to_response' from 'django.shortcuts'
After upgrading to Django 3.0, I get the following error: ImportError: cannot import name 'render_to_response' from 'django.shortcuts' My view: from django.shortcuts import render_to_response from django.template import RequestContext def index(request): context = {'foo': 'bar'} return render_to_response('index.html', context, context_instance=RequestContext(request)) Here is the full traceback: Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 580, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 565, in start_django reloader.run(django_main_thread) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/autoreload.py", line 272, in run get_resolver().urlconf_module File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/alasdair/.virtualenvs/django30/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "/Users/alasdair/.pyenv/versions/3.7.2/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
How can I get super detailed Django debug info?
I have a very difficult to diagnose Django problem in which sometimes the server locks up for a period of time many attempts to debug it have not succeeded. So I need to see at the most detailed level possible what Python is doing. Ideally I would have some sort of output log sitting somewhere dumping vast amounts of info the the screen until the problem occurs then I can see exactly what was happening at the point of hang. Can anyone suggest the most effective way to get this information dumped out of Django? All the searches that I do for Django debugging refer only to application level debugging - I need to go lower. -
Problem with Django app unit tests under Visual Studio Code
I have a draft of the Django project with the added one application (e.g. my_app). In this app I have places tests.py file with one test: import unittest class Test_MyModel(unittest.TestCase): def test_dummy(self): self.assertEqual(1,1) In this case, this dummy test is discoverd by Visual Studio Code and could be executed in it, also it's possible to launch this test from command line: python manage.py test When I modify my file with unit test add import some model (placed in file models.py) from my_app: import unittest from .models import MyModel # new added line class Test_MyModel(unittest.TestCase): def test_dummy(self): self.assertEqual(1,1) In this case I'm still be able run test from command line without any problems, but VSC doesn't discover my test and in the Python Test Log in the VSC I get error: ====================================================================== ERROR: tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: tests Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 434, in _find_test_path module = self._get_module_from_name(name) File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 375, in _get_module_from_name __import__(name) File "/Users/myuser/Projects/backend/my_app/tests.py", line 3, in <module> from my_app.models import MyModel File "/Users/myuser/Projects/backend/my_app/models.py", line 4, in <module> class MyModel(models.Model): File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/myuser/Projects/virtualenvs/my_app_env/lib/python3.7/site-packages/django/apps/registry.py", line … -
How to update django model through data in foreignkey fields?
I am trying to migrate some data from one table to another, and I have the following script: def forward_func(apps, schema_editor): targetModel = apps.get_model("target", "some_target") targetModel.objects.all().update(a='other__table__a') both fields are boolean, and the data inside the original table has no problem and has correct type. For some reason, I'm getting this message: ValidationError: [u"'other__table__a' value must be either True or False."] From the django doc (v1.11), I can't really find a topic talking directly about this, but I've found However, unlike F() objects in filter and exclude clauses, you can’t introduce joins when you use F() objects in an update – you can only reference fields local to the model being updated. If you attempt to introduce a join with an F() object, a FieldError will be raised: # This will raise a FieldError >>> Entry.objects.update(headline=F('blog__name')) Does that mean I simply cannot call .update using foreinkeys? Do I have to loop through every object and update this way? -
When I tried running my python program, I encountered a Django importing module Error
When I tried running a python program on my local machine, I encountered this error: Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. There are also similar posts online, and I tried the suggested solution from each post, but none of them could solve my error. Here is the content of my setting.py My python version: Python 3.7.3 My Django verison: 2.2 Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku import dj_database_url config = dj_database_url.config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY … -
Send POST request from ember to specified URL
I am new to full stack development, and having an issue with a web application I'm working on for my employer. I was tasked with creating a fairly simple application that we can scale over time. For now all that it needs to do is take data from one of our databases, and pass it to a front end application. Using this front-end app our workers should be able to double check the information passed in, and make sure it has been properly translated to a new format. After it is translated I want to send an HTTP POST request to our new systems back-end and have it add this new data via the REST API. Essentially it's an application that was used for practice to get me more acquainted with full stack development while making an effective tool to transfer mass data from one system to another. I can't seem to figure out how to set up something in ember.js to send that POST request to somewhere other than my back-end though. -
Django Migration not starting on ubuntu
i have uploaded my Django project to an ubuntu server. and deleted all migration files on project folder. I was using mysql on my localhost, but installed Postgresql on Ubuntu. When i try to migrate database django raises errors like below. python manage.py migrate results in F File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/Virtual/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/root/Virtual/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/root/Virtual/lib/python3.7/site-packages/django/utils/autoreload.py", line 579, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/root/Virtual/lib/python3.7/site-packages/django/utils/autoreload.py", line 564, in start_django reloader.run(django_main_thread) File "/root/Virtual/lib/python3.7/site-packages/django/utils/autoreload.py", line 272, in run get_resolver().urlconf_module File "/root/Virtual/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/root/Virtual/lib/python3.7/site-packages/django/urls/resolvers.py", line 564, in urlconf_module return import_module(self.urlconf_name) File "/root/Virtual/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", … -
Why does initial autocomplete not work in multiple select?
It is necessary that the initial values are automatically selected in the multiple select, but for some reason this does not happen. Tried to define initial in forms.py models class Provider(models.Model): payment = models.ManyToManyField(Payment, related_name="provider", blank=True) delivery = models.ManyToManyField(Delivery, related_name="provider", blank=True) forms class ProductCreateForm(forms.ModelForm): class Meta: widgets = { 'payment_method': forms.SelectMultiple( attrs={ 'class': 'select2', 'style': 'width: 335px', 'onchange': 'checkProductMethod(event, this);' } ), def __init__(self, *args, **kwargs): self.request = kwargs.pop('initial').get('request') super(ProductCreateForm, self).__init__(*args, **kwargs) provider = Provider.objects.filter(user=self.request.user.id).last()) self.fields['payment_method'] = ModelMultipleChoiceField(queryset=provider.payment.all()) print([i for i in provider.payment.all().values_list('id', flat=True)]) #List of ids self.fields['payment_method'].initial = [i for i in provider.payment.all().values_list('id', flat=True)] views class ProductsCreate(CreateView): model = Product form_class = ProductCreateForm http_method_names = ['get', 'post'] def get_initial(self): initial = super(ProductsCreate, self).get_initial() initial['request'] = self.request return initial def get_context_data(self, *args, **kwargs): ctx=super(ProductsCreate, self).get_context_data(*args, **kwargs) ctx['special_form'] = SpeciallyPriceForm() return ctx def get(self, request, *args, **kwargs): self.object = None if kwargs.get('slug'): category = Category.objects.filter(slug=kwargs.get('slug')).first() self.initial.update({'category': category}) return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): ... -
How to edit user-created data as an admin?
How can I edit user-created data from the admin panel given that I have the user's username and password? I have googled a little but I can't seem to find a clue. -
CSV upload to database does not seem to work
I'm setting up a web app that allows user to upload a CSV file that saves to MEDIA_ROOT and updates the database with the CSV data. However, I can't seem to get it to work. The file saves okay but the database doesn't update. I had trouble with request.FILES but managed to get to the bottom of that. but I can't seem to update the database with the CSV data. models.py import datetime from django.utils import timezone from django.db import models from django.contrib.auth.models import User class UserData(models.Model): user_user = models.ForeignKey(User, on_delete=models.CASCADE ) user_updated = models.DateTimeField(auto_now=True) user_contract_number = models.CharField(verbose_name="Contract Number",max_length=30, null=True, blank=True) user_ticket_number = models.CharField(verbose_name="Ticket number",max_length=30, null=True, blank=True) user_weigh_bridge_number = models.CharField(verbose_name="Weigh Birdge number",max_length=30, null=True, blank=True) def __str__(self): return f'{self.user.username} Data' views.py from django.http import HttpResponse from django.template import loader from django.contrib import messages from django.contrib.auth import login, authenticate from django.contrib.auth.decorators import login_required from data_user.models import UserData import csv, io from datetime import datetime @login_required def user_data(request): if request.method == 'POST': ud_form = UserDataForm(request.POST, request.FILES, instance=request.user.userprofile) if ud_form.is_valid(): ud_form.save() csv_file = request.FILES['user_user_data'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) for column in csv.reader(io_string, delimiter=','): _, created = UserData.objects.update_or_create( user_user=username, user_contract_number=column[0], user_ticket_number=column[1], user_weigh_bridge_number=column[2], ) messages.success(request, f'Congratulations {request.user.first_name} ! You have uploaded your waste data') … -
Python Django website installed from Git(hub) with pip
I would like to create a package for a Django website on Git(hub) which can be installed with pip, and run with whatever server is configured (I'm using uWSGI at the moment). How can I create a new wsgi.py that will import both the app AND project files from the virtual environment installed packages? I understand how just the app would work, but not the project itself. I would like this Django website to be distributed as a whole, with the user only needing to change the settings for their environment (various settings, SECRET, etc.). This is the default wsgi.py that Django creates: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = get_wsgi_application() The imports themselves should be fine, and I assume that I would point the environment variable to my virtual environment package and settings file like so: import my_project os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') and in the settings file, I would import the custom settings project based on the actual file location. That leaves the project urls.py and I haven't any idea on what to try there since I can't find any reference to it. Since I can't find any references, do people not create pip packages from the project? -
How can I restrict an authenticated user from posting on behalf of someone else?
If I am logged in as user1 and I am accessing a ViewSet called RecipeSubmissionViewSet, the POST takes a recipe_id of the recipe the user wants to submit. How do I ensure that user1 does not submit user2's recipe, assuming the Recipe model has an owner field on it and I can just compare it to request.user? Should I use a permission class for this or is there a better way? I'm speaking from an backend point of view and not taking into account that the front end would of course filter out the recipes that belong to the user and only show them their own recipes. -
Call Python script from SQL trigger
I have the following scenario: users can log in and update certain tables, and whenever that table is updated I would like to call a Python script that will query the same database for additional information (joins) and then use Django's email system to email all users in that group (same role) that information. My current methodology is to create a user-defined function in SQLite3, and then create a trigger that will call that function (which is linked to a Python file). Is this possible with SQLite? Django app, SQLite and Python. import sqlite3 def email_materials_submittal(project_id): print(project_id) con = sqlite3.connect('../db.sqlite3') con.create_function("FUNC_EMS", 1, email_materials_submittal) con.commit() cur = con.cursor() cur.execute("CREATE TRIGGER TRIG_EMS AFTER INSERT ON core_level BEGIN SELECT FUNC_EMS(NEW.project_id); END;") con.commit() con.close() I want SQL to call an external Python script whenever a new row is inserted into a certain table. Tried the code above, but SQLite throws the error: no such function: FUNC_EMS -
Fix postgersSQL column to be a timestamp with Django's deafult ORM?
I'm trying to use a models.DateTimeField field in my Django project using postgresSQL and the default ORM. However, for some reason postgresSQL thinks the column is a Boolean type when I try to set it instead of a timestamp. How would I fix this? I've tried to flush the database and reruning makemigerations and migrate as well as deleting the migrations folder but this has not changed the result. relevant code from models.py class Link(models.Model): expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) Error when trying to set that field ProgrammingError at /admin/my_app/link/add/ column "expiry_date" is of type boolean but expression is of type timestamp with time zone LINE 1: ...VALUES ('123', true, 0.0, 0.0, NULL, false, NULL, '2019-04-2... -
How assign existing, nested objects in serializer?
I've got Membership class which contains 3 ForeginKey fields. These FK always have to reference to already existing objects so I'm wondering how simplify create and update methods inside MembershipSerializer in order to assign these fields using only keys passed in request. Here's MembershipSerializer class code: class MembershipSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) club = ClubSerializer(many=False) inClubRole = InClubRoleSerializer(many=False) class Meta: fields=( 'user', 'club', 'inClubRole', ) model = Membership def create(self, validated_data): print(validated_data) user_data = User.objects.get(id=validated_data.pop('user')) club_data = Club.objects.get(id=validated_data.pop('club')) inClubRole_data = InClubRole.objects.get(id=validated_data.pop('inClubRole')) instance = Membership.objects.create(**validated_data) instance.user=user_data instance.club = club_data instance.inClubRole = inClubRole_data return instance Since User, Club, and InClubRole models already exists I want to simplify POST and UPDATE for Membership class just by passing Primary Keys like that: { "user": 1, "club": 1, "inClubRole": 4 } However create methods still expects passing every field related with User, Club and InClubRole classes. How to fix that? Or maybe there is a simplier way to handle with it? -
authenticate only superuser
authenticate() function is only authenticating superuser I had tried using simple search but it's not gonna use login() function then and not gonna check that user is active or not ''' def Login_View(request): if request.method == "POST": username = request.POST['username'] paswrd = request.POST['pwd'] user = authenticate(username=username, password=paswrd) if user is not None: if user.is_active: login(request, user) name = User.objects.get(username=request.user) request.session['username'] = username return redirect('/dashboard/',{'name':name.username}) # return render(request,'dashboard_app/index.html',{'name':name.username}) else: return render(request, 'login_app/index.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'login_app/index.html', {'error_message': 'Invalid login'}) return render(request, 'login_app/index.html') ''' I want to login all user that is in the database either they are simple user or superuser -
raise MultiValueDictKeyError(key) when posting in database
I get the following error raise MultiValueDictKeyError(key) : django.utils.datastructures.MultiValueDictKeyError: 'redirect' when I try to save the value the user types in. At first, I thought it had something to do with the input value, but since the error explicitly gives 'redirect' back I assume it has something to do with the redirect to the next part of the application. I have tried two different versions of return redirect, but it is very confusing what now exactly the right thing is. At the same time, I get raise NoReverseMatch(msg) when I try to submit the input value to the database. view def InputData(request, element_id, session_id): input_element = get_object_or_404(InputData_model, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF_input' result = UserInput() result.input_value = request.POST.get('input_value') result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['redirect']) #return redirect(request.POST.get('redirect')) template <form id="input_form"> <property name="interdigittimeout" value="2s"/> <property name="timeout" value="4s"/> <property name="termchar" value="#" /> <field name="input_value" type="digits?minlength=1;maxlength=5"> <prompt> <audio src="{{ ask_input_label }}"/> </prompt> <filled> <assign name="redirect" expr="'{{ redirect_url }}'"/> <submit next="{{ url }}" enctype="multipart/form-data" namelist="input_value" method="post"/> <goto next="{{ redirect_url }}" /> </filled> </field> </form> traceback Internal Server Error: /vxml/InputData/33/57 File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/datastructures.py", line 77, in __getitem__ list_ = super().__getitem__(key) … -
Django template sidebar not rendering as it should
In a Django project, I have a side bar that is not rendering in the correct place. Instead of coming up on the right hand side of the content, as it does for the other pages that have similar content, the side bar in this case is at the very bottom. I cannot figure out how to move it, and have tried various things in the base.html and moving around the Django templating language block content. Rendering the template (register.html) looks like this: It should however look like this, as per the tutorial: Relevant part of the base.html <!--this is django templating language--> <link rel="stylesheet" href="{% static 'worldguestbook\main2.css' %}"/> </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">FakeBook Newsfeed</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'socialmedia-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'socialmedia-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="{% url 'socialmedia-login' %}">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> register.html {% extends "socialmedia/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset … -
Upstream prematurely closed connection
I'm trying to dockerize my django app with gunicorn and nginx configured to it. I am following this tutorial here (http://pawamoy.github.io/2018/02/01/docker-compose-django-postgres-nginx.html) to do so. Afterwards, when I try doing docker-compose up --build, I get the following. Successfully built 2ba3b610b1c0 Successfully tagged djangotools_iedb_tools:latest Starting djangotools_iedb_tools_1 ... done Starting djangotools_nginx_1 ... done Attaching to djangotools_iedb_tools_1, djangotools_nginx_1 iedb_tools_1 | [2019-04-29 18:37:26 +0000] [1] [INFO] Starting gunicorn 19.9.0 iedb_tools_1 | [2019-04-29 18:37:26 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) iedb_tools_1 | [2019-04-29 18:37:26 +0000] [1] [INFO] Using worker: sync iedb_tools_1 | [2019-04-29 18:37:26 +0000] [10] [INFO] Booting worker with pid: 10 iedb_tools_1 | [2019-04-29 18:38:03 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:10) nginx_1 | 2019/04/29 18:38:03 [error] 6#6: *1 upstream prematurely closed connection while reading response header from upstream, client: 172.23.0.1, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "http://172.23.0.2:8000/", host: "0.0.0.0:8000" nginx_1 | 172.23.0.1 - - [29/Apr/2019:18:38:03 +0000] "GET / HTTP/1.1" 502 576 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36" "-" iedb_tools_1 | [2019-04-29 11:38:03 +0000] [10] [INFO] Worker exiting (pid: 10) iedb_tools_1 | [2019-04-29 18:38:04 +0000] [39] [INFO] Booting worker with pid: 39 On the web, I would get 502 Bad Gateway. So when I took a look at the … -
How to return custom dictionary as response for a "create" method in django rest framework?
Im Using django rest framework for my current project.Im using a nested serializer. class FirstSerializer(serializers.Serializer): field_one = serializers.CharField() field_two = serializers.CharField() Class SecondSerializer(serializers.Serializer): my_field = FirstSerializer(many=True) def create(self, validated_data): custom_dictionary = {} return custom_dictionary This is where am stucked up.I've been doing some operations in SecondSerializer now I need to return a custom dictionary without the key "my_field" on response. -
Bad request for POST and no return value for GET using Ajax
I have the code to post data to the django server and get data from it using ajax. When I use post method the server responds with Bad Request: /quizzes/ [29/Apr/2019 18:13:42] "POST /quizzes/ HTTP/1.1" 400 83 And in the ajax code is not returning any information, not in error nor complete. When I tried to get data from the server, the server says it's okay [29/Apr/2019 18:19:57] "GET /quizzes/ HTTP/1.1" 200 249 but the code entered the error and complete blocks with error msg ONLY "Error with status: error" Another problem is when the request end, my firefox reloads the page and I don't know why So anyone can suggest a solution to these problems?! This is my Ajax code for post method, which not giving me any response And the server is expecting to recieve json object in this format { 'title': "superheroes java", 'pass_score': 1, 'num_of_questions': 3, 'expected_duration': 10, 'skill_type': {"name": "java"}, } Here's how I format and send it $("#add-quiz").click(function () { quizData = { title: $("#quizTitle").val(), pass_score: Number($("#quizPassScore").val()), num_of_questions: Number($("#quizNumQuestions").val()), expected_duration: Number($("#quizDuration").val()), skill_type: {name: $("#quizSkillType").val()} }; response = "" $.ajax({ url: "http://127.0.0.1:8001/quizzes/", dataType: "json", method: "POST", data: quizData, success: function () { response = "success"; … -
How to specify which value is returned for a foreign field when serialising data in a view in Django
I have a model containing a ForeignKey to another model. I am attempting to serialize this model and want to control what field is returned for the foreignkey field. See below: models.py class Surveyor(models.Model): num = models.CharField(max_length=3) name = models.CharField(max_length=250) class Anblsrecord(models.Model): ... sur_num = models.ForeignKey(Surveyor, on_delete=models.CASCADE) views.py def anbls_points(request): points_as_geojson = serialize('geojson', Anblsrecord.objects.all()[:5], fields=(... 'sur_num')) return JsonResponse(json.loads(points_as_geojson)) When I view this I get: ... "sur_num": 1 ... where the "1" is "num" from Surveyor class. I want to return "name". I looked at https://docs.djangoproject.com/en/2.2/topics/serialization/ which talks about multi-table inheritance, but I can't find anything for a related table. Any help would be greatly appreciated. -
In the Wagtail admin, is there an equivalent to the Django admin's save_model method?
I have a model whose instances I would like to restrict to a particular site, and so I want to automatically save the site with the model. I've defined a TenantAwareModel from which I inherit when defining site-specific models: class TenantAwareModel(models.Model): class Meta: abstract = True tenant = models.ForeignKey(Site, on_delete=models.CASCADE) Wagtail provides the site as part of the request, so in the wagtail_hooks.py file I wanted to override save_model in the same way as can be done in the regular Django admin. However, I've just discovered that there is no save_model method on Wagtail's ModelAdmin. Is there a way to intercept a save in the Wagtail admin in order to insert a value that is taken from the request object (in this case the site) into the model?