Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Property fields retrieving data from another model
I do not know if there is such a thing as possible, I have little experience in it, so I ask. Is such a solution possible? I need a User and a Profile with email and password - AbstractBaseUser, the Profile will be connected to the User using the OneToOne relationship. As below: class User(AbstractUser): pass class Profil(AbstractBaseUser, PermissionsMixin): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField('email address', max_length=254, unique=True) USERNAME_FIELD = 'email' In the model, the User needs to fill in the username field that is required. How can I use property to relate to a Profile model and download data for a User model? -
Django: ImportError cannot import name 'Github'
I am getting this error importerror cannot import name 'Github' django when run python manage.py runserver command in windows 10. I am using: Django=2.2.5, django-github=0.1.2, django-uuslug=1.1.9, httplib2=0.13.1, python-slugify=3.0.3, pytz=2019.2, sqlparse=0.3.0, text-unicode=1.2 Someone please help me. -
How to fix search in django 2.2
I have the problem with search class in django 2.2.4 i get error ValueError at /search/ Cannot use None as a query value i can understand why get method doesn't work sorry for my bad English views.py class Search(View): """Search on movies and categories""" def get(self, request): search = request.GET.get("search") context = Movie.objects.filter(Q(name__icontains=search) | Q(category__name__icontains=search)) return render(request, 'movies/movie_list.html', {"movies": context}) urls.py path("search/", Search.as_view(), name="search_form"), form <form action="{% url 'movies:search_form' %}" method="get"> <input name="search " type="search" value="" placeholder="Search"> </form> -
curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid
Guys I'm trying to solve this issue and I'm kinda desperate now after failing so many times. I am trying to deploy my django app on apache I configured a license but I am getting this error curl: (35) schannel: next InitializeSecurityContext failed: SEC_E_INVALID_TOKEN (0x80090308) - The token supplied to the function is invalid. -
Django - Save to disk a pdf file generated using xhtml2pdf
I have been following this tutorial which helped me in generating pdf files in Django using xhtml2pdf. Now what I want is to save the generated file to disk without having to prompt the user to download the file. Below is the code I am using to generate the pdf file in utils.py file and views.py file. #utils.py file 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 #views.py snippet of code html = template.render(context) pdf = render_to_pdf('tdn.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "TDN_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content TDN.objects.filter(id=tdn_no).update(printed=1) return response return HttpResponse("Not found") Any pointers on how I can write to disk the generated pdf will be greatly appreciated -
IntegrityError in Django testcase
I am suspecting that transaction.atomic() does not commit my instance to the database during testing. The problem might comes from multiple databases from django.db import models from model_utils.models import TimeStampedModel class PIIField(TimeStampedModel): """ Personal Information Identifier configuration model This model is M2M on `Plan` """ name = models.CharField(max_length=30) detail = models.CharField(max_length=50, null=True, blank=True) order = models.SmallIntegerField(unique=True) def __str__(self): return self.name class Plan(timestamp.Model, models.Model): class Meta: db_table = "catalog_plans" product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="plans") coverages = models.ManyToManyField(Coverage, through="PlanCoverage") code = models.TextField(null=True) name = models.TextField() pii_fields = models.ManyToManyField(PIIField, related_name='plans', related_query_name='plan') Here is my tests.py from django.db import transaction from django.test import TransactionTestCase from model_mommy import mommy from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APIClient from catalog.models import Plan from pii_fields.models import PIIField class PIIFieldTestCase(TransactionTestCase): databases = {'default', 'product', 'customer'} def setUp(self) -> None: with transaction.atomic(): self.plan = mommy.make(Plan, code='88', name='Non risky life') # single `plan` with no` pii_fields` attached self.field_1 = mommy.make(PIIField, name='first_name', detail='text box', order=1) self.field_2 = mommy.make(PIIField, name='last_name', detail='text box', order=2) self.field_3 = mommy.make(PIIField, name='weight', detail='real number', order=3) self.field_4 = mommy.make(PIIField, name='nationality', detail='drop down', order=4) self.plan.pii_fields.set([self.field_1, self.field_2, self.field_3, self.field_4]) def test_get(self): """ Get the endpoint and see the payload sample :return: """ client = APIClient() url … -
Djando DateField throws 'invalid'
I made an upload xlsx function where i parse each row and add each row data to a dictionary, after that i'm validating this dictionary with a form, in this form i have a DateField, if in the xlsx cell there's a correct formated date as i require in my field everything goes right, the form is valid and i can do whatever i want, but if the cell has an incorect formated date it throws this error: Internal Server Error: /core/process_upload_file Traceback (most recent call last): File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 106, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/debug_toolbar/middleware.py", line 85, in process_view response = panel.process_view(request, view_func, view_args, view_kwargs) File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/debug_toolbar/panels/profiling.py", line 160, in process_view return self.profiler.runcall(view_func, *args, **view_kwargs) File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/cProfile.py", line 109, in runcall return func(*args, **kw) File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/alex/Documents/Projects/Django/platform/application/core/views.py", line 567, in process_upload_file if form.is_valid(): File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/forms/forms.py", line 381, in full_clean self._clean_fields() File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/forms/forms.py", line 399, in _clean_fields value = field.clean(value) File "/Users/alex/Documents/Projects/Django/platform/venv/lib/python3.6/site-packages/django/forms/fields.py", line 148, in clean value = self.to_python(value) … -
How to save foreign key in django Model Form
I have two models and one form and one formsets so Formsets contains foreign of form and I want to save add id to formsets when saving both the forms and formsets. views.py if form.is_valid(): form.save() if formset.is_valid(): forms=formset.save(commit=False) for f in forms: #here I want to add id of previously added form f.save() -
post_save play a video
I have a django model called deposit and two views /admin # django admin /deposit # a ListView for the deposit model I want to reload the /deposit view with the latest data and play a video whenever a new entry is added in /admin view. It can be done using ajax where I keep hitting to check if db is updated after a fixed interval of time but is there any other way something that is more real time? -
Converting Django project from Python 2 to Python 3: How to fix Python int OverFlowError?
I am converting a Django website from Python 2 to Python 3. To do this, I ran 2to3 on the whole project. Now, upon running the server (which works fine in Python 2), an OverflowError occurs as shown in the first code block. The lower block shows the manage.py file. I have read elsewhere this may be an issue relating to int/float, but I am not quite sure how to handle an iterator with regard to this. (env) user:languages user$ python3 manage.py runserver Fatal Python error: initsite: Failed to import the site module Traceback (most recent call last): File ".../src/languages/env/bin/../lib/python3.7/site.py", line 66, in <module> import os File ".../src/languages/env/bin/../lib/python3.7/os.py", line 661, in <module> from _collections_abc import MutableMapping File "...src/languages/env/bin/../lib/python3.7/_collections_abc.py", line 45, in <module> longrange_iterator = type(iter(list(range(1 << 1000)))) OverflowError: Python int too large to convert to C ssize_tappleperson #!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I expected manage.py to run the server as normal and produce the website but instead it gets hungup on the overflow error described above. -
Render a CheckBoxSelectMultiple form using the data present in Database. [initial value is a queryset from DB]
I have a form called DemoForm which is related to model Demo class Demo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and the form for this is class DemoForm(forms.ModelForm): class Meta: model = Demo exclude = ('user',) widgets = {'ans': forms.CheckboxSelectMultiple} I want to render this form using a queryset I have tried different approaches like form = DemoForm(initial=Love.objects.filter(user=request.user)) <form=GoodForm() form.fields["ans"].queryset = Love.objects.filter(user=request.user) > form=DemoForm(instance=Love.objects.filter(user=request.user) form=DemoForm(instance=request.user.love_set.all()) Sometimes it is showing no _Meta present and when I use initial, it shows the expected length 2 got 1 (got 3) NOTE- The Love model is related to user in the same way as the Demo is related to user using ForeignKey. Means the Love model is a copy of Demo model. So the query returns nested objects -
How to validate object used as foreign key
Django==2.2.5 Could you help me validate if object used as foreign key is not archived? The problem: parent_is_archived(obj) receives int as its argument. For example, 1. It is not an object where I can check its fields. And there is no sign of the model whose pk this int represents. Maybe I should redefine some method like clean_fields? class Level_1(models.Model): archived = models.BooleanField(default=False, verbose_name="Archived") def parent_is_archived(obj): if ...: message = 'Parent object is archived' raise ValidationError(message) class Level_2(models.Model): parent_level = models.ForeignKey(Level_1, on_delete=models.CASCADE, validators=[parent_is_archived]) -
Django - Fetched foreign key is shown as dropdown in upload page. How to show the last entered data?
I have a main form and an upload form where i use foreign key to get the id from the main form. In my upload page, the ID's are shown as a dropdown. Is there a way to show only the latest ID instead of the dropdown I am not sure if my understanding is right but think there is something to change in the main model return str. This is the main form class MDform(models.Model): id = models.AutoField(primary_key=True) Author = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return str(self.id) This is my upload model class uploadmeta(models.Model): path = models.ForeignKey(MDform, on_delete=models.PROTECT) document = models.FileField(upload_to="aaData/") def get_absolute_url(self): return reverse('file_list') I am not able to attach a screenshot of my output. its a dropdown with all the id from the main form and the upload file option -
How to save an html file in django?
I have a view that forms the html template class CvView(AuthorizedMixin, View): def get(self, request, employee_id, format_): employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() print(type(data)) if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) return HttpResponse(data, content_type=content_type) This view has a data variable. This variable contains the body of the html template. If I'm printed in a console print(data) I get <!DOCTYPE html> <html lang="en"> <head> ..... </head> <body> ..... </body> The type of values is <class 'django.utils.safestring.SafeText'> I'm interested in the question: can I get an html file from this variable and save it on disk? How can I do this? -
Django filter_horizontal for Many-to-One relations
I need to create a DropDown with search field in django admin panel. After a little surfing, I found "filter_horizontal" which does something similar to what I want, but it works only for M2M relations. Any suggestions, please. -
Django API OneToOne relationship using Auth, User model, Views, Serializers
I'm trying to connect the HighScore model to my User model. This way I can save a HighScore instance for each User. No matter what I do, I get a 500 internal server error. I've tried creating a custom user model using AbstractUser. I've tried setting up OneToOne using settings.AUTH_USER_MODEL, and I've tried doing User = get_user_model() and all come back with a 500 internal server error. # models.py from django.conf import settings from django.db import models # Create your models here. class HighScore(models.Model): # user = models.OneToOneField( # settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # primary_key=True, # ) value = models.IntegerField(default=0) def __str__(self): return "{}".format(self.value) # urls.py from django.urls import path from .views import ListHighScoresView, CreateHighScoresView, HighScoresDetailView, LoginView, RegisterUsersView urlpatterns = [ path("highscores/", ListHighScoresView.as_view(), name="high-scores-all"), path("highscores/create/", CreateHighScoresView.as_view(), name="high-scores-create"), path("highscores/<int:pk>/", HighScoresDetailView.as_view(), name="high-scores-detail"), path("auth/login/", LoginView.as_view(), name="auth-login"), path("auth/register/", RegisterUsersView.as_view(), name="auth-register"), ] # serializers.py from rest_framework import serializers from .models import HighScore from django.contrib.auth.models import User class HighScoreSerializer(serializers.ModelSerializer): class Meta: model = HighScore fields = ("id", "value") def update(self, instance, validated_data): instance.value = validated_data.get("value", instance.value) # instance.user = validated_data.get("user", instance.user) instance.save() return instance class TokenSerializer(serializers.Serializer): token = serializers.CharField(max_length=255) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("username", "email") # views.py from django.shortcuts import render from … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'error in django
i am trying to open my group project in my windows system. what should i install to to eliminate this error i tried intalling this" pip install django_adminlte_theme". while i enter this "PS D:\stock1\stock_prediction-version2.2\stock> python manage.py runserver" it show -"PS D:\stock1\stock_prediction-version2.2\stock> python manage.py runserver" and "ModuleNotFoundError: No module named 'django_adminlte_theme'" and "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''" -
How to filter with different conditions?
Here I am trying to filter staffs by three conditions by selecting joined date year,month and organization.And for this I have tried like this but it is not working .What I am doing wrong here ? Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' And also I find this method that I tried below too long for my problem.If there any better solution for this then it would be a great help views.py def filter_staff_users(request): year = request.GET.get('year') month = request.GET.get('month') organization = request.GET.get('organization') present_year = datetime.datetime.today().year years_list = range(2016,present_year + 1) if year or month or organization: staffs = Staff.objects.filter( Q(joined_date__year=year) | Q(joined_date__month=month) | Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif year and month and organization: staffs = Staff.objects.filter(Q(joined_date__year=year), Q(joined_date__month=month), Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif year: staffs = Staff.objects.filter(joined_date__year=year) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif month: staffs = Staff.objects.filter(joined_date__month=month) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif organization: staffs = Staff.objects.filter(organization=organization) return render(request, 'organization/view_staff_users.html', {'years_list': rangeyears_list, 'staffs': staffs, 'year': year, 'month': month, … -
How can I get whether models.CharField is checked or not?
I want to know whether models.CharField is checked or not. I wrote in models.py like class Check(models.Model): STATUS = { 'A': '1', 'B': '2', } Check = ( (STATUS['A'], 'a'), (STATUS['B'], 'b'), ) check = models.CharField( max_length=1, choices=Check, default=STATUS['A']) in views.py def check(self): check_status = Check.objects I want to check whether STATUS['B'] is checked or not and I want to get all data b is retruned by using only one code check_status = Check.objects But I cannot understand how I should write a code. -
nested loop for checkbox values which compared with input form & saved form values which in json format. And how to avoid duplicates in checkbox goup
nested loop for checkbox values which compared with input form & saved form values which in json format. And how to avoid duplicates in checkbox group var form_fields = {{ i.form_field|safe }}; var save_for_details = {{ i.saved_form_details|safe }}; if(form_fields[i].type=='checkbox-group' || form_fields[i].type=='radio-group' ){ for(j=0;j<form_fields[i].values.length;j++){ for(k=0;k<save_for_details.length;k++){ if(form_fields[i].name+"[]" == save_for_details[k].name){ if(save_for_details[k].value== j){ var checked = "checked"; }else{ var checked = ""; } html += '<input class="" style="width: 25px !important;" type="'+fields+'" id="'+form_fields[i].values[j].value+'" '+checked+' name="'+form_fields[i].name+'[]" value="'+j+'"><label>'+form_fields[i].values[j].value+'</label>'; } } } checked & uchecked need to display only once -
Unable to Update InlineFormset in Django with CBV
class PreChildrenView(CreateView): model = PreDealDetails2 template_name = 'cam_app/children_form.html' fields = '__all__' success_url = reverse_lazy('forms_app:deal-entering') session_initial = 'children_' def get_initial(self,**kwargs): initial = super(PreChildrenView, self).get_initial(**kwargs) initial['deal_id'] = self.request.session['deal_id'] return initial def get_context_data(self, **kwargs): data = super(PreChildrenView, self).get_context_data(**kwargs) if self.request.POST: data['childrens'] = ChildrenFormSet(self.request.POST) print('post') else: print('get') data['childrens'] = ChildrenFormSet() data['childrens'].extra = 5 data['info'] = 'Children Details' return data def form_valid(self, form): print('wwwww') context = self.get_context_data() childrens = context['childrens'] if form.is_valid(): pass if childrens.is_valid(): count = 0 self.object = form.save() childrens.instance = self.object childrens.save() self.request.session[self.session_initial + 'children_count'] = count self.request.session['valid_children'] = True messages.success(self.request, 'Successfully filled Children Details') return self.render_to_response(self.get_context_data(form=form)) else: return super(PreChildrenView, self).form_invalid(form) class UpdatePreChildrenView(UpdateView): model = PreDealDetails2 template_name = 'cam_app/children_form.html' fields = '__all__' success_url = reverse_lazy('forms_app:deal-entering') session_initial = 'children_' def get_object(self, queryset=None): return PreDealDetails2(deal_id = self.request.session['deal_id']) def get_context_data(self, **kwargs): data = super(UpdatePreChildrenView, self).get_context_data(**kwargs) if self.request.POST: a = PreDealDetails2.objects.get(deal_id = self.request.session['deal_id']) data['childrens'] = ChildrenFormSet(self.request.POST) print('post') else: print('get') data['childrens'] = ChildrenFormSet(instance=self.object) data['childrens'].extra = 5 data['info'] = 'Children Details' return data def form_valid(self, form): print('update valid') context = self.get_context_data() childrens = context['childrens'] if form.is_valid(): print('wejri') self.object =form.save() if childrens.is_valid(): childrens.instance = self.object childrens.save() count = 0 self.request.session[self.session_initial + 'children_count'] = count self.request.session['valid_children'] = True messages.success(self.request, 'Successfully filled Children Details') return self.render_to_response(self.get_context_data(form=form)) else: return super(UpdatePreChildrenView, self).form_invalid(form) else: … -
Pagination in search results django
I want to implement pagination in search results. After search I see good result (e.g. http://127.0.0.1:8001/search/?q=mos) But, when I click "next", I have an error: ValueError at /search/, Request URL: http://127.0.0.1:8001/search/?city=2 Cannot use None as a query value I think that problem in urls (search_results.html). How can I fix it? How can I change: <a href="/search?city={{ page_obj.next_page_number }}">next</a> models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) class Meta: verbose_name_plural = "cities" def __str__(self): return self.name views.py class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 page_kwarg = 'city' def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' paginate_by = 3 page_kwarg = 'city' def get_queryset(self): # new query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list urls.py urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] search_results.html <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next … -
Where to start - Python For Interactive Websites
So I can code basic python already and built myself a program that uses sqlite to track certain stuff (data I need to input each day by myself) & wanted to make an online version of it. I read a whole book on django but I literally don't know the first step on how to go forward, cause at least in that book, he always used views that are already implemented in django & it seems like he only worked with posts. What I need to do is the following though. I need to enter certain data on the website and then send it upon a click to the database, and then the website should update (it has certain fields like means etc...). And secondly, again upon a click it should display certain stuff. I want this to be a one-page website so that's why again I felt like django isn't a good start since each 'app' kinda has multiple urls or at least that's how I understood it. Since I have literally zero idea of how to do it, posting here is my last attempt to figure it out, otherwise I'm thinking of hiring a developer only to show … -
How to calculate max requests per second of a Django app?
I am about the deploy a Django app, and then it struck me that I couldn't find a way to anticipate how many Gunicorn workers I will actually need to serve my audience provided that I know how many visitors per second my website will receive. Is there a way of calculating how many requests per second can my Django application handle, without resorting to things like doing a test deployment and use an external tool such as locust? I know there are several factors involved (such as number of database queries, etc.), but perhaps there is a convenient way of calculating, even estimating, how many visitors can a single Django app instance handle -
How to index search results on location bases not the whole model django
I am trying to create a location based app. I want to index search result on location basis. There will be cluster with whom objects will be associated. Index search results per cluster. I have seen some examples of elastic-search but the most examples I found are indexing the whole model. How can someone index but at different locations we have different search indexes. Every cluster and its associated products have their own search index. my models are as follows: from django.db import models from django.contrib.gis.db.models.fields import PointField class Cluster(models.Model): name = models.CharField(max_length=30) location = PointField(srid=4326, geography=True) class Product(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=255) cluster = models.ForiegnKey(Cluster, on_delete=models.DO_NOTHING) Now I want to index search results per cluster not the whole Product model at once.