Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enforce a static order for row_result diff list in ModelResource?
I'm using django-import-export module to import data from spreadsheet to my model via a ModelResource. After the instance initialization process and after the diff between the original and the imported object fields are calculated and a row result is generated, I want to be able to: 1) change the order of the headers in the html, which shows you the imported field values. 2) Add custom values for fields. So far I have tried to override the after_import_row method in my ModelResource to tackle the problem stated in #2: def after_import_row(self, row, row_result, **kwargs): diff = row_result.diff custom_value = 'Custom: {}'.format(row['Reason']) diff[2] = custom_value I expect the third column header value of the HTML table to be changed to what I put in the step above. But since the header order is changed, I cannot ensure that the custom value is matching the header I want. That is why I want to enforce a static order for the diff headers in the row result. How can I do this? -
How to place default value in to dropdown form field in django
I'm building a post-comment model in one view, one page, something like facebook. I have two forms in my home.html and view.py: new post and new comment. In each post container, there is a new comment form. I have a problem because I don't know how to relate comment to post - specifically how to pass post.id to my comment form. Is it possible to pass my {{ post.id }} to my {{newCommentForm.field }}? That each comment has a default value of post's id? My home.html: {% for post in posts %} <div class="container"> <a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }} <img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}"style="width:100%;"> <p>{{ post.content }}</p> <form METHOD="POST" class="new_post"> {% csrf_token %} {{ newCommentForm.content }} {{ newCommentForm.post }} <button type="submit" name="newCommentSubmit">Add</button> </form> </div> {% endfor %} models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=500) date = models.DateTimeField(default=timezone.now) def add_coment(self): self.date = timezone.now() self.save() def __str__(self): return self.content My model is working now, comments are added, but I need to choose my post (post.id) manually from the default dropdown field witch all … -
how to export data with date and foreign key
Ive managed to export the required data. However, as for date, it gives me a string of number instead of date. Tried to use data_format but does not work. Also, I have a foreign key in the database which is studName. I want to export the student name instead of the id. below is model code: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name def get_day(self): return self.day def get_time(self): return self.time class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=0) attendance = models.IntegerField(default=1) Below is my view code: def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="attendance.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('attendance') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True #date_format = xlwt.XFStyle() #date_format.num_format_str = 'dd/mm/yyyy' columns = ['id', 'Student Name', 'Class Group', 'Date','week', 'Attendance' ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = MarkAtt.objects.all().values_list('id', 'studName', 'classGrp', 'currentDate', 'week', 'attendance') for row,obj in … -
Django fetch records with custom joins
I have three models Employee, User and Address. Suppose Employee and User both have an Address, so in Address model, I added two columns addressable_type and addressable_id. addressable_type contains the name of the model either Employee or User, addressable_id contains the id of the Employee or User. So now I want to order all addresses based on Employee or User name. How can I do this as this is not a direct foreign key association? Please suggest a solution. -
Page url not found in Django
I make this app in django for showing Category in Django. I made the views and the urls app for this feature bat don' t work. I don'know why it don't work, can someone help me please? I have tried a lot of different codes to solve it bat they didn't work. Sorry for my English. Urls.py from django.conf.urls import url from . import views from django.contrib import admin from django.views.generic import ListView, DetailView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls.static import static from django.urls import path urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), #Index url(r'^all-articles$', views.PostList, name='PostList'), #All Posts url(r'^category$', views.Category, name='Category'), #All CAtegory path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), #Single Posts ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() Views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import render from django.http import HttpResponse from .models import * from django.views.generic import View from django.views import generic def index(request): #HomePage return render(request, 'blog/index.php', {}) # Post Section def PostList(request): #Articles List articles = Article.objects.all().order_by('data') return render(request, 'blog/post/PostList.php', {'articles':articles}) class PostDetail(generic.DetailView): #Single Article model = Article template_name = 'blog/post/post_detail.php' def Category(request): #Category List category = Category.objects.all() return render(request, 'blog/post/category.php', {'category':category}) Models.py from django.db import models from django import forms from … -
call task from any django app with celery
i would like to use celery to start a python script from a django api and run the python script periodic simultaneously. This tutorial help me to configure celery in django. Now my project looks like: |- web |- api |- migrations |- __init__.py |- admin.py |- apps.py |- models.py |- serializers.py |- tests.py |- urls.py |- views.py |- project |- __init__.py |- celery.py |- settings.py |- tasks.py |- url.py |- wsgi.py Now you can see i followed the tutorial but how can i call the function in my tasks.py from my api app? -
get_object_or_404 latest = True
I want to retrieve the last object of a matching query. How can I get that? Something like : get_object_or_404(Passwordreset, otp=5) My model has multiple objects with otp 5. Is there something by which I can get the last object which has otp=5? -
Model values saved as object ( <Model_Name object>) in DB rather than simple values
I have a model called Love as class Love(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and a ModelForm class LoveForm(forms.ModelForm): class Meta: model = Love fields = ('ans',) and my views to display this form and save data in DB is def love_form(request): #user can input as my answers he wants to thats wht multiple times rendering the same template form = LoveForm() if request.method == 'POST': form = LoveForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.user = request.user answer.save() return render(request, 'purpose_using_DB/love_form.html', {'form': form, 'message': 'Successfully Saved'}) else: return render(request, 'purpose_using_DB/love_form.html', {'form': form, 'message': 'Error Occured'}) else: return render(request, 'purpose_using_DB/love_form.html', {'form': form}) but the problem is that the Data saved in DB after admin.site.register(Love) is shown as an object rather than the ans values Is this normal? Why it isn't showing the values like ans=something in the admin ? -
How to add automatically generated fields in model?
I need to create model with automatically generated fields, that can be used for filtering. This fields must be added by users in user interface. I've found 2 ways: to create chained model by FK, for example UserExtraFieldModel for User model, or to use JsonField for extra_fields field. But both methods have risks with efficiency. Is there better way to do it? -
facebook-messenger-bot error: When & why this error raised "(#100) Length of param name_placeholder[text] must be less than or equal to 640"
I have a Django application that is connected to Messenger for a Facebook page. When any Facebook user messages to the Facebook page my application try respond automatically after parsing Facebook user's message. If any error occurred during sending message from my Django application I stored the error text in a column of a table. When I tried to analyze the errors generated while sending message I found one error text is as follow "(#100) Length of param name_placeholder[text] must be less than or equal to 640" and I can not regenerate it. There is another similar error "(#100) Length of param message[text] must be less than or equal to 2000" which is very clear and I can regenerate it. I have searched on Google and found nothing that can help me. I just wants to know that when and why the error occur so that I can modify my application to handle it. I have used the following api for sending messages to Facebook user https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN with this header parameter {'content-type': 'application/json'} and this data { "messaging_type": "RESPONSE", "recipient": { "id": "receiver_id" }, "message": { "text": "message_text" } } Note: I know Facebook gives error code, type, error_subcode and … -
manage.py is running fine but not showing in the local host
I'm using Django 1.10.0, python 2.7. Can you please tell me Where am I going wrong ? Been stuck with this for weeks. I'm using AWS server to run a chatbot.Ubuntu 16.04.6 LTS When I run "./manage.py run server 0.0.0.0:8000 - The model is being trained and it's running with no error in the terminal. It is running in the terminal :- "Read weights from disk [Parallel(n_jobs=1)]: Done 50 out of 50 | elapsed: 0.2s finished {'multicast_ids': [7269965488589568215], 'canonical_ids': 0, 'success': 0, 'topic_message_id': None, 'results': [{u'error': u'NotRegistered'}], 'failure': 1} System check identified no issues (0 silenced). September 11, 2019 - 09:59:07 Django version 1.10.1, using settings 'exp.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C." My virtual env is activated. and Django is also installed in the virtual environment. My manage.py:- "#!/usr/bin/env python import os import sys print(sys.path) if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "exp.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " … -
How can I utilise the built in first and last name features of the Django User Model?
So I know that Django has a built in system with the User, and it contains things like Username, e-mail, password, and first and last name. I want to know how I can utilise this in my site. So I have a first_name and last_name field in the models.py file, and they are CharFields. I want to know how to connect them to the already existing UserForm that comes with Django. I have tried a few things already, such as doing this with the models.py file. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.OneToOneField(User, on_delete=models.CASCADE) Here is some code for the form.py file. class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password','first_name') As you can see from the form, I added the first_name attribute, and in the models.py file, I have the first_name connected with the forms.py one. I am now getting this error. HINT: Add or change a related_name argument to the definition for 'UserProfileInfo.user' or 'UserProfileInfo.first_name'. So I added a related name field to the model, as shown here first_name = models.OneToOneField(User, on_delete=models.CASCADE,related_name='first_name') But, wouldn't you know it, I got yet another error: ValueError: Cannot assign "''": "User.first_name" must be a "UserProfileInfo" instance. … -
How can I specify a ?-based url parameter with django-rest-framework routers
I am working on a very simple school/student API and I want to handle url ?-based filters like /students/?name="Harry" I know how to do it with custom url patterns but I want to use routers (particularly nested routers) and I don't know how to set my urls.py and views.py in order to handle handle this kind of parameter. my urls.py : router = routers.DefaultRouter() router.register(r'schools', SchoolViewSet, basename='school') router.register(r'students', StudentViewSet, basename='student') schools_router = routers.NestedSimpleRouter(router, r'schools', lookup='school') schools_router.register(r'students', StudentViewSet, basename='school-students') urlpatterns = [ url(r'^', include(router.urls)), url(r'^', include(schools_router.urls)), ] -
Doesn't show pizzas' names on pizzas.html under many-to-one relationship [Python Crash Course exercises 18-8]
I wanted to follow the methodology in Python Crash Course Ch. 18 on building the learning_logs app to build the pizzas app. However I'm stuck at displaying the pizzas' name in pizzas.html. There should be 2 pizzas, named "Hawaiian" and "Meat Lovers". I added both using the admin account. Checked through the shell that both are stored in Pizza.objects.all() so I guess it's the problem to recall them. Some codes for you all's reference: views.py: from django.shortcuts import render from .models import Pizza # Create your views here. def index(request): """ The home page for Pizzeria. """ return render(request, "pizzas/index.html") def pizzas(request): """ Show all pizzas available. """ pizzas = Pizza.objects.all() content = {"pizza": pizzas} return render(request, "pizzas/pizzas.html", content) models.py from django.db import models # Create your models here. class Pizza(models.Model): """ Pizza available. """ name = models.CharField(max_length = 50) def __str__(self): """ Return a string representation of the pizza name. """ return self.name class Topping(models.Model): """ The toppoings on the pizza. """ pizza = models.ForeignKey(Pizza, on_delete = models.CASCADE) text = models.CharField(max_length = 250, unique = True) def __str__(self): """ Return a string representation of the toppings. """ return self.text urls.py: from django.urls import path, include from . import views … -
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' ".