Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i override date validation in django rest framework
in my model gst_date = models.DateField(blank=True, null=True) it is an optional field, from UI it sent as gst_date = "" gst_date = null OR remove the gst_date key is working fine my question is how can I handle the empty string from Django serializer itself ?? -
unexpected output while trying to convert html to pdf in django
here is my view to which converts html to django @api_view(['GET']) @renderer_classes((JSONRenderer,TemplateHTMLRenderer)) def admin_order_pdf(request, order_id, *args, **kwargs): # def admin_order_pdf(request, order_id): queryset=D.objects.all() # serializer= order = get_object_or_404(queryset, id=order_id) price=order.price discount=order.discount total=price-discount template=get_template('bill/bill.html') data={ 'order': order,'total':total } html = render_to_pdf('bill/bill.html', data) return HttpResponse(html, content_type='application/pdf') and this is the code for render_to_pdf from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None and my urls.py re_path(r'^bill/(?P<order_id>\d+)/pdf/$', admin_order_pdf, name='admin_order_pdf'), and my html template <html> <body> <h1>My Shop</h1> <p> {% for ord in order %} <li>{{ ord.name }}</li> {% endfor %} but whenever i tried to access the url i could load the pdf but there isnt any content in that particular pdf file except a single word "profiles" i dont even know where that word came from -
How to create session in django. Please give me few links
I am trying to create a session using python and django. Could anyone please provide me a sample code. Thanks in advance. -
Django: Alter table with migration without altering values
I have a form with a phone number field. I used to have a CharField where anyone could input virtually anything, but I've changed it, using this Widget That means that I now have a widget which allows the user to select a country code and then input his phone number, and the all validation is automatic. However, the use of this widget required that I change my CharField to a PhoneNumberField in my model. I had some tweaks to do but it works fine because both fields translate into a VARCHAR(255). However, when I migrated on my testing environment, all older values in the phone field were altered, and all values that didn't correspond to the format wanted by PhoneNumberField were deleted (or to be more precise, made worthless: 00336XXXXXXXX was turned into +NoneNone). I do not want to reproduce this behavior in production environment. Is there a way to edit my migration so that it doesn't alter any value already present in the table? If not, what tweak could I use to keep older values? -
Django: POST and GET within one form? Need to record users search terms
I'm trying to save a users search history whilst they are using my website. I have created a working search bar for users to search for items in the database. I am using a GET request in my views.py and HTML to receive search results: def project_search_results(request, project_query): query = project_query results = box.objects.filter(Q(project_assigned_to__project_name__icontains=query)) return render(request, 'main_app/project_search_results.html', {'query':query,'results':results}) And the HTML: <form class="search-button" action= "{% url 'main_app:search_results' %}" method="get"> <label for="form-control"> <input class="form-control" name = "q" value="{{request.GET.q}}" placeholder="Enter asset name here"> </label> <button id = "search-button" class="btn btn-dark" type="submit"> Submit </button> </form> I would like to save these results to a model that I have made: class user_search_history(models.Model): user = models.ForeignKey(User) search_history = models.CharField(max_length=300, blank=True, null=True) date_searched = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'user_search_history' Is there some way that I could record these searches in my model despite me using a 'GET' reqeust in the form? I'm unsure as to where to go from here so any help would be massively appreciated. -
how to set config of host in channel layers using django with aws ec2?
I am making a Chat app using django channel and I am also using AWS EC2. My socket is close when i using this type of channel layer : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts":[("<my_aws_host>", 6379)], }, }, } please help me, where and how i put host key of aws in channel layer. Thanks, -
How to form a prefix with manytomany relationship in a django template
I face up with the problem of not knowing how to form the prefix concerning a manytomany relationship in my django template. As a result I can not save more than one instances in the table of manytomany relationship. Note: I am using inline forms. my model.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'ฮ ฮตฮปฮฌฯฮทฯ') preorder_date = models.DateField("ฮฮผ/ฮฝฮฏฮฑ ฮ ฯฮฟฯฮฑฯฮฑฮณฮณฮตฮปฮฏฮฑฯ",null=True, blank=True, default=datetime.date.today) notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="ฮฃฮทฮผฮตฮนฯฯฮตฮนฯ") preorder_has_products=models.ManyToManyField(Product,blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) my form.py class PreorderForm(ModelForm): class Meta: model = Preorder fields=('preorder_date','notes',) def __init__(self, *args, **kwargs): super(PreorderForm, self).__init__(*args,**kwargs) self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) #self.fields['preorder_date'].widget = AdminDateWidget() class PreorderHasProductsForm(ModelForm): class Meta: model=Preorder.preorder_has_products.through exclude=('client',) def __init__(self, *args, **kwargs): super(PreorderHasProductsForm, self).__init__(*args, **kwargs) #self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) self.fields['product'].label = "ฮฮฝฮฟฮผฮฑ ฮ ฯฮฟฯฯฮฝฯฮฟฯ" PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through, form=PreorderHasProductsForm, extra=1) The above seems to work as expected. The issue I think it has to do with the prefix in template. template <script type="text/javascript"> $('table.preorder_has_products tr.formset_row').formset({ addText: 'ฮ ฯฯฯฮธฮตฯฮต ฮ ฯฮฟฯฯฮฝ', deleteText: 'ฮฮนฮฑฮณฯฮฑฯฮฎ', prefix: 'preorderhasproducts__product_set', animateForms: true }); </script> This prefix: 'preorderhasproducts__product_set' implementation is wrong. How can i fix it in order to work? -
Saving django form as excel file with saving to db also in Django
I have code like this. It's working example of saving data specified in forms.py, and some data taken from current logged user. @login_required def save(request): if request.method == 'POST': form = ExcelForm(data=request.POST) if form.is_valid(): name = request.user.first_name lastname = request.user.last_name date = datetime.datetime.now().date() valid_form = form.save(commit=False) valid_form.firstName = name valid_form.lastName = lastname valid_form.date = date valid_form.save() return redirect('account:panel') else: form = ExcelForm(data=request.POST) return render(request, 'account/panel.html', {'form': form}) This form is saved to sqllite db. My main goal is to save this form as excel file. How can I deal with this problem ? How to pass data to the sheet and with clicking submit button in my html file saving to excel file and to database in the same time ? thanks for all answers in the future. -
how to set access control or privilege for Django models and views?
i create a model for website/ frontend . i have 3 types of users. only 1 type i want to see the frontend model. how to create a dynamic access control for the django frontends. please give some solutuion or suggest a plugin. Thanks for solution in advance. -
python django models problems
I made standard class of django.model class Standard(models.Model): name = models.CharField(max_length=300, default='default name') description = models.TextField() link = models.TextField() createat = models.DateTimeField(auto_now_add=True) random = models.TextField(max_length=300, default="random") category = models.ForeignKey(StandardCategory, on_delete=models.CASCADE) requirement = models.ForeignKey(StandardRequirement, on_delete=models.CASCADE) def __str__(self): return self.name but have the problem when I compile it web_1 | django.db.utils.OperationalError: no such column: app_standardrequirement.createat Need to resolve this question -
Django Rest Framework testing function that uses requests library
How can I test the following function in a django project? @api_view(['GET']) def get_films(request): if request.method == "GET": r = requests.get('https://swapi.co/api/films') if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: return Response({"error": "Request failed"}, status=r.status_code) else: return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST) -
How do you modify form data before saving it while using Django's CreateView?
I'm using the CreateView of Django and I'm trying to find out how I can modify any text which gets sent before it gets saved. For example, right now I'm only looking to lowercase all the text before saving. I know I need to use form_valid() but I can't seem to get it right. -
unable to import winkerberos I am running from Linux
from django.conf import settings import logging import json import requests import socket import winkerberos as kerberos While I am running the above code in LINUX machine , i am getting below exception ImportError: No module named winkerberos I have tried installing pip install pykerberos==1.2.1 and pip install request-kerberos But nothing worked for me, please suggest possible solution and where I am doing wrong -
Index tables in Django PostgreSQL database
I have this model - class Table(models.Model): name = models.CharField(max_length=100, unique=True) status = models.IntegerField(default=0) I don't have any db_index=True here, so ideally, there should not be any index tables created. But here is what I get when I run SELECT * FROM pg_indexes WHERE tablename = 'Schema_table'; - schemaname | tablename | indexname | tablespace | indexdef public | Schema_table | Schema_table_name_ad77b83a_like | | CREATE INDEX "Schema_table_name_ad77b83a_like" ON "Schema_table" USING btree (name varchar_pattern_ops) public | Schema_table | Schema_table_name_key | | CREATE UNIQUE INDEX "Schema_table_name_key" ON "Schema_table" USING btree (name) public | Schema_table | Schema_table_pkey | | CREATE UNIQUE INDEX "Schema_table_pkey" ON "Schema_table" USING btree (id) (3 rows) I can understand why there'd be an index for the primary key (pkey), but why the rest? If I understand correctly, everytime an object is created/updated, the corresponding index table is also updated. Does this mean for every write operation into this table, I'll have 4 write operations in total( 1 for the actual writing into the table, and 3 for the index tables)? -
Can't store image file path in database using django models.
I'm learning django. and i'm stuck in a situation where I want user to upload their images in my website. when the user uploads the files, its successful without any errors, but when I load the profile page, all the values are there bur except the image. But uploading files from the admin panel works absolutely fine. I really can't figure out the bug here. Is there something wrong with the request? How to fix that? following is my models.py class BlogUser(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) picture=models.ImageField(upload_to='user_pic') bio= models.TextField(max_length=256,blank=True) date_of_birth=models.DateField() def get_absolute_url(self): return reverse('blogs:profile',kwargs={'username':self.user.username}) following is my template: {% extends 'base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {% block title %}User Profile{% endblock %} {% block body %} <p>{{blog_user.username}}</p> <p>{{blog_user.first_name}}&nbsp;{{blog_user.last_name}}</p> <p>{{blog_user.email}}</p> <img style="width: 200px" src="{% static 'media/' %}{{user_p.picture}}" alt="" /> <p>{{user_p.bio}}</p> <p>{{user_p.date_of_birth }}</p> <br><hr> {% if not is_profile_complete %} <form method="POST" action="{% url 'profile' blog_user.username %}"> {% crispy user_profile %} {% csrf_token %} </form> {% endif %} {% endblock %} this is my views.py: @login_required def Profile(request, username): user = get_object_or_404(User, username=username) user_p="" is_profile_complete=False try: user_p = BlogUser.objects.get(user_id=user.id) user_profile='' except: if request.method == "POST": user_profile = UserProfileForm(data=request.POST) if user_profile.is_valid(): profile = user_profile.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture โฆ -
Getting "no such table: main.auth_user__old" on Django Admin
I creating a fresh new installation of Django and i getting the "no such table: main.auth_user__old" error when i tried to add new user on admin. I already tried with creating an app, without creating an app, update python, among others. I already migrate everything from initial state and applied makemigrations and migrate again, and nothing. No matter i tried to add in admin page, i receive this error. Do anyone have a clue about what's going on? Thanks! -
How to keep each celery class based task in separate file in django project?
I have setup celery in my django project using official documentation at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django So my project structure is โโโ mysite โโโ db.sqlite3 โโโ manage.py โโโ mysite โ โโโ celery.py โ โโโ __init__.py โ โโโ settings.py โ โโโ urls.py โ โโโ wsgi.py โโโ polls โโโ admin.py โโโ apps.py โโโ forms.py โโโ __init__.py โโโ migrations โ โโโ 0001_initial.py โ โโโ __init__.py โโโ models.py โโโ tasks.py โโโ tests.py โโโ views.py polls is application polls/tasks.py have class based celery task. Currently tasks.py have many tasks so that file is too big. I want to keep each task in separate file like mysite/polls/ โโโ admin.py โโโ apps.py โโโ forms.py โโโ __init__.py โโโ migrations โ โโโ 0001_initial.py โ โโโ __init__.py โโโ models.py โโโ tasks โ โโโ download_task.py โ โโโ __init__.py โ โโโ process_task.py โ โโโ upload_task.py โโโ tests.py โโโ views.py How to make this setup working? -
The correct way to hide part of fieldsets in django admin, depending on user rights
I want to hide part of fieldsets in django admin, depending on user rights. I have solved this problem by overriding get_fieldsets method, but now have feeling this is not proper way. def get_fieldsets(self, request, obj=None): fieldsets = super(EmployeeAdmin, self).get_fieldsets(request, obj) if not request.user.has_perm('myapp.can_edit_hidden_employee'): return fieldsets return fieldsets + (( _('Hidden fields'), {'fields': ('field1', 'field2')} ), ) models.py class Employee(models.Model): permitted_fields = { '{app_label}.can_edit_hidden_{model_name}': [ 'field1', 'field2'] } first_name = models.CharField(_('First name'), max_length=255) last_name = models.CharField(_('Last name'), max_length=255) field1 = models.CharField(_('Field1'), max_length=255, null=True, blank=True) field2 = models.CharField(_('Field2'), max_length=255, null=True, blank=True) class Meta: permissions = ( ('can_edit_hidden_employee', _('Can edit hidden fields')) ) admin.py class EmployeeAdminForm(ModelForm): field1 = forms.CharField(label=_('field1'), required=False, widget=CustomWidget()) field2 = forms.CharField(label=_('field2'), required=False, widget=CustomWidget()) class EmployeeAdmin(ModelAdmin): list_display = ('last_name', 'first_name') list_display_links = ('last_name', 'first_name') search_fields = ( 'first_name', '^last_name') fieldsets = (( None, {'fields': ( 'last_name', 'first_name')} ), ) form = EmployeeAdminForm def get_fieldsets(self, request, obj=None): fieldsets = super(EmployeeAdmin, self).get_fieldsets(request, obj) if not request.user.has_perm('myapp.can_edit_hidden_employee'): return fieldsets return fieldsets + (( _('Hidden fields'), {'fields': ('field1', 'field2')} ), ) Django 1.11.17, python 3.7 -
Django Generic Based view: not saving html form data to database
I have a Django library application with several books and authors, here is a /author/create html form used by the admin to create/update details of the author (firstname, lastname, dob, profile picture), referring the MDN Library application. I have a Generic Class Based View for this purpose: class AuthorCreate(PermissionRequiredMixin, CreateView): permission_required = 'is_superuser' model = Author fields = '__all__' success_url = reverse_lazy('author-detail') class AuthorUpdate(PermissionRequiredMixin, UpdateView): permission_required = 'is_superuser' model = Author fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death'] success_url = reverse_lazy('author-detail') class AuthorDelete(PermissionRequiredMixin, DeleteView): permission_required = 'is_superuser' model = Author success_url = reverse_lazy('authors') And these are the url patterns: urlpatterns += [ path('author/create/', views.AuthorCreate.as_view(), name='author_create'), path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'), path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author_delete'), ] And this is the author_form.html for creating/updating author details: <form action="" method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} //remaining code... </form> Now, on clicking the submit button in the html form above, it should redirect to author/id page(mentioned in the success_url), however the main concern is that a new author is not getting created in the first place. I am not sure how the html form data is being saved, whether or not it is being saved in the first place, because the page is redirecting to the sucess_url. Please โฆ -
Django : uploaded image not acessed in the template
I am trying to create a code like facebook image upload in django. My image gets uploaded and it is stored in the media folder under documents , and i like to show that image wherever i want in my template , but the image should be the latest one, to show in the template models.py class ImageUpload(models.Model): image = models.FileField(upload_to='documents/') views.py def ImageUpload(request): #lastimage = ImageUpload.objects.latest() #print(lastimage) if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('dashboard.html') else: form = ImageUploadForm() return render(request, 'image_upload.html', { 'form': form }) forms.py from django import forms from chat.models import ImageUpload class ImageUploadForm(forms.ModelForm): class Meta: model = ImageUpload fields = '__all__' image_upload.html {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'dashboard' %}">Return to home</a></p> {% endblock %} base.html <div class="row"> <div class="col-lg-1 col-md-0 col-sm-1 col-xs-12"> <div class="menu-switcher-pro"> <button type="button" id="sidebarCollapse" class="btn bar-button-pro header-drl-controller-btn btn-info navbar-btn"> <i class="educate-icon educate-nav"></i> </button> </div> </div> <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12 pull-right"> <div class="header-right-info"> <ul class="nav navbar-nav mai-top-nav header-right-menu"> <li class="nav-item"> <a href="#" data-toggle="dropdown" role="button" aria-expanded="false" class="nav-link dropdown-toggle"> <img src="/static/Chatbot_Dashboard/img/admin.png" alt="Admin-image" /> <span class="admin-name">Admin</span> <i class="fa fa-angle-down edu-icon edu-down-arrow"></i> </a> โฆ -
Django - How to access the same list on every call to views.py?
I want to create a simple Tic-Tac-Toe game with Python (Django). It will be just a 3x3 table. When user clicks on a cell - Ajax call to a specific url that leads to views.py. Do I need to send values of the all cells to python script every time? Or is there a way to declare a list with all values inside views.py and access it every time when the call is made? -
django dependant select via jquery , does not work with non english
I used these codes: (Django dependent select) to implement django dependent select, it works properly when the names of citys and counties are saved in english in the database but when i want to save non english names in the database it doesnt work ! i also used <head><meta charset="UTF-8" /></head> for html and # -*- coding: utf-8 -*- for python pages the codes are : models.py : from django.db import models class City(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey("Country") def __unicode__(self): return u'%s' % (self.name) class Country(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return u'%s' % (self.name) views.py: from django.shortcuts import render from map.models import * from django.utils import simplejson from django.http import HttpResponse def index(request): countries = Country.objects.all() print countries return render(request, 'index.html', {'countries': countries}) def getdetails(request): country_name = request.GET['cnt'] print "ajax country_name ", country_name result_set = [] all_cities = [] answer = str(country_name[1:-1]) selected_country = Country.objects.get(name=answer) print "selected country name ", selected_country all_cities = selected_country.city_set.all() for city in all_cities: print "city name", city.name result_set.append({'name': city.name}) return HttpResponse(simplejson.dumps(result_set), content_type='application/json') index.html : <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' โฆ -
Two step object creation in Django Admin
I'm trying to change the implementation of an EAV model using a JSONField to store all the attributes defined by an attribute_set. I already figured out how to build a form to edit the single attributes of the JSON, but I'm currently stuck at implementing the creation of a new object. I think I have to split object creation in two steps, because I need to know the attribute_set to generate the correct form, but I don't know if there's a way to hook in the create action, or any other way to achieve what I need. -
Fetch external data and populate form in django admin
In short: I would like to fill in some form fields in django admin, before I click the save button, based on the input in another field. The longer version: I have 2 models, SteamGame and GameInfo which has a ForeignKey to SteamGame. The SteamGame table gets filled once a day with all the games listed on Steam, by fetching and parsing http://api.steampowered.com/ISteamApps/GetAppList/v0002/, the GameInfo table gets filled manually using the admin site. When adding to GameInfo I select the game from SteamGame. Some of the fields are for info I add myself, some of the fields I want to be populated after selecting the game and fetching https://store.steampowered.com/api/appdetails?appids=GAMEID&l=en for that information. Are there some magic Django functions I can use to accomplish this? Or any other suggestions on how to do this? Thanks! -
Django : Iterate over objects in HTML template doesn't work well
I would like to get your help in order to display objects choosen by user and get some querysets according to each object. I'm working with django 1.11.16 on this project. Context : User has to choice some things : Start date End date One or several publication(s) Then, it returns a table with some querysets applied to this/these publication(s) and display one publication per row with associated data. Forms.py file : class PublicationStatForm(forms.Form): publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) # This part doesn't work while it should be # publication_list = forms.ModelMultipleChoiceField( # queryset=Publication.objects.all().order_by('pub_id'), # label=_('Publication Choice'), # widget=ModelSelect2MultipleWidget( # model=Publication, # queryset=Publication.objects.all().order_by('pub_id'), # search_fields=['pub_id__icontains', 'title__icontains'], # ) # ) def __init__(self, *args, **kwargs): super(PublicationStatForm, self).__init__(*args, **kwargs) In this part, I have a ModelMultipleChoiceField because user can select one or several publication(s). The commented part doesn't work while it should do the job. Views.py file : In this part, I create some querysets in order to get informations about selected publication(s) over a selected time period. I will show you only 2-3 querysets but it counts 6 querysets. I pick up the list of publications, get the id and I make a loop over each id in the list. class StatsView(TemplateView): """ โฆ