Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django templates folder structure good practices
Lets say I have a couple of apps, that are totally separate, and I want to keep the templates folder on a project level. My folder structure would look like this: project_name - first_app - second_app - ... - x_app - project_name - static - templates - __init__.py - manage.py Now, the first question is: If I want to keep template folder on a project level, should I create sub-directories for each app, like so: -templates -first_app -second_app or should I just have templates from all aps mixed together in templates folder? And the same question goes for static folder. If I want to keep it on a project level, should I create sub-directory for each app, and should each of the apps directories have their own /css /images /js? And the last question I have, is, if I as I said have a couple of apps, that are totally separate, and want to create a welcome page for the project, that would just be a simple menu with anchor tags to all the apps, where should I render the view for it? I don't feel like it belongs to any specific app, but creating a whole new app just … -
Share django transaction accross threads
I've a problem where one API implemented in a django (3.2) web app has to fetch different prices from multiple APIs and store those prices in the database (Postgres 13) before returning to the client. I'd like to put the inserts in the same transaction, so if something unexpected happens, nothing will be inserted. I am now going forward by first calling all apis, each one inside a green thread (gevent) and after all of them return, I bulk insert the results. But turns out I got really curious if I it is possible for different threads ( green or not) to share the same transaction. I saw that psycopg2 can execute in a non blocking way. The issue now is everytime I start thread in django the new thread is inside a new transaction. I will dig into the django db backend source to understand what is happening, but maybe someone can clear this out. Tldr; is possible to different threads execute queries inside the same transaction? -
Dango API "request count" now showing in Azure App Insights > Performance with opencensus
running into an issue where my Django python API application is not logging all metrics to Azure App Insights using opencensus. But for example, we are getting CPU/memory logging: I would expect the performance > request count to look similar to this (on a different application framework): The performance counters section looks pretty straight forward. My code looks like this: from opencensus.ext.azure import metrics_exporter def main(): INSTRUMENTATION_KEY = os.getenv("INSTRUMENTATION_KEY", "xxx") exporter = metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey='+INSTRUMENTATION_KEY) -
How to call OneToOneField reverese relationship in template (django)?
I have these models in my models.py User Model class User(AbstractBaseUser, PermissionsMixin): """Custom user model""" email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) UserInfo Model class UserInfo(models.Model): """User's Info""" user = models.OneToOneField(User, related_name="parent_user", on_delete=models.CASCADE) image = models.ImageField(upload_to=user_image_file_path) age = models.IntegerField() bio = models.CharField(max_length=400) My-template In my template i am passing some filtered User Profiles(let's say filtering by age, if age > 25 ) now i need to show the name of the user(first_name) as well but i don't know how to call a OneToOnefield reversely. Help is really appreciated :). {% for p in profiles %} <div class="profile-container" style="position: relative"> <div class ="left-div"> <div class="mySlides fade"> <img src="media/{{p.image}}" style="width:100%" id="user-media-img"> <div class="text">User First Name is : {{`What to type here?`}} </div> </div> </div> <div class="right-div"> <div class="details"> <h1>BIO</h1> <p>{{p.bio}}</p> <h1>Age:</h1><p>{{p.age}}</p> </div> </div> {% endfor %} Thanks :) -
Celery tasks aren't running in django
I'm just starting out with celery, hoping to build out something better, but I can't even get the test to work. Is there something I'm doing wrong here? I'm using Docker, and I'm running both beat and worker settings.py # Celery settings BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' core/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) core/tasks.py from celery import Celery from celery.schedules import crontab from celery.decorators import periodic_task app = Celery('tasks', broker='redis://localhost//') @periodic_task(run_every=timedelta(minutes=1)) def update_keep_alive(self): logger.info("running keep alive task") statsd.incr(statsd_tags.CELERY_BEAT_ALIVE) @periodic_task( run_every=(crontab(seconds=10)), name="task_save_latest_flickr_image", ignore_result=True ) def task_save_latest_flickr_image(): print("Tester") logger.info("Saved image from Flickr") @app.task def see_you(): print("See you in ten seconds!") app.conf.beat_schedule = { "see-you-in-ten-seconds-task": { "task": "periodic.see_you", "schedule": 10.0 } } -
TypeError: post() missing 1 required positional argument
I'm trying to edit data from a table in a template: I click on "Edit" button but I get this error: post() missing 1 required positional argument: 'folio' Here is my urls.py from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.conf.urls import url from django.urls import path, include, re_path from . import views from django.views.generic.base import RedirectView app_name = 'oficios' urlpatterns = [ path('', views.lista_oficios, name="list"), path('crear/', views.crear_oficio, name="crear"), path('dependencia/', views.agregar_dependencia, name="dependencia"), path('editar/', views.EditarOficio.as_view(), name="editar"), path('editar/<str:folio>/', views.EditarOficio.as_view(), name="editar"), ] My views.py: @method_decorator(login_required, name='dispatch') class EditarOficio(CreateView): model = Oficio fields = ['folio', 'usuario', 'asunto', 'estatus', 'documento', 'dependencia', 'turnado'] def get(self, request, folio): oficio = Oficio.objects.get(id=folio) form = forms.CreateOficio(instance=oficio) context = { "form": form, "title": "Editar oficio " + oficio.folio } return render(request, "editar_oficio.html", context) def post(self, request, folio): oficio = Oficio.objects.get(id=folio) print(oficio) form = forms.CreateOficio(request.POST, request.FILES, instance=oficio) context = { "form": form, "title": "Editar oficio " + oficio.folio } if(form.is_valid()): oficio = form.save(commit=False) oficio.save() return redirect('oficios:list') return render(request, "editar_oficio.html", context) My models.py: class Oficio(models.Model): class Estatus(models.TextChoices): NUEVO = 'NU', _('Nuevo') NO_REVISADO = 'NR', _('No Revisado') LEIDO = 'L', _('Leido') SEGUIMIENTO = 'S', _('Seguimiento') COMPLETADO = 'C', _('Completado') folio = models.CharField( primary_key=True, max_length=10, unique=True, null=False) usuario = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT) fecha … -
Cannot edit fields of django's formets empty_form in views
I'm using empty_forms from Django's BaseFormset in order to dynamically append inline forms to a parent. Works fine for edit/create view. Now however I need to implement, in essence, a DuplicateView. I'm basically using a CreateView, tweaking it in get_context_data() to populate it with the object to duplicate. Something like this: def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) self.object = self.model.objects.get(pk=self.kwargs["pk"]) logger.info(f"ProduitDuplicateView.get_context_data - object id/code: {self.object.pk} {self.object.no_prod}") if self.request.POST: # code else: ctx["form"] = ProduitForm(instance=self.object) fourprodfrmset = FourProdFormSet(instance=self.object) casefrmset = CaseFormSet(instance=self.object) I do need to set the instance to self.object, because I want to populate existing inline forms for the base object to be duplicated with the relevent data. However, that inlineform includes a foreign key to the parent object, which by default is set to the parent object's pk value. For the form instance, I set it to none like so: for f in formset: try: f.initial.pop("fk_produit") f.fields["fk_produit"].initial = None except KeyError as ex: logger.info(f"There was no fk_produit in form.initial for this form of the formset") That works fine for the form instance. However, I also need to do the same with the empty_form - otherwise, when I append the emtpy_form to my inline formset, then it is set to … -
Django rest framework updating nested serializers
I have two models, one with a foreignkey relationship to the other. I am wanting to be able to create or update multiple entries at the same time. I would not be creating and updating simultaneously. I keep getting a bit confused about what is going on with people's examples. I was hoping someone could not only show me what I need to do, but also give a bit of an explanation about what is going on at each step. I'm specifically not understanding what the validated_data.get() method is doing, or what exactly is an instance, and what is being done with them. class ExtraFieldsSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = ExtraFields fields = [ 'id', 'job', 'custom_data', ] class JobWriteSerializer(serializers.ModelSerializer): extra_fields = ExtraFieldsSerializer(many=True) class Meta: model = Job fields = [ "extra_fields", "custom_data_fields", ] # Make JobSerializer able to create custom fields. def create(self, validated_data): extra_fields = validated_data.pop("extra_fields") user = User.objects.get(id=self.context['request'].user.id) client = Client.objects.get(user=self.context['request'].user) new_job = Job.objects.create(user=user, client=client, **validated_data) new_job.save() for field in extra_fields: new_field = ExtraFields.objects.create(job=new_job, custom_data=field['custom_data']) new_field.save() return new_job # Make JobSerializer able to update custom fields def update(self, instance, validated_data): pass -
Django InconsistentMigrationHistory with fresh restore
I am having trouble with migrations from this new dump that I received from my test server. This is the error that I am getting in the terminal after I execute the command python manage.py migrate. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration rmas.0001_initial is applied before its dependency equipment.0002_auto_20210629_1540 on database 'default'. I have been looking through some of the other related questions in StackOverflow and I have done about every suggestion including: drop the database delete django_migrations comment out admin in urls.py make sure that AUTH_USER_MODEL is in the .py files for dependency issues migrations.swappable_dependency(settings.AUTH_USER_MODEL) This is after running the command python manage.py showmigrations and you can see that it is just this one file that is causing a whole lot of issues. equipment [X] 0001_initial [ ] 0002_auto_20210629_1540 guardian [X] 0001_initial inspections [X] 0001_initial [ ] 0002_auto_20210629_1540 notifications [X] 0001_initial pendingsrns [X] 0001_initial [X] 0002_pendingsrn_verified_srn product_support (no migrations) repairs [X] 0001_initial [ ] 0002_auto_20210629_1540 reversion [X] 0001_initial rmas [X] 0001_initial For context if you need it: Django version = 1.11.24 Python version = 2.7 PostgreSQL 12 Please let me know if you need any additional information in order to make sense of this. Thank you. -
What are the consequences of omitting is_staff from AbstractBaseUser?
For example, if I'm trying to create a model for an existing User table in my DB which doesn't have a column for is_staff, email, last_login etc, so I omit those in my AbstractBaseUser, would it be allowed? Would some functionality not work? For AUTHENTICATION_BACKENDS I'm using 'django.contrib.auth.backends.AllowAllUsersModelBackend' so I don't need is_staff for any purpose I can think of. -
How to use Celery primitives with remote tasks?
I would like to use celery's workflows such as group and chords on tasks located on another system. Currently using send_task() to execute these tasks, but now in need to group a multitude of these remote tasks. Also interested to know if group has its own id field to refer to. I've looked through Celery docs but can't seem to find anything to do with using primitives with remote tasks. -
401 Authentication when making request involving another url
I am trying to make a get request to my django backend but when I do i get a 401 and this is after i have logged in already. console.log(this.state.logged_in) try{ let response = await axios.get(`http://127.0.0.1:8000/Anime_Creator_App/videos/${id}/`) console.log(response.data) this.setState({ search_results: response.data, }); } catch (er){ console.log('ERROR in get_SearchResults', er) } }``` ```CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://127.0.0.1:8000', ) JWT_AUTH = { 'JWT_RESPONSE_PAYLOAD_HANDLER': 'Anime_Creator_App.utils.my_jwt_response_handler' }``` ```def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data }``` -
Store dynamic variables in Django globally
How to store variables globally in Django, so I can access the variables from ALL Django files? When declaring a variable as global in views.py for instance, it doesn't have the same memory in other files including routing.py>consumers.py. Note: I am using websockets and channels. The variable to be stored is a list with classes (clients) with their individual socket connection (not websocket), so it is not possible to store it in a database. I am making a webversion of a reverse shell. The victims/clients will then connect to the server and I will be able to send commands to them through the socket connection. It works perfectly fine in a regular terminal, as it is where I created the project in the beginning. Does someone know how to do this? all_clients = [] class Client(): def __init__(self, clientSocket, name, ip, port, permission, time_when_connected): self.clientSocket = clientSocket self.name = name self.ip = ip self.port = port self.permission = permission self.time_when_connected = time_when_connected -
These messages pops up when I'm running a django project
Import "django.http" could not be resolved from source Import "django.urls" could not be resolved from source Import "django.shortcuts" could not be resolved from source Import "django.contrib" could not be resolved from source -
"Expected a string value" on login using Django REST and pyjwt
So, I'm trying to build simple register and login functionalities into my API. I can register just fine, but when I insert the user details on the login API view page, it gives me the "Expected a string value" error. I think this is probably because one of the credentials being passed somehow doesn't get stringified? I'm really not sure and I can't find much about it. Here's my code! views.py from django.shortcuts import render from rest_framework.generics import GenericAPIView from .serializers import UserSerializer, LoginSerializer from rest_framework import status from rest_framework.response import Response from django.conf import settings from django.contrib import auth import jwt class RegisterView(GenericAPIView): serializer_class = UserSerializer def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginView(GenericAPIView): serializer_class = LoginSerializer def post(self, request): data = request.data username = data.get('username', '') password = data.get('password', '') user = auth.authenticate(username=username, password=password) if user: auth_token = jwt.encode({'username': user.username}, settings.JWT_SECRET_KEY, algorithm="HS256") serializer = UserSerializer(user) data = {"user": serializer.data, "token": auth_token} print(auth_token) return Response(data, status=status.HTTP_200_OK) ### SEND RES return Response({'detail':'Invalid Credentials'}, status=status.HTTP_401_UNAUTHORIZED) serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True) email = serializers.EmailField(max_length=220) username = serializers.CharField(max_length=50) class Meta: model = User … -
Django url passing more than one parameter
in my django project i create in urls.py file an entry like this one: .... url(r'^pd/<str:df>/<str:dt>/<int:v_id>/<str:interval>', calc_q), ... because i need to pass different params to my calc_q function. Well when i start my django project and try to call my url: http://127.0.0.1:8000/pd/2021-06-27/2021-06-29/17/15min/ i get an error: ... ^pd/str:df/str:dt/int:v_id/str:interval ... The current path, pd/2021-06-27/2021-06-29/17/15min/, didn't match any of these. Why djngo cannot find my url in url list? So many thanks in advance -
Why does Heroku postgres not change after attempt to create object?
I'm creating a website for flashcards and after pushing my work to Heroku my website was working fine until I realised I couldn't create any cards. I'm not getting any errors in the logs either. When I click the submit button to create it just reloads the page with the information I've already filled in and does nothing else. Weirdly however, I was able to create an account, login, logout, and view my profile. So the database is, at least to some extent, working. Also I have switched to development to check if everything was still working and yes, everything is fine so this is definitely a Heroku problem. This is what I get in the logs followed by a sea of GET requests (I replaced some of the useless or sensitive data with triple dots like so ...) ... heroku[router]: at=info method=POST path="/create-card/" host=... request_id=... fwd="..." dyno=web.1 connect=0ms service=54ms status=200 bytes=7835 protocol=https ... app[web.1]: ... - - ... "POST /create-card/ HTTP/1.1" 200 7413 "https://my-app.herokuapp.com/create-card/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/... Safari/..." -
Django POST issue
I' ve been struggling with this for a while: I've create a Django App and have these models: Seasons Participants Objectives Partic_Obj Movements_Obj "Partic_Obj" is the table that join "Participants" and "Seasons". "Movements_Obj" is the table that i can't populate and should be containing the next data: When you add a participant, it need to create automatically one register in "Movements_Obj", for every objetive that corresponds to the season the participant is in. For example: A participant is included in Season 1, which has 5 objectives, then, when i add this participant to "Partic_Obj" i need the 5 registers to be created automatically in "Movements_Obj". Hope you can help me. Thanks! -
Huey ``db_task`` successfully registered by consumer but does not receive/execute any task
I have a Django project with huey as task queue. In my dev environment (see below), everything works as expected: [save] Django model instance saved [trigger] huey task triggerd [execute] huey task gets executed by running consumer (run_huey) But I could not get the third point [execute] working in my production environment. The only difference is DEBUG = False and the consumerrun_huey started by a systemd service unit (see below). The consumer does correctly recognize the db_task "schedule_virusscan", but does not pick up/receive any task triggered by my model save method (here: schedule_virusscan(self.id)) I use immediate=False for my huey instance, as I run run_huey even in my dev environment. I get this behavior for huey.FileHuey and huey.SqliteHuey. Question What am I missing that my consumer (only on production) does not execute or even receive any task? Setup # settings.py DEBUG = False # True in dev environment HUEY = { 'huey_class': 'huey.FileHuey', 'path': '/tmp/huey', 'immediate': False, 'immediate_use_memory': False, 'consumer': { 'workers': 2, # use 2 threads }, } # my-huey-systemd-service-unit.service [Unit] After=network.target [Service] Restart=always WorkingDirectory=/path/to/project ExecStart=/path/to/venv/bin/python3 \ /path/to/project/manage.py run_huey \ --logfile=/path/to/project/wagtailapiforms-huey.log ExecReload=/bin/kill -s SIGHUP $MAINPID ExecStop=/bin/kill -s SIGINT $MAINPID [Install] WantedBy=default.target # project/apps/core/tasks.py from huey.contrib.djhuey import db_task @db_task() def schedule_virusscan(attachment_id): … -
I want to use django with celery (redis). Do I need to install redis on the server of my django application ? or can I have a seperate redis server?
I installed redis on an ubuntu server following these guidlines. I want to use it with celery for a Django application. My Django application is running on another server. Now I'm confused however on how to set the Django settings, since everywhere I looked I could only find writings about a "localhost". Is it possible to use celery and django with redis on another server ? What Django settings.py do I need to add ? So how do -
django-webpack points to localhost in production
I use vue and django webpack loader for rendering a vue app in django template. it works well locally, but when I deploy it, it goes all wrong In template I have this: {% load render_bundle from webpack_loader %} {% render_bundle "chunk-vendors" %} {% render_bundle "app" %} which in production is rendered like that: <script type="text/javascript" src="http://localhost:8080/js/chunk-vendors.js" ></script> <script type="text/javascript" src="http://localhost:8080/js/app.js" ></script> The vue.config.js looks like that: const BundleTracker = require('webpack-bundle-tracker') const path = require('path'); const DEPLOYMENT_PATH = '/static/dist' module.exports = { publicPath: process.env.NODE_ENV === 'production' ? DEPLOYMENT_PATH : 'http://localhost:8080/', outputDir: '../_static/dist', configureWebpack: { plugins: [ new BundleTracker({path: __dirname, filename: 'webpack-stats.json'}), ], }, "transpileDependencies": [ "vuetify" ], chainWebpack: config => { config.resolve.alias .set('__STATIC__', 'static'); config.devServer .public('http://localhost:8080') .host('localhost') .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .headers({ "Access-Control-Allow-Origin": ["*"] }); config.module.rules.delete('eslint'); }, } `` -
Auto Scrollable table is not working on Heroku
I'm working on on this auto scrollable text on my first django project, and it's running just fine locally but once deployed on Heroku, the text will show up as fixed and without format. table.scrollable-content tbody tr{ overflow:auto; display:block; height:200px; } table.scrollable-content tbody tr div{ animation-name: example; animation-duration: 5s; } table.scrollable-content tbody tr:hover div{ animation-name: example2; animation-duration: 5s; } {% load static %} <!DOCTYPE html> <html lang="en"></html> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <table class="scrollable-content"> <thead><tr><th>Lorem ipsum dolor sit amet</th></tr></thead> <tbody> <tr> <td> <div> llentesque imperdiet felis congue turpis porttitor, quis mollis quam viverra. Ut placerat mauris sit amet ante dictum, non tempor turpis gravida. Donec euismod, purus quis rutrum facilisis, mi metus sodales quam, non egestas odio quam semper libero. </div> </td> </tr> </tbody> </table> -
MYSQLCLIENT on MacOs
enter image description herei was trying to setup my django project and to migrate data i needed to install mysqlclient. i tried so much things to do fix but its still not working!! when i run brew search mysql it shows mysql-client installed but when i go on my django project and run python3 manage.py runserver it still shows did you installed mysqlclient then i tried pip install mysqlclient but still so many errors i dont understand what to do, im super pissed now my classes on hold because i cant continue without mysql client. im super newbiee in developement. PLEASE HELP! look error in attached picture in below link -
Access denied for user when running django tests
My django project migrate from sqlite3 -> MySQL running on a remote server. Migration completed successfully, site is working correctly, but i have problem with tests: alex@alex-YOGA11S:~/PycharmProjects/WebGalaxyIdent$ python manage.py test Creating test database for alias 'default'... Got an error creating the test database: (1045, "Access denied for user 'FrolovPV'@'%' (using password: YES)") -
Django UserCreationForm only displays inside my HTML file when i dont extend from my base HTML
As the title suggests im having some difficulty getting this form to display when i extend from base.html Code that doesn't display my form but displays my base.html {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Sign up</button> </form> {% endblock %} code that does display my form properly {% block title %}Sign Up{% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Sign up</button> </form> {% endblock %}