Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter an existing queryset by the month instead of day
I have a queryset that displays the amount of followers for each day of the month. Views: context["brandtwitterFollowerCounts"] = ( TwitterFollowerCount.objects.filter( twitter_account=self.object.twitter_account, followers__gt=0 ) .distinct("created__date") .order_by("created__date") ) context["brandTwitterFollowCreated"] = [ i.created.strftime("%d %m") for i in context["brandtwitterFollowerCounts"] ] context["brandTwitterFollowers"] = [ i.followers for i in context["brandtwitterFollowerCounts"] Dataset: var newDataObjectTwo = { labels: {{ brandTwitterFollowCreated|safe }}, datasets: [{ label: 'Daily', backgroundColor: 'rgb(255, 255, 255)', fill: false, borderColor: 'rgb(29, 161, 242)', data: {{ brandTwitterFollowers|safe }} }], } I would like to filter this by months instead now. So as there are currently 3 months (08, 09, 10), the graph should only show 3 data points. Sorry if this doesn't make sense, I am not sure what the best way to explain it is. -
django - How to upload file to the folder in filefield
i am saving a form with a filefield, and saying upload_to to a user_path from the userprofile. I do not know how to write the view for the form models.py def nice_user_folder_upload(instance, filename): extension = filename.split(".")[-1] return ( f"{instance.UserProfile.Assigned_Group}/{filename}" ) class Metadataform(models.Model): id = models.AutoField(primary_key=True) Authors_Name = models.CharField(max_length=500, blank=True, null=True) Document = models.FileField(upload_to=nice_user_folder_upload) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username views.py def Metadata_submission(request): Authors_Name = request.POST["Authors_Name"] if request.method == 'POST': form = Fileuploadform(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, "home.html") else: form = Fileuploadform() i am getting an AttributeError at /Metadata_submission/ 'Metadataform' object has no attribute 'UserProfile' -
How could django's save() method of model know where to save among db tables?
Save() function must know where to save data, especially the exact table. Assume that there exist Question model and I create a new record and save it through q.save() like below. Although I haven't give the information of table actually, but it works well. I want to know how save() method can know the table name needed. def create_question(request, question): q = Question(question_text=question, pub_date=timezone.now())pub_date=timezone.now()) q.save() -
How to do validation in django serializers?
I have 2 custom validation functions created using packages from PyPI, I want to inlcude them in my serializers.py in my django project before converting it to JSON using rest. Problem is i dont know where or how to put the functions in such that the code will run through it. Here is my code: /* serializers.py */ import re import phonenumbers from rest_framework import serializers from phonenumbers import carrier from validate_email import validate_email class basicSerializer(serializers.Serializer): emailplus = serializers.EmailField() country = serializers.CharField(max_length=2) phone_number = serializers.CharField(max_length=100) def validate_emailplus(self): email = self.validated_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise serializers.ValidationError("Invalid email") return email /* views.py */ from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import basic from .serializers import basicSerializer class basicList(APIView): def get(self, request): basic1 = basic.objects.all() serializer = basicSerializer(basic1, many=True) return Response(serializer.data) def post(self): pass As you can see I am not using models.py anymore and serializers.py as some sort of model with the given email and phone fields. In order for my function to work (which is not at the moment), it needs to use get() method from the entered data and … -
SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted in django production?
I've a djagno app deployed on heroku. In one of the section i'm sending email to the user using smtp gmail settings. The emails are sent successfully when I run project locally but not on my same deployed project on heroku. I've seen many of the other answers on stackoerflow but none of them resolves my issue. I've enabled the 2FA on my google account and generated an APP password and using that password in my settings file. Turning on allow_less_secure_app option isn't suggested by other developers My settings.py file email settings- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER2') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS2') My views.py view handling the mail- def index(request) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): message = form.cleaned_data['message'] email = form.cleaned_data['email'] subject = "You got a message" thoughts = "{} by {}".format(message,email) recipients = ['xyz@gmail.com'] sender = 'abc@gmail.com' send_mail(subject, thoughts, sender ,recipients,fail_silently=False) return HttpResponse() else: form = MyForm() return render(request,'my_webapp/index.html',{'form':form}) The error I'm getting in heroku logs is- raise SMTPAuthenticationError(code, resp) 2019-10-07T18:22:12.174365+00:00 app[web.1]: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials w2sm9789664qtc.59 - gsmtp') -
how to fix "running scripts is disabled on this system" in vs code, i am using django2
i am trying to run server but its aint working and i can neither able to activate virtualenv.. winter\scripts\activate : File G:\enna\winter\scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + winter\scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess -
User logout by session in Django Rest Framework
I have a application, where frontend written by Angular 6 and backend - by Django Rest Framework. User logging out implemented on the frond whith following code: @Component({ selector: 'app-logout-modal', templateUrl: './logout-modal.component.html', styleUrls: ['./logout-modal.component.scss'] }) export class LogoutModalComponent implements OnInit { constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>, private router: Router, @Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { } logoutAndClose(): void { localStorage.clear(); this.thisDialogRef.close(); this.router.navigateByUrl(RouteUrls.Login); } } class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): @action(detail=False, methods=['post']) def logout(self, request): #??? return Response(status=status.HTTP_200_OK) That is, the user is not actually logging out. How can to implemet user logout by session on the DRF? -
How to set attr from model field in forms in django
How to set specific attribute for html template based on model method return value or just a model field name? I have already known it's possible to override fields by __init__ function or widgets like this: models.py class Item(models.Model): title = models.CharField(verbose_name=u"name", max_length=200, blank=False, null=False) def __str__(self): return ("%s" % self.title) forms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['title',] widgets = { 'title': forms.RadioSelect(attrs={ 'class': 'radioselect', 'item_name': 'title name?' # <- i want to have title name here of each not statis string }), } def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({ 'item_name': '' # <- i want to have title name here of each not statis string }) however, I want to set specific field name, based on previosly defined fields in model not just a static string like in above-mentioned example. If i add Item into a database with title = "Apple" i want to insert this string into this attribute to have such expected result like this in templates: <input type="radio" class="radioselect" item_name="Apple"> -
html page to download checkbox values(appending Y/N in values according to checked status) as a text file in specific folder
I have to develop a webpage with below requirements: A html form with 10 different checkbox in a table format Each check box is pre-checked with default value as "Y" When a user uncheck the checkbox, default value should display as "N" and vice versa There is a submit button in the bottom of the page, when clicked, all the values of checkbox(including unchecked) should be appended by Y if checked and N if unchecked, and then downloaded in a text file in a specific location. Example : [Checkboxes] Elements Enabled [Checked] Bob Y [Unchecked] Mary N [Checked] Marlo Y The text file should contain bobY MaryN MarloY Also, when submit button is clicked, user should be prompted with a pop-up saying "File is downloaded in the path : "The Path" " Thanks in Advance -
Django Translation - invalid token in plural form when running server
Django version 2.2.6; gettext 0.20 in Windows Environment I start using Python and Django to develop a webapp where translation is needed. Following tutorials, I ran makemessages and compilemessages without errors. Then, when I try to run the server I have the following error : ValueError: invalid token in plural form : Expression at getttext.py line 93. I already tried to flush and recreate my venv, removing my po/mo files and running the server, the error is still the same. It looks like Django mo files are causing this error and I don't know why. Probably a version mismatch between Python, Django and Gettext but I don't know how to fix it. Can you help ? -
When you exclude a field from a Django admin class, does that also prevent the field being set in a POST?
Say I have a model admin: class Customer(Model): name = CharField(max_length=255) secret = CharField(max_length=255, blank=True) @register(Customer) class CustomerAdmin(ModelAdmin): list_display = ['name'] exclude = ['secret'] The secret field is not going to appear in the admin. But if I programmatically create a POST with the secret field in, will Django prevent it from being set on the model? So is there any security risk in having an admin class for a model which has excluded fields that should not be written to from a web client? -
Reverse for 'facebook_login' not found
I keep getting: NoReverseMatch: Reverse for 'facebook_login' not found. 'facebook_login' is not a valid view function or pattern name when I try to use django-allauth. I have followed their documentation but I still can't figure out why I get this error. From django-allauth documentation, I have created: url urlpatterns = [ ('accounts/', include('allauth.urls')), ] AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 I have also added to installed apps the following: 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', indext.html {% load socialaccount %} <a href="{% provider_login_url 'facebook' %}">Facebook</a> -
How to choose child model while create parent?
Is there a way to choose child model as type of parent model in a parent creation form? Some code for example: from django.db import models class Parent(models.Model): title = models.CharField( max_length=100 ) some_attribute = models.PositiveIntegerField( null=True, blank=True, ) class ThinChild(Parent): name = models.CharField( max_length=300, ) class ThickChild(Parent): platform = models.CharField( max_length=300, ) Let's say i want to be able to create both of ThinChild and ThickChild from one form. Is it possible to do this, for example, by creating an instance of the Parent model and selecting the required child from the list of child models (let's name that field "child type"), so that depending on the choice a form appears with a fields set corresponding to the selected model? -
how can i automate project creation in django(from scratch to a simple helloworld website)?
Look at below code please. pipenv install django==2.1 pipenv shell django-admin startproject project . python mange.py runserver # check wether all things are alright or not. #Ctrl+c #go out of the server python mange.py startapp app #creat an app in your project # Add your app in settings.py at project folder by finding Installed_apps variable containing a list of installed apps like this and add another app url like this===>'app.apps.AppConfig' #Then go to views.py in your project's app folder and do this from django.http import HttpResponse def homePageView(request): return HttpResponse('Hello, World!') #then make a urls.py in your project's app folder and type this in it from django.urls import path from .views import homePageView urlpatterns = [ path('', homePageView, name = 'home') ] #The come to urls.py in project folder and add include to the imported functions from django.contrib import admin from django.urls import path, include#<== I mean this one Then add another path to urlpatterns containing a list urlpatterns = [ path('admin/', admin.site.urls), path('', include('shipping.urls'))#<==I mean this one ] then if no problem was found in this algorithm you are good to go to have your helloworld project. Is there anyway to automate all these scriptings? Is it possible to … -
django - save uploaded file to users group from the userprofile
I have a userprofile form that gets the username and the group he is assigned to, i want the file that the user uploads to be directly stored in the group folder that the user is assinged to. I achieve it when i follow this method, but The problem is in the form the username is a dropdown, if the user selects another name by mistake then the files are stored in that respective users group not the looged in users group views.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: initial = {'user_profile':request.user.username} form = uploadmetaform(initial=initial) return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username def nice_user_folder_upload(instance, filename): extension = filename.split(".")[-1] return ( f"{instance.user_profile.Assigned_Group}/{filename}" ) class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username') #, default=lambda: UserProfile.objects.get(id=1) tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") def __unicode__(self): return self.user_profile.user.username So how to avoide this, if i dont have to use the username in the form -
Python Django ValueError invalid literal for int() with base 10: 'telba.de_001'
I have tried to basically copy the behavior of 3 Different already functioning class-based Views views but getting this error and I don't get why. The Problematic class/model is in the "exten_int" area. Models: class context(models.Model): """Model representing a context. (for example telba.de)""" CONTEXT = models.CharField('Kontext', primary_key=True, unique=True, max_length=200, help_text='') COUNTRYPREFIX = models.IntegerField('Ländervorwahl', help_text='') CITYPREFIX = models.IntegerField('Ortsvorwahl', help_text='') ROOTNUMBER = models.IntegerField('Nummer') EXTENSIONSFROM = models.IntegerField('Nebenstellen von') EXTENSIONSTILL = models.IntegerField('Nebenstellen bis') PORTSCOUNT = models.IntegerField('Anzahl erlaubter Nebenstelen') CALLPERMISSIONS_CHOICES = ( (u'0', u'WorldWide'), (u'1', u'Europe'), (u'2', u'National'), (u'3', u'None'), ) CALLPERMISSIONS = models.CharField('Anrufberechtigungen', max_length=1, choices=CALLPERMISSIONS_CHOICES, help_text='') def __str__(self): """String for representing the Model object context.""" return self.CONTEXT def get_absolute_url(self): """Model representing a context.""" return reverse('context-detail', args=[str(self.CONTEXT)]) class sipuser(models.Model): """Model representing a SIPUser. (for example telba.de_525)""" SIPUSER = models.CharField('SIP-Nutzername', primary_key=True, unique=True, max_length=200, help_text='') CONTEXT = models.ForeignKey('context', verbose_name='Kontext', max_length=200, on_delete=models.SET_NULL, null=True) SIPPASSWD = models.CharField('SIP-Password', max_length=200, help_text='') NAME = models.CharField('Name', max_length=200, help_text='') NST = models.IntegerField('Nebenstelle', help_text='') EXTSIGNALNUMBER = models.IntegerField('Externe Anzeigenummer', help_text='') CALLERID = models.CharField('CallerID', max_length=200, help_text='') def __str__(self): """String for representing the Model object sipuser.""" return self.SIPUSER def get_absolute_url(self): """Model representing a SIPUser.""" return reverse('sipuser-detail', args=[str(self.SIPUSER)]) class exten_ext(models.Model): """Model representing external Routing z.b. 4921190096525 => context telba.de nst 525""" EXTEN_EXT = models.IntegerField('Eingehende Nummer geht auf', primary_key=True, unique=True, … -
Obtaining set within template using template tags
I've got a model of Review and a model of Answer. Multiple answers are related to each review by way of a foreign key as per below. Let's assume that I have 5 instances of the Review model and for each instance, there are 3 instances of a related Answer model. I'm trying to display all 15 of these answers in my template, but the code in my template isn't working. Views.py reviews = Review.objects.filter(user=user) Models.py class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) comments = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return str(self.user) class Answer(models.Model): review = models.ForeignKey(Review, on_delete=models.CASCADE, default=None) answer = models.IntegerField(null=True, blank=False) def __str__(self): return str(self.review) template.html {% for review in reviews %} {% for i in review.answer_set %} #I believe this is the problem {{i.answer}} {% endfor %} {% endfor %} -
Cannot resolve keyword 'model' into field. Django filters
I tried to rewrite filters, written on Django 1.1 to 2.1 I have a complex model, called Apartment that includes a Location model. Location includes the District model. So, there my models code: class District(models.Model): district_number = models.IntegerField(_('district')) title = models.CharField(_('district name'), max_length=100) city = models.ForeignKey(City, on_delete=models.PROTECT) class Meta: unique_together = ('city', 'district_number',) def __str__(self): return self.title class Location(models.Model): apartment = models.OneToOneField(Apartment, related_name='location', on_delete=models.CASCADE) coordinate_long = models.DecimalField(max_digits=15, decimal_places=10) coordinate_lat = models.DecimalField(max_digits=15, decimal_places=10) zip_code = models.IntegerField(_('zip')) district = models.ForeignKey(District, on_delete=models.PROTECT) subway_station = models.ForeignKey(SubwayStation, on_delete=models.PROTECT) city = models.ForeignKey(City, on_delete=models.PROTECT) address = models.CharField(_('human readable address of apartment'), max_length=250) def __str__(self): return self.address and filter is district = django_filters.ModelMultipleChoiceFilter( name="location_district", queryset=District.objects.all(), ) At new version I changed name to to_field_name. When I tried to launch, this drop an error - Cannot resolve keyword 'district' into field. Choices are: apartment_type, apartment_type_id, bedrooms_count, co_ownership, date_added, descriptions, economy_effective, economy_effective_id, energy_effective, energy_effective_id, favorite_lists, financial_info, floor, id, is_published, location, manager, manager_id, photos, plan, price, publish_type, publish_type_id, rooms, rooms_count, services, square, title, video_url I don't really understand how the ModelMultipleChoiceFilter works, and how can I get the nested model District from Location on it. -
DJANGO CRUD No module named 'django.contrib.name'
when I've open cmd and command this "python manage.py makemigrations" Then I've got this huge problem. I can't understad what to do. Please help. Traceback (most recent call last): File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'django.contrib' has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 123, in create import_module(entry) File "C:\Users\s\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.name' WHat should I change from setting.py file?: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.name', 'django.contrib.email', 'django.contrib.address', 'django.contrib.phone', ] -
Decode a value in django template
I am trying to decode a value from byte string in django-template. I have tried with field|stringformat :'i', but it won't work. Ex:- django template {{ pk:field }} The field value returns like this {'pk': b'122'} I need to get the value like {'pk':122} -
How can I include extra parameter in my Django Built-in Documentation and Swagger?
Any ideas how can I include extra parameter (I mean parameter after question mark accessible by request.GET.get('test')) in my Django Built-in Documentation and Swagger? By default documentations display only methods from the GenericAPIView and the fields from serializer_class but I am not sure how to include also this parameter? -
How to include custom functions in django serializers?
I've been trying all sorts of method but still cant seem to get this task done even through asking here with my previous questions. The problem is, I am trying to convert my data that is entered by the user on django's admin page to json data using rest. But before converting the data to json, I have 2 custom functions that validates the email and phone number fields entered by the user that uses packages from PyPI and I need these functions to run through the entered text values on the admin page. I dont know where to put my 2 functions in my python files, whether in models.py or serializers.py, Ive actually tried both ways but cant seem to get it to work. /* models.py */ import re import phonenumbers from django.db import models from phonenumbers import carrier from validate_email import validate_email class razer(models.Model): emailplus = models.EmailField() country = models.CharField(max_length=2) phone_number = models.CharField(max_length=100) def clean_emailplus(self): email = self.cleaned_data.get("emailplus") if not validate_email(email, check_mx=True, verify=True): raise models.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) # alpha_2 = self.cleaned_data.get("country") alpha_2 = self.cleaned_data.get("country") z = phonenumbers.parse(clean_number, "%s" % (alpha_2)) if len(clean_number) > 15 or len(clean_number) < … -
Is it possible to insert one model in another?
I have few models. Let's say in home.html I'm using Page model to create simple page structure via admin panel. Now I want add and display inside page multiple galleries. How I should do that ? Is it possible to have inside Page model (in my admin panel) fields with Gallery model ? class Page(models.Model): title = models.CharField(max_length=254) slug = models.SlugField(unique=True) is_active = models.BooleanField(efault=True) display_order = models.IntegerField(default=1) meta_title = models.CharField(max_length=100, null=True, blank=True) meta_description = models.TextField(null=True, blank=True) content = RichTextUploadingField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Meta: verbose_name = 'Home page' verbose_name_plural = verbose_name def __str__(self): return self.title class Gallery(models.Model): title = models.CharField(max_length=100) img = OptimizedImageField(upload_to='gallery') display = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Meta: verbose_name = 'Gallery' verbose_name_plural = verbose_name def __str__(self): return f'{self.id} {self.title}' -
How to have multiple sitemap classes in a single django app?
I have my_app in django 'my_project'. I have two models in my_app class Author(model): name = CharField(...) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) def get_absolute_url() kwargs = {'author_pk': self.pk, } return reverse('author', kwargs=kwargs) class Post(model): title = CharField(...) author = ForeignKey(Author, ...) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) def get_absolute_url() kwargs = {'author_pk': slef.author.pk, 'post_pk': self.pk, } return reverse('author', kwargs=kwargs) I have a file name sitemap in my_app folder as below: class AuthorSitemap(Sitemap): changefreq = "monthly" priority = 0.9 def items(self): return Author.objects.all() def lastmod(self, obj): return obj.updated_at class PostSitemap(Sitemap): changefreq = "monthly" priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated_at in my_project folder in urls file I have this: sitemaps = { 'my_app': PartnerSitemap, 'my_app': PartnerBlogPostSitemap, } urlpatterns = [ ... ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] As you see, I have a dictionary within which I have two items having the same key. I changed it as below. It still did not work: sitemaps = { 'my_app': [PartnerSitemap, PartnerBlogPostSitemap, ] } How should I make it work? -
How to dynamically pass arguments to forms in django?
I have a form 'BasicSearch', having two fields. One is a choice field called 'search_by' while the other is a text field called 'search_for'. I have models for customers, suppliers, items, projects and few others. What I want to do is to give user the ability to perform their searches on various models on their respective pages by providing their query in the text field and selecting from the choice field what they want to search in (the column headers from the models) I have already tried several solutions on stackoverflow but none is working for me. It works fine when I manually create a dictionary of column headers and pass it to the choice field. Currently the search form class looks like below (Which is not working) class BasicSearch(forms.Form): def __init__(self,arg): super(BasicSearch, self).__init__(arg) caller = arg if caller == 'customer': cu = Customers() field_dct = get_col_heads(cu) self.fields['search_by'] = forms.ChoiceField(choices=field_dct,widget=forms.Select(attrs={'class':'form-control'})) self.fields['search_for'] = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) The get_col_heads function: def get_col_heads(cu): all_fields = cu._meta.fields all_field_list = [] for fields in all_fields: column_head = (str(fields)).split(".") all_field_list.append(column_head[-1]) field_list = all_field_list[1:-2] field_dct = tuple(zip(field_list,field_list)) return field_dct customers view class in view.py class IndexView(TemplateView): template_name = 'crudbasic/index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context ['page_title'] = '' return …