Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} -
Django Celery Beat tasks limit to number of cores,, but opening terminals I can run the same task more times
I have about 5 python web scrapers. I can open 5 terminals and run the scraper 5 times simultaneously. I have implemented Django Celery Beat, where after a single iteration the scraper waits for about 2 min and restart. Following is my problem, in the command prompt I can run 5 sessions, but via celery beat, we can only run 2 scripts at a time, because my ubuntu has only 2 cores. This to me, a waste of resources. We love Celery, but we can open 5 terminals and a cron call can run the 5 different scrapers concurrently. We are basically using celery as a periodic cron job. Are we doing anything wrong? Do we have to ditch Celery? Can we deploy multiple workers? The server has enough resources to run more than 2 python scripts. Can you help? Thank you very much -
Django Admin: Limit size of read-only field in tabular inline
It seems that Django happens to just use a Tag for read-only text fields inside forms (at least tabular inlines in admin forms). What I want is, to display an URL inside a tabular inline (just using one line if possible). Unfortunately that URL tends to be rather long. So the best would be, when the URL would be inside some text field, where I can scroll or just select the whole content with CNTRL-A to get the link. But the field should be read-only. When I do that in the admin, it changes the whole output to and thus the URL will be displayed in full length and taking over the whole width of the screen -- and compressing other fields -- what is rather ugly. Any solution? -
Django Python - Creating a landing page with a prepopulated form
I'm working on a project for CS50's web course where users can visit a Wikepedia mock up and edit entries. Right now I'm having a hard time getting my entry's editing page to load properly. Right now I can't seem to get the 'entry' title from the Edit Button on the entry page in order for the page to load with the entry title/content. THe current implementation throws me this error "Reverse for 'edit_landing' with arguments '('title',)' not found. 1 pattern(s) tried: ['edit_landing$']" I've tried swapping out "title" for "entry" and even declaring "entry = entry" OR "entry = title" but nothing seems to work. I'm a little confused as to how django passing variable in a url still. I've tried about 4 or 5 implementations and I'm super lost on how to do it. Right now separating the edit landing and edit functionality seems to work. Any help would be appreciated. Thanks so much! Here is my code so far: views.py: def edit_landing_page(request, entry): edit = EditEntryForm({'content':(util.get_entry(entry))}) return render(request, "encyclopedia/edit.html", { {"edit":edit} }) def edit(request, entry): if request.method == "POST": util.save_entry(entry) return redirect('wiki'+entry) else: content = util.get_entry(entry) return render(request, "encyclopedia/edit.html", { "title": entry, }) urls.py: urlpatterns = [ path("", … -
Start Django development server on AWS EC2 Amazon Linux
This tutorial here shows how to start the development server on AWS EC2: ALLOWED_HOSTS=['EC2_DNS_NAME'] ... python manage.py runserver 0.0.0.0:8000 In a browser, navigate to public DNS of the instance, make sure to append port “8000” at the end and if everything was properly configured, it will show the index page of the application. For example: www.ec2dnsname.com:8000 My public IPv4 DNS is of this form: ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com So, in my settings.py ALLOWED_HOSTS=['ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com'] And run this in the EC2 terminal: python manage.py runserver 0.0.0.0:8000 However, when I try to reach this address: www.ec2-xx-xxx-xx-xxx.region.compute.amazonaws.com:8000 nothing is showing up (The page took too long to respond). Is this the complete and correct way to just try run a development server on AWS EC2? -
Build DevOps to deploy ReactJS - Django app
I am currently developing a web app where the front-end is done in React and the back-end in Django (using Django REST API to communicate the front with the back) and now is the time to deploy the first version :) So the situation is the following: The code is in BitBucket. I want to deploy it in Google Cloud Platform. I would like to create a Jenkins pipeline for CI/CD. How should I do this? Does anyone have any recommendations or guidelines? Many thanks!