Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to set user create article is by user is logon
class Article(models.Model): slidenumber = models.AutoField(primary_key=True) title = models.CharField(max_length=255) category = models.CharField(default='', max_length=30) description = models.TextField(default="") timeupdate = models.DateTimeField('Date Published') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False, default=1) If I set author field has default=1, when I login django admin page to create a article it will alway get author is my superuser (has ID =1), so How I can set if I login admin django page to create article by other user(not my superuser), the author field will get user is logon current. -
Django-tables2 : usage of linkify to point to the record itself
I am converting a small application by replacing handcrafted html-tables by django-tables2. But I am unable to add 2 linkify links (detail & update) towards separate pages. Django 3.2.4 django-crispy-forms 1.12.0 django-filter 2.4.0 django-tables2 2.4.0 models.py class Environment(models.Model): name = models.CharField(max_length=10) description = models.TextField(max_length=100, help_text="Enter a brief description") envType = models.CharField( max_length = 32, choices = ENVIRONMENT_TYPES, default = "D" ) def get_absolute_url(self): return reverse('environment-detail', args=[str(self.id)]) urls.py urlpatterns = [ path('', views.index, name='index'), path('environments/', views.EnvironmentList.as_view(), name='environments'), path('environment/<int:pk>', views.EnvironmentDetailView.as_view(), name='environment-detail'), path('environment/create/', views.EnvironmentCreate.as_view(), name='environment-create'), path('environment/<int:pk>/update/', views.EnvironmentUpdate.as_view(), name='environment-update'), ] views.py class EnvironmentList(PagedFilteredTableView): # based on https://stackoverflow.com/questions/25256239/how-do-i-filter-tables-with-django-generic-views model = Environment table_class = EnvironmentTable filter_class = EnvironmentFilter formhelper_class = EnvironmentListFormHelper forms.py class EnvironmentListFormHelper(FormHelper): model = Environment form_tag = False # Adding a Filter Button layout = Layout('envType', ButtonHolder( Submit('submit', 'Filter', css_class='button white right') )) tables.py class EnvironmentTable(dt2.Table): # https://github.com/jieter/django-tables2/commit/204a7f23860d178afc8f3aef50512e6bf96f8f6b name =dt2.Column(linkify = True) edit = dt2.Column(default="edit",linkify=lambda record: record.get_update_url()) #edit = dt2.LinkColumn('environment-update', args=[A('pk')]) class Meta: model = Environment template_name = 'django_tables2/bootstrap-responsive.html' attrs = { 'class': 'table table-bordered table-striped table-hover', 'id': 'environmentTable' } fields = ("name", "description", "envType", "edit" ) per_page = 7 environment_list.html {% extends "base_generic.html" %} {% load render_table from django_tables2 %} {% load crispy_forms_tags %} {% block content %} <h1>Environment List</h1> <br> <a href="{% … -
how to login automatically after signup in django class base view
i want to login automatically user when successful signup. but my code return anonymous user now so, i use CreateView in django CBV views.py class SignUpView(CreateView): template_name = 'users/signup.html' success_url = reverse_lazy('users:email_confirm_notice') form_class = CustomUserCreationForm def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) and i try it def form_valid(self, form): form.save() new_user = authenticate(username=form.cleaned_data.get('username'), password.cleaned_data.get('password1') login(self.request, new_user) return super().form_valid(form) success_url is TemplateView that is just display templates and customusercreationform change error message. it is expected that there will be no changes from the first function. What's my problem? -
Is there any method to find (resume, job posts) documents score matching based on NLP with django and react
I have created an API for uploading resumes and job descriptions. Now I have to match both uploaded files for n number of resumes for the respective job profiles. Views.py - I have to get only one job id and matching all resumes and it has to give scores for all profiles this way I'm planning. class Score(APIView): queryset = Resume.objects.all() serializer_class = ResumeSerializer def get_object(self): id = self.request.id return JobDescription.objects.filter(id=id) def get_queryset(self, request): """ Return a list of all Resumes. """ data = [x for resumes in Resume.objects.all()] return Response(data) def get_score(resumes,job_description): x = calculate_scores(Resumes,Jobs) return Response(x) urls.py - looks like this way from django.urls import path,include from . views import ResumeViewSet,JobViewSet,Score from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'resume', ResumeViewSet) router.register(r'job', JobViewSet) router.register(r'score', Score) urlpatterns = [ path('', include(router.urls)), ] Calculate the score is a function of the NLP module to compare both documents. Is there any method or how I can solve this problem For more info about the NLP, model go through this link - https://github.com/srbhr/Naive-Resume-Matching -
Django restapi Axios fetch to vuex - than trying to read updated object in other vuex module
I am trying to find a way to communicate with my database so would be accesible for all of the Vuex instance. This is my code for fetching the data with axios: import { getAPI } from '../../../axios-api' const staticpages = { state: { pages: [] }, actions: { loadData({ commit }) { getAPI('/pages/').then((response) => { // console.log(response.data, this) commit('updatePages', response.data) commit('changeLoadingState', false) }) } }, mutations: { updatePages(state, pages) { state.pages = pages }, changeLoadingState(state, loading) { state.loading = loading } }, getters: { getAllStaticPages : (state) => state.pages } } export default staticpages; Than in my App.vue which is the first instance of vue to be initialized i have this code inside my created lifecycle hook to start fetching the data: created() { this.$store.dispatch("loadData"); }, Everything works fine and i see the updated state data in vue developer tools: enter image description here Then i try to access this data in other module of vuex and here is the problem. I import staticpages with import: import staticpages from "../front/frontstaticpages"; when i console log staticpages i see something like this console log of staticpages so even inside vuex module everything seems to be fine. Than i console log staticpages.state … -
Error occurs during migrating the models in django
I am trying to make migrations when saving the models.py. I came across this error and I am at a complete loss. I am creating a database that saves all the employees details in an excel sheet. For instance, when any employee submits a file upload, all of the files will be saved to excel automatically. This is the error I came across. PS python manage.py makemigrations No changes detected PS python manage.py migrate Operations to perform: Apply all migrations: EmpDBUpload, User, admin, auth, contenttypes, sessions Running migrations: Applying EmpDBUpload.0002_auto_20210715_1226...Traceback (most recent call last): File "C:\Users\18050478\Desktop\Workspace\PCUpdated\PCUpdated\manage.py", line 22, in <module> main() File "C:\Users\18050478\Desktop\Workspace\PCUpdated\PCUpdated\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) self.effective_default(create_field) File "C:\Users\18050478\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 310, in … -
Where to begin: transciption webapp/software
I have an idea for a transcription application that will help me with my job. I am a novice programmer and haven't done any programming application for a while now. Please be patient if this seems like a dumb question. I could do with some pointers as to how to approach this. I have experience using django python to build simple webapps in the past, so if I'd prefer to start this project using these tools if possible. I want to have a program or webapp where users can load a video with subtitles from their device. I want to be able to play the video for the duration of one subtitle line. (I use Aesisub at the moment which has a similar function.) My initial idea is to load this in a web browser. Users should be able to play one section of a video with subtitles, line by line, with the option to skip back and forth to the next lines of dialogue. The app will show the video and subtitles. Could anyone give any advice on the simplest way to build such an app? Should I be thinking about a chrome extension? Would it be difficult to … -
How to get the current and local date and time in Django?
I want to get the local time, so I tried the following codes in my Django shell. from django.utils import timezone now = timezone.localtime(timezone.now()) date = now.date() time = now.time() ## from datetime import datetime now = datetime.now() >>> print(now) datetime.datetime(2021, 7, 15, 4, 13, 49, 624395) In both cases, I got the wrong time, but if I use the same code in my terminal as python code, I get the current and local time. >>> datetime.now() datetime.datetime(2021, 7, 15, 8, 22, 50, 316528) >>> -
Django rest API. , I have a task for getting an internship in python/Django . Can you help me to solving this task?
Design a DB and an API server in Django that has the following functionality: -
Filtering MYSQL pull using datetimefield model django
I have been having a hard time finding a solution specific to filtering a model get from a mysql db. models file: class PreviousLossesMlbV5WithDateAgg(models.Model): game_points_with_formula_field = models.FloatField(db_column='GAME POINTS WITH FORMULA:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. date_field = models.DateTimeField(db_column='DATE:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. class Meta: managed = False db_table = 'previous_losses_mlb_v5_with_date_agg' views file def indexsss(request): PreviousLossesMlbV5WithDateAgg.objects.values_list('game_points_with_formula_field',flat=True).filter(date_field= '2021-07-05') monday_list = list(monday_new) return render(request, "show4.html", context={'test45': monday_list} ) The data does not populate and also shows this in the terminal DateTimeField PreviousLossesMlbV5WithDateAgg.date_field received a naive datetime (2021-07-05 00:00:00) while time zone support is active. -
How do I change the format of the permissions field in the outputted fixture for the dumpdata command?
When I create data fixtures for user groups using the dumpdata command: python manage.py dumpdata auth.Group --indent 4 > fixtures.json I get the ids of the permissions (23, 25, 26) in the following format: { "model": "auth.group", "pk": 7, "fields": { "name": "Subscribers", "permissions": [ 23, 25, 26 ] } } How do I get it to be in the format below for the permissions field? { "model": "auth.group", "pk": 7, "fields": { "name": "Subscribers", "permissions": [ ["add_location", "main", "location"], ["change_location", "main", "location"], ["delete_location", "main", "location"] ] } } I looked up the documentation but couldn't find anything on this. -
Difference between shortcut reverse and url reverse in Django
I am learning django. And recently I have came upon something that I don't understand. There are two different version of reverse module that can be imported. One is: from django.shortcuts import reverse Another is: from django.urls import reverse What are the actual difference between them? Can someone explain to me in an easy way? -
Django cannot find specified path for FilePathField
Trying to use FilePathField for my images, but my application returns the following error: FileNotFoundError at /api/projects/ | [WinError 3] The system cannot find the path specified: 'portfolio/img' settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') models.py class Tech(models.Model): name = models.CharField(max_length=100, null=False) icon = models.FilePathField(path="portfolio/img") class Project(models.Model): title = models.CharField(max_length=100, null=False) desc = models.TextField() image = models.FilePathField(path="portfolio/img") tech = models.ForeignKey(Tech, on_delete=models.CASCADE, null=False) And my current file hierarchy: back core portfolio static portfolio img manage.py -
VM101:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I am using Sandbox for payment testing. Everything works fine till payment and the console throws an error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 The error points to this line of code at the fetch. I am not sure what's wrong with the Django app. I even have initialized URL at the top: var url = "{% url 'payments' %}" onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(details); sendData(); function sendData(){ fetch(url, { method : "POST", headers: { "Content-type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ orderID: orderID, transID: details.id, payment_method: payment_method, status: details.status, }), }) .then((response) => response.json()) .then((data) => { window.location.href = redirect_url + '?order_number='+data.order_number+'&payment_id='+data.transID; }) } }); } -
Convert SQL string into Model datetime in django
I'm using Django rest framework to expose a database as API, The database was created manually before the Django implementation. By error, a charfield is storing a DateTime data as a string, My model is unmanaged so that the database structure is not changed, however, I need to use the DateTime field as DateTime, not as a string so that I'll be able to filter the records by date. Can anybody help me out to check how to cast the value as datetime? Thanks in advance. -
Django only able to handle 3 actions at same time?
Hello apologies as I am incredibly new to Django. I have a Django site deployed to an AWS ec2 with Gunicorn and Nginx. Essentially within the app the user clients a button some python code kicks off and ~10 seconds later the work is done. This works perfectly until there are more than 3 actions going on at the same time. If I were to open 3 tabs and click 3 buttons at roughly the same time, the entire site can't do anything else. No other pages will load or anything. The aws EC2 has 2 codes. Gunicorn is set to 5 workers. I tried increasing the size of the ec2 to an instance with more cores thinking that might be it but unfortunately no dice. Would anyone have a clue what might be going on? -
Django Direct assignment to the reverse side of a many-to-many set is prohibited. Use .set()
I have two models, StudyConditions and studies, and there exists a many to many relationship between the two, declared in studies. I am trying to create new conditions in my StudyConditionViewSet and link them to the studies. When doing a post request with the JSON object below, I get the error Direct assignment to the reverse side of a many-to-many set is prohibited. Use .set(). Is this just not possible, i.e I can only do this in my StudyViewSet, or is there something I'm missing/misunderstanding? There aren't many issues I've seen concerning this specific case. I've tried both study_obj.conditions.add(new_condition) and new_condition.studies.add(study_obj), trying to add the condition to the study in the first, and trying to add the study to the condition in the second. I've also tried them using set, but with no success. { "name": "Post w/ studies", "studies": [ { "id": "1" }, { "id": "2" } ] } models.py class Study(models.Model): featured = models.BooleanField(default=False) conditions = models.ManyToManyField('StudyCondition', related_name='studies', db_table='Study_Condition') class Meta: db_table = 'Study' class StudyCondition(models.Model): name = models.TextField(null=False) class Meta: db_table = 'Condition' views.py class StudyConditionViewSet(viewsets.ViewSet): def list(self, request): queryset = StudyCondition.objects.all() result = StudyConditionSerializer(queryset, many=True) if result: return Response(result.data) else: return Response(data=result.data, status=200) def retrieve(self, … -
Try to sum the incoming data
from django.db import models from django.urls import reverse from django.contrib.auth.models import User from datetime import date class Goals(models.Model): calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) user = models.ForeignKey(User, on_delete=models.CASCADE) class Macros(models.Model): name= models.CharField(max_length=100) calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) goals = models.ForeignKey(Goals, on_delete=models.CASCADE) here is my models and trying sum the macros like calories protein carbohydrates fats by += -
Django - Display a pandas dataframe into django template
everybody. I'm trying to use Django to display a pandas dataframe example, but it doesn't render. I tried use for statement, the function df.to_html, with no success. I hope you help me, I would appreciate it. views.py from django.shortcuts import render import pandas as pd # Create your views here. def index(request): df = pd.DataFrame( {'Nome': ['Beatriz', 'Ana', 'Flávia', 'Bianca'], 'Idade': [23, 24, 24, 19], 'Profissao': ['Analista de Sistemas', 'Advogada', 'Promotora', 'Jornalista'], 'Renda_mensal': [5000, 8000, 15000, 4500] }) df = df.to_html() return render(request, 'index.html') index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>Em construção</h1> {{ df }} </body> </html> Thank you since now. -
how to Extract days from DateField in django
interval = Attribute.objects.filter(Q(register_date__gte='2021-07-01')) \ .annotate(input_interval=Cast('create_at', DateField()) - F('register_date')).values('student_id', 'input_interval') The date you registered the student is register_date and the model property is DateField . The date/time that each student's enrollment date was entered into the actual program is create_at and the model property is DateTimeField . The two fields have different model properties, so I converted the create_at field to a DateField using the Cast function. And (actual input date) - (student enrollment date) was obtained. The result is as below. <QuerySet [{'student_id': 1, 'input_interval': datetime.timedelta(days=1)}, {'student_id': 2, 'input_interval': datetime.timedelta(0)}, {'student_id': 3, 'input_interval': datetime.timedelta(0)}, {'student_id': 4, 'input_interval': datetime.timedelta(0)}]> Is there a way to extract only the days value of input_interval from here? I googled and tried functions such as ExtractDay, days, etc., but the date returned using the Cast function is Is it impossible to extract... Please help. -
Django: If an object from a database is deleted do the remainer objects keep the same id/order?
This might be a stupid question but here I go: I have a SQLite database with Django. Let's say in one table i have four objects: ID=1 name=dog ID=2 name=cat ID=3 name=lion ID=4 name=rat If I were to delete an object let's say animals.objects.get(id=3).delete() Do the id's from the other objects change? Would it be: ID=1 name=dog ID=2 name=cat ID=3 name=rat They change right? I am supposing they do. And if they do is this so in other databases like MySQL? -
Logging activity django backend react
I have a react application that uses django rest framework as a backend. Problem is the server the react application is hosted on is a flask application (long story..not my monster). I would like to keep a log of activity from the react app, but I would also like to add some custom data from the react front end when these logs are generated that goes to the back end. Any help would be appreciated. -
I am using the justdjango chat app and as I follow his works suddenly I received this kind of error from django as I tried to send a message?
Traceback (most recent call last): File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\routing.py", line 71, in call return await application(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\sessions.py", line 263, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\auth.py", line 185, in call return await super().call(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\middleware.py", line 26, in call return await self.inner(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\routing.py", line 150, in call return await application( File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 58, in call await await_many_dispatch( File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\asgiref\sync.py", line 444, in call ret = await asyncio.wait_for(future, timeout=None) File "c:\users\ralphjohn\appdata\local\programs\python\python39\lib\asyncio\tasks.py", line 442, in wait_for return await fut File "c:\users\ralphjohn\appdata\local\programs\python\python39\lib\concurrent\futures\thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\asgiref\sync.py", line 486, in thread_handler return func(*args, **kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 125, in dispatch handler(message) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\generic\websocket.py", line 59, in websocket_receive self.receive(text_data=message["text"]) File "C:\Users\RalphJohn\Documents\ChatApp\source\privateChat\consumers.py", line 75, in receive self.commands[data['command']](self, data) File "C:\Users\RalphJohn\Documents\ChatApp\source\privateChat\consumers.py", line 23, in new_message author_user = User.objects.filter(username=author)[1] File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\django\db\models\query.py", line 318, in getitem return qs._result_cache[0] IndexError: list index out … -
Django floatformat with forms.FloatField objects
{{ value }} works in my template. {{ myForm.myFloatField }} works. myForm inherits from forms.Form and myFloatField is a forms.FloatField object. {{ value|floatformat:3 }} presents the value with three numbers after the decimal, as expected. {{ myForm.myFloatField|floatformat:3 }} does not work, not even rendering the field. How do I get myForm.myFloatField to present with three numbers after the decimal? -
How can i fix Django Postgresql migrations error?
I can import migrations with Sqlite3 in my Django project, but when I try to import it with postgreql, I get an error like this. How can I fix this? I installed before pip install psycopg2 pip install django psycopg2 Error conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError DB Settings Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'lordplusdb', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } }