Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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): """ … -
Django filter objects based on the value of a field of the last data in another model
There are 2 models class A(models.Model): name = models.TextField() class B(models.Model): a = models.ForeignKey(A) status = models.BooleanField(default=False) Now I want to filter objects of class A based on the last data in class B status. if there are 2 datas of Model B id | a | status 1 | abc | False 2 | abc | True So if I want to filter objects of Model A which are having status False. In this case it will give me abc. If I wanted to filter objects of Model A which are having status True. In this case it should not return me abc. I want to write a query something like A.objects.filter(b__status__last=True) Is it possible to do using filters? -
register your Django router
when i use route.register(r'codes', SmsCodeViewset) don't add base_name="", this is an error `AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. when i useroute.register(r'codes', SmsCodeViewset, bose_name="")` there is no error ,may i ask why? -
How can I avoid users having to reenter their password when signed in to o365?
I am building a webapp with Django which allows our users to create a meeting in their office365 calendar while also storing the meeting in a database so we can display some information about it on a screen in the office. I am using exchangelib to create the meetings and it works really well. I want to make it so our users do not have to enter their passwords for their o365 account every time they use it, but I would prefer not storing the passwords locally either since they change regularly. Our users are always logged in to sharepoint or owa when they use this app is it possible to get their credentials from there? Or is it possible to link it to our local AD? -
Django 1.11 ManyToMany
I'm having problems with Django 11.1. I added a ManyToMany relation to a file upload but in Admin there is no option to send the files. In this system I have the registration information of a course and I need to send files to download. There may be several files per course, so a ManyToMany interface. Below is the image of how Admin is showing the field. Django Admin input print models.py class PalestraFile(models.Model): file = models.FileField( upload_to=path_and_rename('uploaded_files/palestra/'), blank=True, verbose_name="Arquivo da programação", help_text="(.pdf, .doc, .txt, .png, .jpg)") class Palestra(Programacao): palestrante = models.ForeignKey(Palestrante, null=True, blank=True, limit_choices_to={'ativo': True}) palestrantes = models.ManyToManyField( Palestrante, related_name='palestra_palestrantes', blank=True, limit_choices_to={'ativo': True} ) file = models.ManyToManyField( PalestraFile, related_name='palestra_palestrafiles', blank=True, verbose_name="Arquivos da palestra") class Meta: verbose_name = 'Palestra' verbose_name_plural = 'Palestras' def __str__(self): return '%s | %s ' % (date(self.dia, "d/m"), self.tema) admin.py from django.contrib import admin from .models import Palestrante, Palestra, PalestraFile from .forms import PalestranteFormAdmin @admin.register(Palestrante) class PalestranteAdmin(admin.ModelAdmin): form = PalestranteFormAdmin list_display = ['nome', 'email', 'slug', 'ativo'] prepopulated_fields = {"slug": ("nome",)} # actions = ['compress_uploads'] def compress_uploads(self, request, queryset): for obj in queryset: obj.save() compress_uploads.short_description = "Comprimir Imagens de Uploads" @admin.register(Palestra) class PalestraAdmin(admin.ModelAdmin): search_fields = ( 'tema', 'palestrante__nome', 'dia', 'evento__nome', 'evento__local' ) list_display = [ 'evento', 'palestrante', … -
Dynamic DOB Year selection in Django
I am using django 1.7.7. I want to make a year selection dropdown using for loop. <option value="0">Year</option> {% for year in 2018|getxrange:1893 %} if year < 10 %} <option value="0{{year}}">0{{year}}</option> {% else %} <option value="{{year}}">{{year}}</option> {% endif %} {% endfor %} Instead of 2018 I want a dynamic year. My Try: {% with now "Y" as name %} {%endwith%} Its not working. please suggest better way to achieve this. -
AWS lambda serverless website (using django ) session maintaining
I developed a website using django. Recently I am trying to make it serverless and deploy to lambda. I haven't figured out how to maintain the session after user logged in when deployed to lambda.any suggestions please.