Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django XMLRenderer
I have problem with django rest XMLRenderer. By default the output of XMLRenderer is like <root> <list-item></list-item> ... </root> but I would like to get something like that <rss rss xmlns:g="http://base.google.com/ns/1.0" version="2.0"> <channel> <item></item> ... </channel> </rss> From this post I know that I need to override XMLRenderer class, here is my code from __future__ import unicode_literals from django.utils import six from django.utils.xmlutils import SimplerXMLGenerator from rest_framework.compat import StringIO, smart_text, yaml from rest_framework.renderers import BaseRenderer class ModifiedXMLRenderer(BaseRenderer): """ Renderer which serializes to XML. """ media_type = 'application/xml' format = 'xml' charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized XML. """ if data is None: return '' stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startElement("rss", { "xmlns:g": "http://base.google.com/ns/1.0", "version": "2.0" }) xml.startElement("channel") ####### here self._to_xml(xml, data) xml.endElement("channel") ####### here xml.endElement("rss") xml.endDocument() return stream.getvalue() def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement("item", {}) self._to_xml(xml, item) xml.endElement("item") elif isinstance(data, dict): for key, value in six.iteritems(data): xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(smart_text(data)) I marked lines by ####### where I try to add channel tag. When there are, there are no output at … -
django generate token for verification to user email
I want to generate a token which needs to be sent to a user e-mail for verification. By default, the token will carry unverified value in the database. but when the user clicks on the link provided in e-mail with token the database value should change from unverified to pending which had been defined in models.py I generated some random values using python-secrets. but don`t know how to implement it -
How do you pre-populate a CheckboxSelectMultiple form in the views (requires request object) [not using using __init__]
I have 2 questions. What are the requirements for rendering a CheckboxSelectMultiple. How this is pre-populated using some list of data? How to pre-populate this form using list of data in views rather than in forms without using the constructor in forms Problem :-> I have model called Good which is like this class Good(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and a form from this is made like class GoodForm(forms.ModelForm): class Meta: model = Good exclude = ('user',) widgets = {'ans': forms.CheckboxSelectMultiple} I want to render this form using the data given below data= request.user.love_set.all() or data=Love.objects.filter(user=user) I want to render it with the data[i].ans where ans is an attribute in Love model ( just like id,pk,username etc) for example let data=['a','b','c', 'd'] then I want users to choose from 'a','b','c','d' How can I initialise the form in views NOTE - I want to do it in views rather than in forms as it requires request.user and using the constructor,__init__, super() would be very complex and jumbled. -
Passing extra variable with Django ListView
Can't pass extra variable with listview I tried adding another function and returning the value but it then doesn't return the main part. class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 3 def get_context_data(self, **kwargs): posting = [] for post in Post.objects.all(): post_words = post.content.split() for word in post_words: posting.append(word.lower()) mostused_word = [] for word in posting: if len(mostused_word) == 0: mostused_word.append({'daword': word, 'word_count': posting.count(word)}) else: if posting.count(word) > mostused_word[0]['word_count']: mostused_word[0] = {'daword': word, 'word_count': posting.count(word)} context = { 'mostused_word': mostused_word[0]['daword'], 'mostused_word_count': mostused_word[0]['word_count'], 'postin': posting, } return context I expect to pass both needed variables, not only one of them. -
How to create task with infinite loop and kill it safely in consumers, django channels 2?
From this answer, which helps to send data from consumers for every n seconds. Tried to handle the disconnection properly, using creat_task method, tried to stop while-loop(which is used to send data for every n seconds) by sending a flag=False(Assuming, this flag is not sent to the same instance which is created the task). consumers.py: class AutoUpdateConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) await self.create_task(True) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): await self.create_task(False) print("disconnected", event) async def create_task(self, flag=True): while flag: await asyncio.sleep(2) df= pd.DataFrame(data=[random.sample(range(100), 4) for _ in range(5)]) await self.send({ 'type': 'websocket.send', 'text': df.to_html(), }) Warning: 2019-09-11 14:40:06,400 - WARNING - server - Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at D:\Django\Django channels\django_channels_env\lib\site-packages\channels\sessions.py:175> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000001870E06C618>()] for connection <WebSocketProtocol client= ['127.0.0.1', 63789] path=b'/ws/home'> took too long to shut down and was killed. How to stop_task safely instead of waiting for channels to kill task? -
How to get user data from template in Django?
It's probably super simple but I found nothing on this specific case. It doesn't help that I messed up a bit and lost track of what does what. I want my template to display user account balance. models.py: from django.contrib.auth.models import User from django.db import models class Uzytkownik(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) saldo = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False) telefon = models.CharField(max_length=12, blank=True) adres = models.TextField(max_length=255, blank=True) def get_balance(self, request): current_user = request.user return current_user.saldo view.py: from django.shortcuts import render from .models import Uzytkownik, User def index(request): context = {'saldo': Uzytkownik.get_balance} return render(request, 'bpanelapp/index.html', context) In my template, I refer to it using <h2>{{context}}</h2>. Yet the <h2> is empty, even though my currently logged in account's balance field contains data. -
LDAP Connectivity error : Transport endpoint is not connected
When I try to login using ldap it shows error. I had install slapd ldap-utils and add entries according to this [link] (https://computingforgeeks.com/install-and-configure-openldap-phpldapadmin-on-ubuntu-18-04-lts/) settings.py import ldap from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = "ldap://example.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=People,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(samAccountName=%(user)s)" ) WARNING Caught LDAPError while authenticating rohits: SERVER_DOWN({'desc': "Can't contact LDAP server", 'errno': 107, 'info': 'Transport endpoint is not connected'},) -
Django custom Form and GenericView
The following code is working but I wonder if there is a more elegant way of doing. I have to pass the specie_id so I can filter the breeds to the corresponding specie. I can pass the specie_id to the view but I also have the information in the Resident model ("specie"). both get() and post() have nearly the same code, passing the specie_id. The View class ResidentUpdate(UpdateView): model = Resident template_name = "administration/resident_form.html" form_class = ResidentCreateForm def get(self, request, pk): initial = self.model.objects.get(id=pk) form = self.form_class(instance=initial, specie_id=initial.specie.id) return render(request, self.template_name, {"form": form}) def post(self, request, pk): initial = self.model.objects.get(id=pk) form = self.form_class(request.POST, specie_id=initial.specie.id, instance=initial) if form.is_valid(): form.save() return redirect("resident_detail", pk) return render(request, self.template_name, {"form", form}) The Form class ResidentCreateForm(ModelForm): class Meta: model = Resident fields = [ "name", "specie", "breed", "gender", "gender_status", "birth_date", "organization", "social_behaviors", "notes", ] widgets = { "birth_date": DateInput(attrs={"class": "flatpickr"}), "specie": HiddenInput(), } def __init__(self, *args, **kwargs): self.specie_id = kwargs.pop("specie_id", None) super(ResidentCreateForm, self).__init__(*args, **kwargs) self.fields["specie"].initial = self.specie_id self.fields["breed"].queryset = Breed.objects.for_specie(self.specie_id) -
Django deployment's redis usage is linearly increasing
I have a deployment of a Django application, with Redis running on Google Memory Store. I am using Redis as a broker for Celery, and as a caching backend for Django. There is almost no usage of Redis as a cache. There is minimal usage of Redis as a queue - about 3 scheduled jobs run a few times a day. The memory consumption on the Redis instance is increasing linearly. I have to FLUSHALL every few hours to keep it available. How do I debug this problem, and understand what is consuming as much memory? I have tried MGET to view the contents of keys - the stored values are bytes that make no sense to me. I was previously using django-cachalot. I disabled it, verified that it's disabled, and still have the same result. -
drf how to avoid objects.all() in UniqueValidator
I have a serializer class that represents a user. class UserSerializer(BaseSerializer): uid = serializers.IntegerField(required=True) class Meta: model = User fields = "all" def validate(self, data): super().validate(data) validate_user_data(data=self.initial_data, user=self.instance) return data users should be unique on uid, so when getting a post request what I really want is to change the uid field to: uid = serializers.IntegerField(required=True, min_value=1, max_value=2147483647, validators=[validators.UniqueValidator(queryset=User.objects.all())]) and this will probably work, the problem is, this will trigger an sql query the will select all the users. This could have a very high impact on the system, since there could be tens of thousands of them. What I would really want is to change the query to User.objects.get(uid=uid), which will not select every user from the db. However since i'm in the serializer definition of uid, I can't use uid=uid because uid is just being defined. -
Django: How to run a function in background and direct to a URL when a certain thing happens?
I intend to show the user the home page and wait for the user to tap his NFC enabled ID card. Say, the ID card only contains the name. I want a function that will wait for the user to tap his ID. I have retrieved that name and stored in a variable in that function. Now, I want that function to redirect the web application to a certain URL and pass the name to that URL. How do I do this? Any help will be much appreciated. I have tried celery but it did not work for me. I could not even import decorators. It says "Cannot find reference 'decorators' in 'init.py' ". -
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?