Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign Key with db_constraint= False and postresql: foreign key appears to refer to wrong parent field
I am preparing tables for use in an analytics tool (Microsof Power BI). It would be helpful to show relationships between the tables to assist in report building. However, I don't want to use foreign keys with constraints because the method of data updating and integrity checking doesn't need constraints, and it will actually get in the way. Some of the alternate backends this code supports are for cloud databases that don't offer real foreign keys. I mention that because it means I am trying to define a foreignkey field like this: order_guid = models.ForeignKey("Dear_sales_header",to_field="order_guid",db_constraint=False,on_delete=models.DO_NOTHING) The migration file has this: operations = [ migrations.AlterField( model_name='sales_fact', name='order_guid', field=models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.DO_NOTHING, to='dear_zoho_analytics.Dear_sales_header', to_field='order_guid'), ), ] This table is routed to a different database python manage.py migrate --database=dear_analytics does indicate that the migration file was applied (it is 0026) Applying dear_zoho_analytics.0026_auto_20210217_2245... OK But when I inspect the postgresql schema in my IDE, the column in sales_fact is renamed to order_guid_id so it looks like I have done something wrong because this seems to reference the id field of the "parent table" dear_sales_header yet I need it to refer to dear_sales_header.order_guid which is unique but not the primary key. -
Get Response Cookies from Django redirect to SAP application VueJS
I'm working with Django 3.1 backend and Vue js frontend frameworks. The authentication is done by JWT tokens, however, I'm implementing the SSO authentication with SAML. The problem arises when I have to pass the JWT Tokens to VueJs after the SAML authentication is done. Then, the flow is something like this: View in frontend has a button to authenticate with SAML. It is redirected to http://backend/idp?=myIdp Backend go to IDP and IDP prompts to the user the credentials box. IDP redirects the successful SAML response to the backend. Backend generates the JWT for the session, log out the user, and redirected with response cookies for JWT tokens. The frontend view is shown to the user but I cannot get the cookies In the following diagram, I surrounded the part where I'm stuck (credits: https://jcbaey.com/oauth2-oidc-best-practices-in-spa) My redirected code looks like this: class Saml2JwtView(LoginRequiredMixin, RedirectView): url = "http://proxy.localhost/candidates/myServices" def get(self, request, *args, **kwargs): # Obtain JWT tokens for logged in user refresh = RefreshToken.for_user(request.user) response = super().get(request, *args, **kwargs) # Set JWT cookies response.set_cookie("access", str(refresh.access_token)) response.set_cookie("refresh", str(refresh)) # Logout session created by SAML logout(request) return response My networks show me that I'm setting the set-cookie and the 302 redirected to my … -
How to test Django Custom Forms/Views with .save() and .is_valid() form methods
I'm developing a web application and beginning to write tests for an app within the project 'users'. I'm using Python Unit-Testing and TestCase with coverage. I have approximately 83% tested so far however I can't seem to figure out how I should be testing the form.save() method. In addition to this, form.is_valid() seems to never be evaluating to true in my views.py file shown below: Views.py from django.shortcuts import render, redirect from users.forms import RegistrationForm, LoginForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate # Register view def user_register(response): if response.method == 'POST': form = RegistrationForm(response.POST) if form.is_valid(): # Can be saved once valid form.save() # Clean inputs username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') messages.success(response, f'Account created for {username}') return redirect('home') else: form = RegistrationForm() return render(response, 'users/register.html', {'form': form}) I can't post an image here but running coverage with live-server, it shows that everything after the 'if form.is_valid()' is highlighted in red as too is the single line in the else condition 'form = RegistrationForm()' This is my testing code: test_views.py from django.test import TestCase, Client from django.urls import reverse from django.contrib.auth import get_user_model from users.forms import RegistrationForm … -
What is the best way to represent this spreadsheet as a django model
I have been scratching my head, thinking about how to put this as a Django model, my concern is the column that is used to group the rest of the data. -
django.db.utils.OperationalError: no such table: characters_race
I try to run python manage.py migrate or even python manage.py makemigrations characters and i still get errors, I tried to search all of the files for this table or even a similar one and i found nothing, I even tried to delete "db.sqlite3" and "ptcache" and try the lines again and still the same error. Here is the Traceback: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( errors.extend(model.check(**kwargs)) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 1264, in check *cls._check_fields(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 1343, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 836, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 482, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 100, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line 200, in check *self._check_choices(), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line 245, in _check_choices if not self.choices: File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 291, in __bool__ self._fetch_all() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) … -
Django - User to User messaging on a website
I (and my team) am working on a university senior project which is something like a medical web app, I need to implement user to user messaging feature, like the patient to a doctor messaging and vice versa, would Django channels work for this feature? if not could you recommend anything that might help in this case? Thanks -
retrieve, update and delete by pk or id
I am using Django REST for my API, I have 2 questions: In my urlpatterns, in the retrieve, update and delete endpoints, I want to filter using an id. For some reason, I am not able to. In the update endpoint, I do not see the JSON data that is in the database Here is my views.py: from django.http import HttpResponse from django.shortcuts import render from rest_framework.response import Response from .serializers import mySerializer from .models import myModel from rest_framework import generics # Create your views here. class CreateShipment(generics.CreateAPIView): queryset = myModel.objects.all() serializer_class = mySerializer class ListPoint(generics.ListAPIView): queryset = myModel.objects.all() serializer_class = mySerializer class RetrievePoint(generics.RetrieveAPIView): queryset= myModel.objects.all() serializer_class= mySerializer lookup_url_kwarg = "id" class UpdatePoint(generics.UpdateAPIView): queryset = myModel.objects.all() serializer_class = mySerializer lookup_url_kwarg= "id" class DeletePoint(generics.DestroyAPIView): queryset = myModel.objects.all() Here is my urls.py: from django.urls import path from rest_framework.routers import DefaultRouter from .views import * urlpatterns = [ path('api/create/', CreatePoint.as_view()), path('api/list/', ListPoint.as_view()), path('api/retrieve/<int:id>', RetrievePoint.as_view()), path('api/update/<int:id>/', UpdatePoint.as_view()), path('api/delete/<int:id>/', DeletePoint.as_view()), ] Thanks. -
How do I dynamically generate link tags in header based on installed languages in Django?
For example, I have multiple languages installed and would like to dynamically generate the link tags. Preferably in my base.html's header. <link rel="canonical" href="https://example.com/{{ LANGUAGE_CODE }}{{ URL }}"/> <link rel="alternate" href="https://example.com/da{{ URL }}" hreflang="da"> <link rel="alternate" href="https://example.com/de{{ URL }}" hreflang="de"> <link rel="alternate" href="https://example.com/en{{ URL }}" hreflang="en"> This is what I am currently using but would there be a way to do this by looping all the installed languages so I wouldn't need to update the HTML each time I add another language? -
Django drf customer user model authentication over https
I have a Django project, where I'm using DRF (Django Rest Framework) with custom user model authentication. I'm using rest framework TokenAuthentication. Everything works fine over http where I send authentication request with username/password and I get back token successfully or if I send request with token and I get my data successfully. I'm in need to set up https connection (with proper ssl certificate). I already got ssl certificate installed (Ubuntu Apache2 setup) using wsgi. However once my https is enabled and I send auth request over https connection, I don't get back token and I get 404 Unauthorized. I already have below in my settings.py file ENABLE_SSL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'users', 'api', 'corsheaders' ] AUTH_USER_MODEL = 'users.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100, 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'users.serializers.CustomTokenSerializer', } REST_SESSION_LOGIN = True CORS_ORIGIN_ALLOW_ALL=True Can someone please tell me if I'm missing anything -
how can make hashtag clickable and show it in the post in Django?
User can make hashtag. Now I want to make hashtag clickable. Bellow is my Models.py for Hashtag: class Hashtag(models.Model): hashtagname = models.CharField(max_length=3000, blank=True, null=True) hashtagcount = models.IntegerField(null=True, blank=True) post_pk = models.ManyToManyField(PostUser) atetime = models.DateTimeField(auto_now_add=True) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) user_pk = models.IntegerField() and in my views.py I get all the hashtags and send it by dictionary to html as bellow codes: mosttrending = Hashtag.objects.all().order_by('-hashtagcount')[:10] and already I have a model for all the Posts as bellow class PostUser(models.Model): posttype = models.CharField(max_length=3000, default='postuser') content = models.TextField(null = True, blank= True) media_image = models.FileField(null = True, blank= True) media_video = models.FileField(null = True, blank= True) per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) datetime = models.DateTimeField(auto_now_add=True) like = models.IntegerField(null=True, blank=True) comment = models.IntegerField(null=True, blank=True) share = models.IntegerField(null=True, blank=True) user_pk = models.IntegerField() And in my html with a for loop I get all the PostUser: {% for readposts in readposts %} <p class="card-text">{{readposts.content|linebreaks}}</p> {% endfor %} How Can I make the link for hashtag and when a user click on the hashtag show the user the all the post? -
Why am I getting this "Converting circular structure to JSON\n --> starting at object with constructor" error?
I'm trying to build a like button in my React/Django/DjangoRestFramework social app, and I am getting this error when I try to post a like to the backend: "Converting circular structure to JSON\n --> starting at object with constructor 'HTMLButtonElement'\n | property '__reactFiber$295h0s4sjuq' -> object with constructor 'FiberNode'\n --- property 'stateNode' closes the circle" Here is my current code: AddLike.js import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import { addLike, deleteLike } from "./LikeActions"; function LikeButton(props) { return ( <button onClick={props.onClick}> Like </button> ) } function LikedButton(props) { return ( <button onClick={props.onClick}> Liked </button> ) } class AddLike extends Component { constructor(props) { super(props); this.state = { like: false, } } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; handleAddLike = id => { const post = { post: id }; this.setState({like: true}) this.props.addLike(post); }; handleDeleteLike = id => { const post = { post: id }; this.setState({like: false}) this.props.deleteLike(post); } render() { const like = this.state.like; let button; if (like) { button = <LikedButton onClick={this.handleDeleteLike}/>; } else { button = <LikeButton onClick={this.handleAddLike}/>; } return ( <div> {button} </div> ); } } … -
I am trying to open a csv file in django. I am facing error
My forms.py file is: class TsvFileForm(forms.Form): tsv_file = forms.FileField( label="Upload File") My view.py file is: def dummy(request): form = forms.TsvFileForm() if request.method == "POST": data = csv.reader(request.FILES['tsv_file'], delimiter="\t") for row in data: print(row) print("-------------------") context = {'form': form} return render(request, 'file_input.html', context) I am getting error iterator should return strings, not bytes (did you open the file in text mode?) -
Count the objects printed in a django template only, not the entire query set
I have a for loop, with an if condition inside, which limits what prints. A simple count, gives me all of the values in the queryset. I need a total items printed for each loop. What I'm tyring to print out is the total number of dates that each person was present for class, which is the items that the loop prints. views.py @login_required def attendance_report_student_view(request): my_title = "Attendance Report" church = request.user.church count = Attendance.objects.prefetch_related("course", "student", "attendance_date").count() attendance_list = Attendance.objects.order_by('attendance_date').filter(course__church=church) qs = Attendance.objects.distinct('student').order_by('student') attendance_filter = AttendanceFilter(request.GET, queryset=qs) template_name = "attendance_report_student_inline.html" context = {'count':count, 'attendance_list': attendance_list, "object_list": attendance_filter, "title": my_title} return render(request, template_name, context) models.py class Attendance(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE,related_name="user_attendance",) course = models.ForeignKey(Course, on_delete=models.CASCADE,related_name="course_attendance",) attendance_date = models.DateField() present = models.BooleanField() class Meta: ordering = ["-attendance_date"] unique_together = ('attendance_date','student', 'course') def __str__(self): return "%s %s %s %s" % ( self.attendance_date, self.student, self.course, self.present, ) def record_attendance_url(self): return f"/record-attendance" def edit_attendance_url(self): return f"/attendance/{self.id}/edit-attendance" def get_delete_url(self): return f"/attendance/{self.id}/delete" my template: {% extends "base.html" %} {% block content %} <h3 align="center">Search Options</h3> <form method="get"> {{ object_list.form.as_p }} <button type="submit">Search</button> </form> {% for object in object_list.qs%} {% regroup attendance by course_title as course_list %} <div class='col-20 col-md-50 mb-1 mx-auto'> <div class='card'> <div class='card-body'> <h3 … -
I'm confused about model relationships in django
ok, so I want to build a headless backend in Django and was running into issues as to how to best relate my models to achieve the desired result. I am having trouble wrapping my head around how to create the categories and then have them accessible as a selection to choose from when I want to ascribe them to a book or movie the goal is to be able to create multiple categories and select/add the correct categories to the movie or book they best fit. here's what I thought up but I don't know if I'm going to get the desired result but I think I'm missing a bit. class Category(models.Model): name = models.CharField() description = models.CharField() def __str__(self): return self.name class Movie(models.Model): name = models.CharField() category = models.ManyToManyField(Category) def __str__(self): return self.name class Book(models.Model): name = models.CharField() category = models.ManyToManyField(Category) def __str__(self): return self.name -
Github workflow error Django : ModuleNotFoundError: No module named 'widget_tweaks'
I am new to Django and also github workflows. I am working on a django project and I installed widget_tweaks via pip install django-widget-tweaks. Everything is working as expected and the tests (tests.py) run fine on the command prompt. However, I have created workflows on github and when I push the code, I get the following error: Run pip3 install --user django Collecting django Downloading https://files.pythonhosted.org/packages/75/42/f59a8ebf14be6d17438f13042c775f53d3dfa71fff973e4aef64ca89582c/Django-3.1.6-py3-none-any.whl (7.8MB) Collecting pytz (from django) Downloading https://files.pythonhosted.org/packages/70/94/784178ca5dd892a98f113cdd923372024dc04b8d40abe77ca76b5fb90ca6/pytz-2021.1-py2.py3-none-any.whl (510kB) Collecting sqlparse>=0.2.2 (from django) Downloading https://files.pythonhosted.org/packages/14/05/6e8eb62ca685b10e34051a80d7ea94b7137369d8c0be5c3b9d9b6e3f5dae/sqlparse-0.4.1-py3-none-any.whl (42kB) Collecting asgiref<4,>=3.2.10 (from django) Downloading https://files.pythonhosted.org/packages/89/49/5531992efc62f9c6d08a7199dc31176c8c60f7b2548c6ef245f96f29d0d9/asgiref-3.3.1-py3-none-any.whl Installing collected packages: pytz, sqlparse, asgiref, django Successfully installed asgiref-3.3.1 django-3.1.6 pytz-2021.1 sqlparse-0.4.1 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/runner/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/runner/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/runner/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/runner/.local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/runner/.local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'widget_tweaks' Error: Process completed with exit code … -
getting 'ArticleSitemap' object has no attribute 'get_urls' error when creating sitemap in django
follow the description on django official document and standard setup for a sitemap but got the following error: AttributeError at /sitemap.xml/ 'ArticleSitemap' object has no attribute 'get_urls' there is my urls: from django.contrib.sitemaps.views import sitemap from . import views from .sitemaps import StaticViewSitemap, ArticleSitemap, ArticleCategorySitemap sitemaps = {'static': StaticViewSitemap, 'article': ArticleSitemap, 'article-category': ArticleCategorySitemap} urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] there is my sitemaps.py: from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from iman_articles.models import Article, Category class StaticViewSitemap(Sitemap): def items(self): return ['home'] def location(self, item): return reverse(item) class ArticleCategorySitemap(Sitemap): changefreq = 'never' priority = 0.5 def items(self): return Category.objects.all() class ArticleSitemap(): changefreq = 'monthly' priority = 0.5 def items(self): return Article.objects.filter(active=True) def lastmod(self, obj): return obj.edited_at -
Django-Elasticsearch-DSL Range Query
I'm trying to implement the following Elasticsearch query using django-elasticsearch-dsl and am having some difficulty Query { "query":{ "nested":{ "path":"ip_addresses", "query":{ "bool":{ "filter":[ { "range":{ "ip_addresses.ip":{ "gte":"192.168.1.0", "lte":"192.168.1.255" } } } ] } } } } } Code def search_ip_range(self, start: str, end: str): range_query = Q('range', gte=start, lte=end) search = Search() search = search.query('nested', path='ip_addresses', query=range_query) try: response = search.execute() pprint("Found {} results".format(response.hits.total.value)) for hit in response: pprint(hit.detail_url) except Exception as e: pprint('Search error: {}'.format(e)) Error RequestError(400, 'parsing_exception', '[range] query does not support [gte]') -
I'm trying to get Saleor Django installation running
I have followed all the instructions from the saleor.io docs however, I got stuck at migrating the db. The problem is that every time I run python manage.py migrate I get this error message. I have python 3.8 installed and both GTK 2 and 3, MSYS2 but nothing seems to work. Does anyone know how to fix this issue? I have tried everything, and have no clue how to install cairo. Please help OSError: no library called "cairo" was found cannot load library 'C:\GTK\bin\libcairo-2.dll': error 0xc1 cannot load library 'libcairo.so.2': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e -
Django site hosting on Heroku "No web processes runnng"
So I tried to host my Django application to Heroku and at first it worked. Then I wanted to add some release commands so I did this: release_commands.sh python manage.py makemigrations python manage.py migrate And in my Procfile: release: bash ./release_commands.sh web: gunicorn todo.wsgi --log-file - The second line in my Procfile is unchanged, so I guessed that the error must be coming from the release commands, but that's not the case as in my heroku logs I have this: 2021-02-17T19:41:31.675215+00:00 heroku[release.6232]: Process exited with status 0 2021-02-17T19:41:31.772693+00:00 heroku[release.6232]: State changed from up to complete 2021-02-17T19:41:34.021990+00:00 app[api]: Release v11 created by user georgi.hr.dim@gmail.com This is the error message: 2021-02-17T19:41:43.594322+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=POST path="/accounts/login/?next=/" host=essentialtodo.herokuapp.com request_id=5dce4816-6343-44c3-9c8f -171e79379abc fwd="78.90.0.206" dyno= connect= service= status=503 bytes= protocol=https -
How to intergrate API calls in Django-rest framework
I'm trying to build a dashboard app using Django-rest framework and Reactjs for frontend. I'm able to produce required json files for my query. How do I edit my code so as to get different query results for different plots. For example, I have a filter for 'year', 4 types ie. 'segment' here, and 'sale/profit'. I have the required data in my database. Should I make individual query-view for every combination of API calls or is there a better way to modify my code for respective call. I'm noob in Django and have no experience working with react also. Please help. class StatSerializer(serializers.Serializer): segment = serializers.CharField(max_length=25, required=True) sale = serializers.DecimalField(max_digits=12, decimal_places=5, required=True) class Meta: fields = ('segment', 'sale') class StatList(ListAPIView): serializer_class = StatSerializer queryset = superstore.objects.filter(order_date__year=2015).values('segment').annotate(sale=Sum('sales')) def list(self, request): query = self.get_queryset() serializer = StatSerializer(list(query), many=True) return Response(serializer.data) -
how can i add Django Filter in one line by removing the label and making it placeholder?
this is my filters.py class StudentFilterSel(django_filters.FilterSet): class Meta: model=Student fields=['registrationSession','registrationNumber','studentName','applyingForClass','studentDob','studentAadharNum','fathersName','fathersContactNumber'] this is my views.py def selectedList(request): Studentss=Student.objects.filter(AdmissionStatus='Selected') myFilter=StudentFilterSel(request.GET,queryset=Studentss) Studentss=myFilter.qs return render(request,"register/selectedList.html",{'myfilter':myFilter,"Studentss":Studentss}) this is my HTML file <form method='get'> {{myfilter.form}} <button type="submit">search</button> </form> I need a lot of filters in my table but they are getting distorted and getting in multiple lines how can I remove the label and change it to the placeholder to reduce space? -
How to Intercept and Modify / Alter a Django Request URL?
I have a search box. I search for: <- blank spaces in my search box. My form validation catches this. The URL shows: ++++++++++++++++ If I search for: <script>alert(1);</script> The URL shows: <script>alert%281%29%3B<%2Fscript> The Question Where in Django can I alter / change / modify the request that determines the request URL? I'm thinking middleware but I haven't found an example. Would I have to create an entirely new HttpRequest from scratch? Why do I want to? I want to encode the URL differently. For example, strip all punctuation from the q= value, replace whitespace, strip, replace single spaces with + to have cleaner URLs. Really looking for a clear example with CODE. -
How to acces Instances in Foreginkey
I have an app with 3 models class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) .... Class FamilyGroup(models.Model): ... transaction = models.foreignkey(Transaction) ... Class Familymember(models.Model): ... transaction = models.foreignkey(Transaction) family_group = models.foreignkey(FamilyGroup) ... in another app i have a model Batch that will be a mirror of the three apps,the idea is this app will be imports that accept xlsx files with data being passed in, i have thought about how to make it through like this, but this aint working i cant make Transaction instance inside FamilyGroup get_or_create and same for FamilyMember class Batch(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) batch = models.CharField(max_length=50) transaction_chp_reference = models.CharField( max_length=50, null=True, blank=True) transaction_rent_effective_date = models.DateField(null=True, blank=True) transaction_income_period = models.CharField( max_length=11, choices=income_period_choices, null=True, blank=True) transaction_property_market_rent = models.DecimalField( help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) transaction_number_of_family_group = models.PositiveSmallIntegerField( null=True, blank=True, validators=[MaxValueValidator(5), ]) transaction_cruser = models.CharField(max_length=50, null=True, blank=True) transaction_prop_id = models.PositiveIntegerField(null=True, blank=True) transaction_state = models.CharField(max_length=50, null=True, blank=True) family_group_name = models.CharField(max_length=100, null=True, blank=True) family_group_family_type = models.CharField( max_length=50, null=True, blank=True) family_group_alloc_id = models.PositiveIntegerField(null=True, blank=True) family_group_last_rent = models.DecimalField( help_text='per week', max_digits=7, decimal_places=2, null=True, blank=True) family_group_any_income_support_payment = models.BooleanField( null=True, blank=True) family_group_cra_eligibilty = models.BooleanField( help_text='legislated', null=True, blank=True) family_group_cra_amount = models.DecimalField( help_text='per week', max_digits=6, decimal_places=2, null=True, blank=True) family_group_ftb_a = models.DecimalField( 'FTB-A', help_text='Legislated - per week', … -
my media files are shown in localhost but not on server after hosting it, django
I have E-commerce app which I created using django, and it works fine when I run it in localhost , but as soon as I host it to a linux based server it shows in console ' 404 media files. ' I already have " urlpatterns += static(settings.Media_url...) " thing in my urls.py I have done following thing in "settings.py" [ and tried many other ways , possibly not that one which will work for me.] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') BASE_DIR = os.path.dirname(os.path.dirname(file)) MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' static files are shown but not the media files. when I goto domain_name.com\admin and i click on the image it gives me this path ' The requested URL /media/Data/shoes_nike.jpg was not found on this server. ' and in url section 'https://domain_name.com/media/Data/sdfghj.PNG' and on server my project folder is stored in following order home > labelbyk > modaz > >main >media >modaz >db >manage.py -
Why not receiving post body dict - Django
I'm using manual built form (not the Forms.form or ModelForms.form) in Django. <div class="container"> <div id="tabs-contents"> <div id="infos" class="tab-content"> <form action="/page/" method="POST"> {% csrf_token %} <div class="infos-form-content"> <div class="infos-row-1"> <input id="field1" type="text" value="" name="field1"> <input id="field2" type="text" value="" name="field2"> </div> <div class="infos-row-2"> <input id="field3" type="date" value="" name="field3"> </div> ... ... </div> <button type="submit">Save</button> </form> </div> </div> </div> And it contains also dynamic input fields (created by JavaScript). When I check the request.body type in the view (after decoding of course request.body.decode('utf-8')) I find it's a string and not a dictionary. Why is that happening ? And how to receive the form data in dict ?