Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django) How to get an object id in form_valid?
I am trying to make a comment form on a posting app with django, the problem is I can't seem to get it's own object's id, any idea? class MyFormView(FormView): form_class = CommentForm success_url = "/" def form_valid(self,form,*args,**kwargs): comment = form.save(commit=False) comment.message=Message.objects.get(id=???) comment.save() return super(MyFormView, self).form_valid(form) If i were to replace the ??? with for example 7, it will post every comment on message(or post) with the id 7, but I want the comment to be posted on the message i am seeing. Any help appreciated -
Please provide Django ORM query for Sql query
Need Django ORM query for below Postgres Query, Sql query has sub queries. Please explain how to write ORM for it. select arc.quantity as quantity, arc.quantity - pr.quantity as remaining_qunatity from (select d.document_number as document_number, dr.quantity as quantity, dr.sku as sku from document_rows as dr join documents as d on dr.document_id = d.id join document_type as dt on d.document_type_id = dt.id where dt.title = 'annual_rate_contract' ) as arc join (select d.document_number as document_number, dr.quantity as quantity, dr.sku as sku from document_rows as dr join documents as d on dr.document_id = d.id join document_type as dt on d.document_type_id = dt.id where dt.title = 'purchase_requisition' ) as pr on arc.document_number = pr.document_number and arc.sku = pr.sku -
I am unable to fix error while working on django project, TypeError: expected str, bytes or os.PathLike object, not function
I get the below error ..please help. Thanks in advance. this is my views.py code def details_view(request): context={} user=request.user if not user.is_authenticated: return HttpResponse('Please login') form=DetailsForm(request.POST or None, request.FILES or None) if form.is_valid(): obj=form.save(commit=False) student=Account.objects.filter(email=user.email).first() obj.student=student obj.save() form=DetailsForm() context['form']=form return render(request,'account/details.html',context) -
Django / JQuery Iterate over table updating each cell with json data
I have table rows that looks like this {% for item in items %} <tr id="labels" data-index="{{ forloop.counter }}"> </tr> {% endfor %} I get this json data: "labels": [ "A", "B", "C ", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ], Im trying to iterate over the table rows and the json data at the same time, so that I can assign each table row its label. jQuery.each(labels, function() { newlabel = this; document.querySelectorAll('#labels').forEach(function (element, index) { element.innerHTML = newlabel; }); })}, But with this all the cells have the character Z, instead of being in alphabetical order. Thank you for any help -
DRF Serializer empty OrderedDict on update()
I'm using Django 2.x and Django REST Framework class ComponentDataSerializer(serializers.ModelSerializer): class Meta: model = ComponentData fields = [ 'id', 'analytics_type' ] class ComponentSerializer(serializers.ModelSerializer): data = ComponentDataSerializer(many=True) class Meta: model = Component fields = [ 'id', 'name', 'group', 'data', ] def validate(self, attrs): print('validate data: {}'.format(attrs)) return attrs With POST request, the attrs in validate() is validate data: OrderedDict([('name', 'Component Test'), ('group', <AnalyticsGroup: Chart>), ('data', [OrderedDict([('analytics_type', <AnalyticsType: Bar Chart>)])])]) While with PATCH request, the data attribute has empty OrderedDict validate data: OrderedDict([('group', <AnalyticsGroup: Chart>), ('data', [OrderedDict()])]) The data payload in each request is the same. name: "Component Test" group: "2" data[0]analytics_type: "3" data[0]analytics_sub_type: "2" data[0]query: "9" Where value for each field analytics_type, analytics_sub_type and query is the pk respectively. -
Got a `TypeError` when calling `Article.objects.create()`
I am working on Django React Project using the Django REST FRAMEWORK,I am trying to post some data tied to my model. The list view and the detail view of the project works pretty fine,The only problem is when I try to make a POST request whenever I Try post the data in the CreateAPIView I get an error : Got a `TypeError` when calling `Article.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Article.objects.create()`. You may need to make the field read-only, or override the ArticleSerializer.create() method to handle this correctly. I have searched through various past problems but non of them seem to fix my problem. Here is my serializers file from rest_framework import serializers from articles.models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','title','content','star_count','like_count','comment_count','avatar') Here is my views file from rest_framework.generics import ListAPIView,RetrieveAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView from .serializers import ArticleSerializer from articles.models import Article from rest_framework import viewsets class ArticleViewSets(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer models file content = models.TextField() comment_count = models.IntegerField(default=0,null=True,blank=True) like_count = models.IntegerField(default=0,null=True,blank=True) star_count = models.IntegerField(default=0,null=True,blank=True) avatar = models.ImageField(null=True,blank=True) def __str__(self): return self.title def save(self): if not self.slug: self.slug = … -
Loop JavaScript in Ajax
i'm following the Django code that dynamically generates cards according to my amount of variables i have in a bank. For each card it consumes data from an API through ajax code. However, my ajax code is not being called every loop. It is called only once. What I can do is wrong, because I need ajax to be called every loop of HTML. {% block content %} <div id="auto" class="row"> {% for row in list %} {% if row.state == 1 %} <div class="col-xs-6 col-md-4"> <div class="card"> <h5 class="card-header">{{row.description}} - Temperatura Atual (˚C)</h5> <!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!--> <canvas id="myChart-{{ forloop.counter }}" class="piechart"></canvas> <script> var rowId = {{ row.id }} console.log(rowId); readTempDinamic(rowId); //refresh(); </script> <p class="text-center font-weight-bold" style="font-size: 0.7rem"><span id="datetime"></span></p> <a href="{% url 'row_details' pk=row.pk %}" class="btn botao-detalhar btn-sm">Show</a> </div> </div> {% endif %} {% endfor %} </div> {% endblock content %} function readTempDinamic(rowId) { var endpointTemp = '/api/weatherData/getSensor/1/' + rowId + '/' console.log(endpointTemp); /* ############################################################################# */ $.ajax({ method: "GET", url: endpointTemp, success: function(data){ var row = [] var value = [] var read_data = [] row = data.row value = data.value read_data = data.read_date generateGaugeCharts(row[0], read_data[0], value[0]) }, error: function(error_data){ console.log("error") console.log(error_data) … -
How to render template in Django and redirect to a certain fragment of the template?
A Django newbie question. Let's say I have a template that contains three paragraphs and I render it in views.py. Is there a way to redirect to a certain paragraph of the template using render? and if not what are my options? -
Get first -random- interation in a Wagtail Page Queryset that is not the page itself
So I am using Wagtail (a Django CMS) and I on the bottom of a page I need a next button. Which will go to a random Page that is not the current page. I am using a custom context processor for this purpose. My code: from cases.models import CasePage def random_case(request): case = CasePage.objects.live().order_by('?').first() for entry in case: if entry.get_url != request.get_full_path(): return {'random_case': case} So I want to get a random url from the CasePage object. And check it in the template wether this is the url of the current page (and skip that one ofcourse). In the template something like this: {% for entry in random_case %} <a class="ajax-link project-next" href="{{ entry.get_url }}"> <div class="nav-project-title">{{ entry.title }}</div> <div class="nav-title">next</div> </a> {% endfor %} But the above code is not working. How can I do this on the proper way to keep all the logic in the context processor and only use a for loop in the template? -
Django template with javascript rendering problem
I ran into a problem when my template contains some javascript. For instance <script>var i = /{{([a-z]*)}}/gi;</script> Sure enough the template interpreter wants to interpret everything that is in double curled braces {{}} as a variable. Now I wonder if there is a way to turn of such variable interpretation similar to {% autoescape off %}{% endautoescape %}. -
Problem with the Postgresql database installation in django
I have a problem with the postgresql database in dajngo. When I run the command "python -m pip install psycopg2" it works. So I run the command "python manage.py makemigrations", I have this issues : (env) PS C:\projects\first_project\webdev> python manage.py makemigrations Traceback (most recent call last): File "C:\projects\first_project\env\lib\site-packages\django\db\backends\postgresql\base.py", line 20, in import psycopg2 as Database File "C:\projects\first_project\env\lib\site-packages\psycopg2__init__.py", line 50, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: specified module not found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\projects\first_project\env\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\projects\first_project\env\lib\site-packages\django\core\management__init__.py", line 357, in execute django.setup() File "C:\projects\first_project\env\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\projects\first_project\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\projects\first_project\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Louise\AppData\Local\Programs\Python\Python38\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\projects\first_project\env\lib\site-packages\django\contrib\auth\models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\projects\first_project\env\lib\site-packages\django\contrib\auth\base_user.py", line … -
Video storage for a web application
Im developing an API using Python-Django and I need some way to store videos to be retrieved. Should I store the videos in a sql/no-sql db ? , or should they be retrieved in a way from a cloud-storage? or maybe firebase or google-drive? Thanks. -
How to filter SIP character correctly in Django with MariaDB?
I was trying to filter out some data from my database, but it failed filtering and eventually collected all rows from the table when filtering SIP (Supplementary Ideographic Plane) characters such as "𠋫" in ext-B, "𭨡" in ext-F. This only applies in production environment using MariaDB (utf8mb4), but it is totally normal in development environment (SQLite). mysite/settings/production.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'; SET NAMES utf8mb4;", 'charset': 'utf8mb4', 'use_unicode': True, } } } enter code here mysite/myapp/views.py def query_dzih(dzih): result = list(Dzih.objects.filter(dzih=dzih)) MariaDB MariaDB [django]> show variables like "chara%"; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ MariaDB [django]> describe myapp_dzih; +---------------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+------------+------+-----+---------+-------+ | dzih_no | int(11) | NO | PRI | NULL | | | dzih | varchar(5) | NO | MUL | NULL | | | dzihm | longtext | NO | | NULL | | | dzihs … -
KeyError: 'instance': send_activation_notification(kwargs['instance'])
I am trying to implement registration in Django and faced with error: models.py", line 20, in user_registrated_dispatcher send_activation_notification(kwargs['instance']) KeyError: 'instance' How can I solve the error? Could you recommend good tutorial about registration with email in Django? Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, isinstance=user) return user class Meta: model = AdvUser fields = ('username', 'email', 'password', 'password2', 'first_name', 'last_name', 'send_messages') urls.py from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate urlpatterns = [ path('', views.post_list, name='post_list'), … -
How to send mail after api endpoint is provoked, Django?
My application is using React for frontend and Django & Django RestFramework. I am trying to send email. It is not possible from React Side. So what I thought is to create a Model Mail here in django with class Mail(models.Model): MAIL_SENT= ( ('Y', 'Yes'), ('N', 'No'), ) send_to= models.CharField(max_length=120) reply_to= models.CharField(max_length=120) message= models.TextField() subject= models.TextField() mail_sent= models.CharField(max_length=1, default="Y", choices=MAIL_SENT) def __self__(self): return self.send_to What I want to do is create an API endpoint for Mail and send method at the time of post method. Can anyone please help me with this? -
Django app - data processing on the server
I have some question about some django app. Simple example: On the server I'd like to run some program, which should display some value. Example: for(i in range(10)): print(10**i) sleep(1) So value changes every 1 second without refreshing. It could be some progress bar etc. How to start with it? Celery is the good start? What should I look for? Best regards! -
How to merge similar data into a custom field using serializers in django-rest-framework?
I have an api which returns the material_id,material_name and it's store_id (foreign key) and store_name and it also has a search backend. So i want to return all the material_name and material_id's on one key material and similarly all the store fields in the key store. So i've tried the code below class MaterialSuggestions(generics.ListAPIView): search_fields = ['name', 'shape', 'color', 'material_type', 'surface_type', 'store__name'] filter_backends = (filters.SearchFilter,) queryset = Material.objects.all() serializer_class = MaterialSuggestionsSerializer class MaterialSuggestionsSerializer(serializers.ModelSerializer): class Meta: model = Material fields = ('material','store') material = serializers.SerializerMethodField('get_material') store = serializers.SerializerMethodField('get_store') def get_material(self,obj): return {'material_id':obj.id,'material_name':obj.name} def get_store(self,obj): return {'store_id':obj.store.id,'store_name':obj.store.name} when i call the api i get something like this: { "material": { "material_id": 14, "material_name": "test" }, "store": { "store_id": 28, "store_name": "test1" } }, { "material": { "material_id": 13, "material_name": "test3" }, "store": { "store_id": 29, "store_name": "test2" } } ] This is what I would ideally want to return. { "material": [ { "material_id": 14, "material_name": "test" }, { "material_id": 13, "material_name": "test3" } ] "store": [ { "store_id": 28, "store_name": "test1" }, { "store_id": 29, "store_name": "test2" } ] } or Even this would be great { "material": { "material_id": 14,13 "material_name": "test","test3" }, "store": { "store_id": 28,29 "store_name": "test1","test2" }, … -
Excel random tuple, Convert to python datetime format
How to convert '=RANDBETWEEN(DATE(1975, 1, 1),DATE(2015, 3, 1))' excel date format to python datetime format.its showing ["'=RANDBETWEEN(DATE(1975, 1, 1),DATE(2015, 3, 1))' value has an invalid date format. It must be in YYYY-MM-DD format."] error plz help me how to convert -
Django Form is_valid() missing 1 required positional argument: 'self'
I am trying to create a form(boqform) to post data into a model(boqmodel) but i am getting this typeerror is_valid() missing 1 required positional argument: 'self' I need to display a form called boqform on html template and post the data user entered into boqmodel my view def boqmodel1(request): if boqform.is_valid(): form = boqform(request.POST) obj=form.save(commit=False) obj.save() context = {'form': form} return render(request, 'create.html', context) else: context = {'error': 'The post has been successfully created. Please enter boq'} return render(request, 'create.html', context) -
NoReverseMatch at / in django
Hi Everyone i want to go on detail view but i get this error while paste the url NoReverseMatch at / Reverse for 'test' with no arguments not found. 1 pattern(s) tried: ['test/(?P<pk>[0-9]+)/$'] Here is my Models.py from django.db import models # Create your models here. class article(models.Model): Title = models.CharField(max_length=200) Content = models.CharField(max_length=1000) Here is my Views.py from django.shortcuts import render from django.views.generic import (ListView,DetailView) from .models import * # Create your views here. class Article(ListView): model = article class Test(DetailView): model = article Here is my Urls.py from django.contrib import admin from django.urls import path from cbs import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Article.as_view(),name="Article"), path('test/<int:pk>/', views.Test.as_view(),name="test"), ] Here is my Article_list.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% for article in article_list %} <h1><a href="{% url 'test' %}">{{ article.Title }}</a></h1> {% endfor %} </body> </html> -
How do I access a data value in a dictionary in the html template
I'm passing a dictionary in the context in my views.py to my html template. How do I know access a value in the template based on a particular key. For instance I'd wanna do something like {{ dictionary.keyname.value }} but I don't know the correct syntax and for some reason I can't seem to find the documentation. I want to achieve the same effect as this without having to use a for loop: <b>Calories</b> {% for key, value in output.items %} {% if key == "calories" %} {{ value }} {% endif %} {% endfor %} -
how to fix 'Exception in thread django-main-thread'
Here i was trying to print ''Hello world' using django MVT pattern. while running my code got below error. kindly help me to understand where i am doing wrong. expected output was "hello world" but getting below error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\sonal\Envs\test\lib\site-packages\django\urls\resolvers.py", line 586, in url_patterns iter(patterns) TypeError: 'module' object is not iterable -
django.core.exceptions.ImproperlyConfigured: . You must either define the environment variable DJANGO_SETTINGS_MODULE
I made an app djecommerce. Got an django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings in urls.py. Here is my code from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
@get data from browser,but giving lots problems
def page(request): # a = int(request.GET['num1']) # b = int(request.GET['num2']) # val = a + b val1 = request.POST.get(['num1']) a = int(val1) val2 = request.POST.get(['num2']) b = int(val2) val = a+b return render(request,'khushi/block.html',{'result':val}) -
Paging with RawQuerySet
I'm making a raw sql query using Django. I need to do pagination of the output, because for some inputs these queries return more than 100k results which takes a very long time. I cannot use Django ORM because my sql query contains interaction with quite specific postgres plugin (RDKit PostgreSQL cartridge). Currently I am fetching all the results and make the pagination only after that. However, this is really a bottleneck in my program as fetching all the results might take more than a minute for more than 100k rows. # making a specific sql statement sql = compose_sql_statement(parameters) molecules = Molecule.objects.raw(sql) paginator = Paginator(molecules, 10) molecules_page = paginator.get_page(page)