Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i add a onchange js event to Select widget in Django?
I need to attach a javascript onchange event to the receipt dropdown list in a Django project. When the value of the dropdown list is changed a js function is to be called. How can it be done? The form.py file is given below from django import forms receipt_types=(('option1','Option 1'),('option2','Option 2'),('option3','Option 3'),) class accountsInForm(forms.Form): receipt=forms.CharField(max_length=100, widget=forms.Select(choices=reciept_types)) -
Display a model field as readonly in Django admin
I want to display a model field ie module_name as read only in django user profile edit page. The model Category has a manytomany relationship with Profile model. Category id category_name module_name 1 A X 2 B Y profile_category id profile_id category_id 1 2 1 So for eg. when I am on the admin page to editing a user id of 2 then I would like to display the module name X if category id 1 is assigned to the user id 2 models.py class Category(models.Model): category_name = models.CharField(max_length=150, blank=False, null=True, default="", unique=True) module_name = models.TextField(blank=False, null=True) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile') phone_number = PhoneNumberField( blank=True, null=True) organisation = models.CharField(max_length=30, blank=True) category = models.ManyToManyField(Category) admin.py class ProfileInline(admin.StackedInline): model = Profile filter_horizontal = ('category',) class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_select_related = ( 'profile', ) Please suggest if this is possible or not. Any help/suggestion is highly appreciated. Thanks in advance. -
How to paginate django TemplateView
I wish to add pagination to the following in my views. I have added it to context_data but get a 'AgenciesByLocation' object has no attribute 'object_list'. So I need to define object list and I guess my question really is how do I define agency_list as object_list. class AgenciesByLocationMixin(MultipleObjectMixin): def get_context_data(self, pk, **kwargs): context_data = super(AgenciesByLocationMixin, self).get_context_data(**kwargs) place_list = Agencies.objects.filter(place__id=pk).filter(place__isnull=False) context_data["place_list"] = place_list city_list = Agencies.objects.filter(city__id=pk).filter(place__isnull=True).filter(po_box__isnull=True) context_data["city_list"] = city_list agency_list = list(chain(place_list, city_list)) context_data["agency_list"] = agency_list paginator = Paginator(agency_list, 10) page = request.GET.get('page', '1') try: p = paginator.page(page) except PageNotAnInteger: p = paginator.page(1) except EmptyPage: p = paginator.page(paginator.num_pages) return context_data def object_list(self, pk, **kwargs): **** What to put here to use agency_list as the object list **** class AgenciesByLocation(TemplateView, AgenciesByLocationMixin): def get_template_names(self, **kwargs): place_list = Agencies.objects.filter(place__id=self.kwargs['pk']).filter(place__isnull=False) city_list = Agencies.objects.filter(city__id=self.kwargs['pk']).filter(place__isnull=True).filter(po_box__isnull=True) agencies = list(chain(place_list, city_list)) if agencies: if agencies: return 'community_information_database/agencies_by_location.html' #elif self.kwargs['type'] == "printer_friendly": # return 'community_information_database/agency_full_printer_friendly.html' else: raise Http404 else: raise Http404 def get_context_data(self, **kwargs): context_data = super(AgenciesByLocation, self).get_context_data(**kwargs) return context_data -
Why am I receiving only one record during aggregation
I changes my code to code from this post : Link but I am receiving only one record ( should be 20 ). It looks like django aggregate all records. What I wanna do is execute such query using django model: SELECT week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total FROM table1 WHERE location = 'TgR' AND week_number BETWEEN 38 AND 42 AND part IN ('Q', 'F') GROUP BY week_number, part, type I'll be thankful for help, -
How to save records in relation manytomany Django
Good afternoon I have my application in Django 1.10, where I create a many-to-many relationship between the Beneficiario and Auxilio models, the beneficiario field being the key to this relationship, as you can see, I needed an additional field in the model that would be created by this relationship , so customize the model Auxilio_Beneficiario with 'through', to better understand: models.py class Dependencia(models.Model): dependencia = models.CharField(max_length=100) class Beneficiario(models.Model): nombre = models.CharField(max_length=100) numeroDocumento = models.BigIntegerField() class Auxilio(models.Model): auxilio = models.CharField(max_length=100) descripcion = models.TextField() dependencia = models.ForeignKey(Dependencia) beneficiario = models.ManyToManyField(Beneficiario, through='Auxilio_Beneficiario') class Auxilio_Beneficiario(models.Model): auxilio = models.ForeignKey(Auxilio) beneficiario = models.ForeignKey(Beneficiario) fechaEntrega = models.DateField(null=True) The problem that I have is that I do not know how to record the information in the model Auxilio_Beneficiario: views.py def asignaAuxilio(request): if request.method == 'POST': beneficiario = Beneficiario.objects.get(numeroDocumento=request.POST['documento']) # # #No se como grabar los campos auxilio,beneficiario,fecha de entrega # # return render(request, 'asignaAuxilio.html') Thanks for your help -
how to increment a global char inside a for loop? django
I am doing this in a view not in django template though I want to try incrementing a char in a for loop but somehow I keep on getting the same char. Cans someone give me a hand? I have something like this but it keeps on giving me B though start_char = 'A' for x in range(10): print(chr(ord(start_char) + 1)) -
Python/Django ORM filter by ManyToMany relationship where one object matches
I can't wrap my head around how to filter using Django ORM where ForeignKeys and ManyToMany fields are involved. I've done a ton of googling but can't find a similar case. Django documentation isn't helping much either. Here's the situation. I have apps. An app can have multiple releases. These releases have metadata, such as the platform versions they're compatible with. A release can be compatible with multiple platform versions. I want to find the latest release that's compatible with a specific platform version. So in Django, I have an App model and I have a Release model, with App being a ForeignKey. I also have a PlatformVersion model. On the Release model I have PlatformVersion as a ManyToManyField. I want to create a method on the App model that gives me the latest Release that is compatible with a specific PlatformVersion. It can be compatible with other PlatformVersions too, I don't care. But it needs to at least be compatible with that one PlatformVersion. Here's some code: class App(models.Model): def get_latest_filtered_release(self, **kwargs): platform_version = PlatformVersion.objects.get(name=kwargs.get('platform_version', None) return self.releases.filter(platform_versions__in=platform_version).latest() # When I try to run this I get "TypeError: 'PlatformVersion' object is not iterable" as expected class Release(models.Model): class Meta: … -
Bootstap:span class icon bar not working
I have used span class icon bar to display that three lines symbol after resizing the windows and other components should get displayed under that icon. But when I resize the window it only shows that icon and after clicking on it nothing happens This what I have done : what's gone wrong? Thank you in advance <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <! Header --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'ontheway:index' %}"> Way2go </a> </div> <! Items --> <div class="collapse navbar-collapse" id="#topNavBar"> <ul class="nav navbar-nav"> <li class="active"> <a href="{% url 'ontheway:index' %}"> <span aria-hidden="true"></span>&nbsp;&nbsp;Home </a> </li> <li class=""> <a href="#"> <span aria-hidden="true"></span>&nbsp;&nbsp;Hotels </a> </li> <li class=""> <a href="#"> <span aria-hidden="true"></span>&nbsp;&nbsp;Homestays </a> </li> </ul> <form class="navbar-form navbar-left" role="search" method="get" action="#"> <div class="form-group"> <input type="text" class="form-control" name="q" value=""placeholder="Search tourist places,hotels, homestays here"> </div> <button type="submit" class="btn btn-default">&nbsp;Search</button> </form> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="#"> <span class="glyphicon glyphicon-bell" aria-hidden="true"></span>&nbsp;Notifications </a> <li class=""> <a href="#"> <span aria-hidden="true"></span>&nbsp;Log in </a> </li> <li class=""> <a href="#"> <span aria-hidden="true"></span>&nbsp;Sign up </a> </li> </ul> </div> </div> </nav> -
User created custom Fields in Django
I'm working on a Django app for keeping track of collections (coins, cards, gems, stamps, cars, whatever). You can have multiple collections, each collection can have sets (Pirates cards, Cardinals cards, etc.) and then of course the individual items in each collection/set. Each item can contain multiple pictures, a name, and description, but here's where I'm unsure how to proceed. Each collection will need it's own set of values, or fields, that the user will need to determine (condition, dimensions in the appropriate units, coin thickness, model number, etc). How can I make custom fields such that the user can name the field and choose the input type (text, numbers, dropdown w/choices) and those fields will show up to be entered on each item within that collection? -
Django Form is Always Invaliad with ChoiceField
I recently added a ChoiceField to my form but now it always returns invalid; I verified this with a 'print(form.is_valid())'. All fields are displayed properly in my template and values are always being passing so I can't fathom why the form is returned as invalid. models.py class Lead(models.Model): Company_Name = models.CharField(max_length=180, default="No_Name", blank=True) Company_ID = models.BooleanField(default=True) Client_Name = models.CharField(max_length=180, default="No_Name_Provided", blank=True) Client_ID = models.BooleanField(default=True) Advertising = models.BooleanField(default=False) Automotive = models.BooleanField(default=False) Storage = models.BooleanField(default=False) Child_Related = models.BooleanField(default=False) Cleaning = models.BooleanField(default=False) Coffee = models.BooleanField(default=False) Computer = models.BooleanField(default=False) Internet = models.BooleanField(default=False) Dry_Cleaning = models.BooleanField(default=False) Education = models.BooleanField(default=False) Employment = models.BooleanField(default=False) Financial_Services = models.BooleanField(default=False) Fitness = models.BooleanField(default=False) Food = models.BooleanField(default=False) Eco_Friendly = models.BooleanField(default=False) Hair_Care_Beauty_Salon = models.BooleanField(default=False) Health = models.BooleanField(default=False) Nutrition = models.BooleanField(default=False) Home_Services = models.BooleanField(default=False) Maintenance = models.BooleanField(default=False) Management = models.BooleanField(default=False) Training = models.BooleanField(default=False) Miscellaneous = models.BooleanField(default=False) Pack_and_Mail = models.BooleanField(default=False) Pet_Related = models.BooleanField(default=False) Print_Copy = models.BooleanField(default=False) Real_Estate = models.BooleanField(default=False) Repair_Restoration = models.BooleanField(default=False) Retail = models.BooleanField(default=False) Senior_Care = models.BooleanField(default=False) Sports = models.BooleanField(default=False) Tanning_Salon = models.BooleanField(default=False) Travel = models.BooleanField(default=False) Vending = models.BooleanField(default=False) Home_Based = models.BooleanField(default=False) Investment_Level = models.CharField(max_length=2, choices=CATEGORIES, default=CATEGORIES[0]) forms.py class FormForReq(forms.Form): Company_Name = forms.CharField(max_length=180, required=False) Client_Name = forms.CharField(max_length=180, required=False) category = forms.BooleanField(initial=False, required=False) From_Home = forms.BooleanField(initial=False, required=False) Advertising = forms.BooleanField(initial=False, required=False) Automotive = forms.BooleanField(initial=False, … -
Calling api without knowing ip address in django
I have a post request http://localhost:8000/api/orders/shipment what i want to do is i dont want to pass domain/ip address and access the api something like Django admin console give "172.18.0.1 - - [08/Sep/2017 14:30:29] "POST /adminorder/order/import/ HTTP/1.1" 200 " I searched in the django documentation get_absolute_url() method is there to define custom urls, I am not getting how to use this in this scenario. -
Django - IntegrityError, UNIQUE contraint failed but there are no existing records
I'm on Django 1.11.3. I try to create an object: obj = cls.objects.create(type=type, token=token, value=value) ...which fails with: IntegrityError: UNIQUE constraint failed: intel_property.type, intel_property.token I have a unique index like so: unique_together = ( ('type', 'token'), ) Fair enough. Let's see what it's clashing with: >> cls.objects.filter(type=type, token=token) <QuerySet []> Weird-- there are no existing records with these values. I standardized the token field as all uppercase and the value of token is similarly uppercase, so this isn't a case-insensitivity issue. As part of troubleshooting I force-uppered all token values. I also tried searching by token alone and it still yields empty Querysets. If it matters, this query is deeply nested inside a series of transactions. Any ideas on what's going on here? -
How to post data to external API from django HTML in Json format
I am trying to post some data to an external API using json in django. I am also getting the data from an external API. Once the data is received, I am showing that on my HTML page. Now, what I am trying to do is select one of the options in the dropdown and click submit. Once the data is submitted, It should post to an external API. views.py import json, urlib def home(request): deviceroles = list() if request.method == 'GET' url = "http://netbox.com/deviceroles" response = urllib.urlopen(url) data = json.loads(response.read()) for i in range(0, len(data['results'])): devicerole = data['results'][i]['name'] deviceroles.append(devicerole) return render(request,"base.html", {'deviceroles': deviceroles}) base.html <label for="device_role" class="em-c-field__label">Device role</label> <select class="em-c-select em-c-select" id="file" placeholder="Placeholder">] {% for devicerole in deviceroles %} <optgroup> <option value="{{ devicerole }}" disabled="disabled" selected="selected">{{ devicerole }}</option> </optgroup> {% endfor %} </select> <button class="xys"> <span class"xyz" value="select">Submit<span> </button> Now, I have created a from and added the following in the views. I want to post to http://netbox.com/devices in json format class NameForm(forms.Form) device_roles = forms.CharField(label='device_role', max_length=100) views.py def device(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): payload = {'apikey' : apikey, 'device_role' : request.POST.get('device_role') response = request.get('http://netbox.com/devices', params=payload) else: form = Nameform() return render(request, "index.html", {'form': … -
how to add **dyno** in heroku?
In the present, I am running 2 dynos in my heroku app. I want to add one more dyno. worker: python manage.py runworker What should I do to add dyno? -
Why won't serialize capture annotate fields?
I had no idea adding data to a queryset would be so hard. It's like, if it didn't come directly from the db then it might as well not exist. Even when I annotate, the new fields are 2nd class citizens and aren't always available. Why won't serialize capture my annotate fields? class Parc(models.Model): # Regular Django fields corresponding to the attributes in the # world borders shapefile. prop_id = models.IntegerField(unique=True) #OBJECTID: Integer (10.0) shp_id = models.IntegerField() # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField(srid=2277) sale_price=models.DecimalField(max_digits=8, decimal_places=2, null=True) floorplan_area=models.DecimalField(max_digits=8, decimal_places=2, null=True) price_per_area=models.DecimalField(max_digits=8, decimal_places=2, null=True) nbhd = models.CharField(max_length=200, null=True) # Returns the string representation of the model. def __str__(self): # __unicode__ on Python 2 return str(self.shp_id) parcels = Parc.objects.filter(prop_id__in=attrList).order_by('prop_id')\ .annotate(avg_price=Avg('sale_price'), perc_90_price=RawAnnotation('percentile_disc(%s) WITHIN GROUP (ORDER BY sale_price)', (0.9,)), ) geojson = serialize('geojson', parcels) When I print geojson it has no key/values for avg_price or perc_90_price. At this point, I'm leaning towards creating a dummy field and then populating it with the my customer calculations after I retrieve the queryset but I'm open to ideas. -
Some form attributes are not appearing in QueryDict -- request.POST
What might be the reason? I have a form having various fields like : id, startdate, enddate, leave type, description and a submit button. While I was trying to access the description and submit button from views.py, I couldn't. Later I've tried to print request.POST and it was printing all other fields except description and submit button. I don't understand what possibly the reason could be.. Here is my HTML: <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <form class="form-horizontal" id="leave-form" role="form" action="{% url 'apply:add' %}" method="POST"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Apply Leave </h4> </div> <div class="modal-body"> <div class="form-group"> <label class="control-label col-sm-3" for="e_id">Employee-Id</label> <div class="col-sm-9"> <select class="form-control" id="e_id" name="e_id" class="required"> {% for entry in emp_data %} <option value="{{ entry.emp_id }}">{{ entry.emp_id }} - {{ entry.emp_name}} </option> {% endfor %} </select> </div> </div> <style> .datepicker { z-index: 1600 !important; border-color: black; } </style> <div class="form-group"> <label class=" control-label col-sm-3" for="s_dt">Start Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="s_dt" placeholder="Start Date" name="s_dt"/> </div> </div> <div class="form-group"> <label class="control-label col-sm-3" for="e_dt">End Date</label> <div class="col-sm-9" > <input type='text' class="form-control" id="e_dt" placeholder="End Date" name="e_dt"/> … -
Django model save()'s resistance to SIGTERM
I have a celery task which generates some data and saves them to the database using the Django's save() method. Sometimes I need to stop it which is done by sending a SIGTERM to it. I wonder, might it happen that I will be unlucky enough to send that signal in the middle of saving, ending up with some mess in the database and/or Django models? -
Django how to make internal api call?
Currently I'm using requests library to make an internal API call. But it fails on staging. class LoginSubscriber(generics.GenericAPIView): queryset = User.objects.all() serializer_class = LoginSerializer client_id = settings.client_id client_secret = settings.client_secret def user_logged_in(self, username, password, host): data = [('grant_type', 'password'), ('username', username), ('password', password), ('scope', 'read')] return requests.post(self.protocol + host + '/oauth/token/', data=data, auth=(self.client_id, self.client_secret)) # def post(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): data = serializer.data host = request.META['HTTP_HOST'] logged_in_token = self.user_logged_in(request, data['username'],data['password'], host) if logged_in_token: return Response({'token': logged_in_token.text}, status=status.HTTP_200_OK) return Response({'status': 'Failed Authentication'}, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is there any way to achieve this without requests library? -
Trying to test Django app with model that has BLOB column
I have a Django app that uses a model that has a BinaryField column my_col. My db is Oracle 12c and my_col is of type BLOB . I created a fixture for the model by serializing part of the database to json. However, when I run the test I always get a django.db.utils.DatabaseError: Problem installing fixture . . . Could not load revisorsite.PublishDocument(pk=1988554): ORA-01461: can bind a LONG value only for insert into a LONG column Can anybody help? -
Ubuntu + Python3.6 + Apache2_web access error: No module named django.core.wsgi
Ubuntu16(x64) + Python3.6(installed by anaconda) + Django1.11.3(installed by conda) + Apache2.4.18. With this configuration__ect/apache2/site-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/mblog WSGIDaemonProcess mblog python-path=/var/www/mblog WSGIProcessGroup mblog WSGIScriptAlias / /var/www/mblog/mblog/wsgi.py <Directory /var/www/mblog/mblog> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> </VirtualHost> and the apache www directory for python project as below: enter code here/var/www/mblog/(755) |-- manage.py(755) | |-- mblog(dir 755) | `|-- wsgi.py(644) | `-- urls.py(644) |-- templates(dir) | `-- *.html(644) The wsgi.py is configured as below (the files is granted): import os, sys sys.path.append('/var/www/mblog/mblog') # poiting to the project settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mblog.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() After all of these config, the browser display:"500 Internal Server Error" So I look for the error of /var/log/apache2/error.log as below: File "/var/www/mblog/mblog/wsgi.py", line 31, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi I am confused about all of the explain of website explanation but all of these cannot solve this question. https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/ Could you please give me a hand to solve this problem? Thank you! -
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I can not locate this error. Error is genereted after I added one field in disease that is contact and taggable manager in models If that is correct than is this error is generated due to Id field that I gave manually Help to me get out of this!! personal(myapp)/urls.py urlpatterns = [ url(r'^.*doctorsu/$', views.doctorsu.as_view(), name = 'doctorsu'), url(r'^.*disease/$', views.AddDisease.as_view(), name = 'AddDisease'), ] mysite/urls.py urlpatterns = [ url(r'^$',include('personal.urls')), url(r'^taggit/',include('taggit_selectize.urls')), ] models.py class DoctorSignup(models.Model): contact_regex = RegexValidator(regex=r'^[789]\d{9}$',message="Phone number must be start with 7,8 or 9") doid = models.AutoField(verbose_name='Doctor Id',primary_key=True,default=0) email = models.CharField(max_length=50) contact = models.CharField(validators=[contact_regex]) class TaggedSymptoms(TaggedItemBase): content_object = models.ForeignKey("Disease") class TaggedMedicine(TaggedItemBase): content_object = models.ForeignKey("Disease") class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True,default=0) dName = models.CharField(max_length=20) dtype = models.CharField(max_length=10) symptoms = TaggableManager(through=TaggedSymptoms) symptoms.rel.related_name = "+" medi = TaggableManager(through=TaggedMedicine) medi.rel.related_name = "+" views.py class doctorsu(TemplateView): template_name = 'personal/doctorsu.html' def get(self, request): dsform = DoctorSignupForm() data = DoctorSignup.objects.all() args = {'dsform': dsform,'data': data} return render(request,self.template_name,args) def post(self, request): dsform = DoctorSignupForm(request.POST) if dsform.is_valid(): dsform.save() cd = dsform.cleaned_data args = {'dsform': dsform , 'cd': cd} return render(request,self.template_name,args) return render(request, 'personal/doctorsu.html') class AddDisease(TemplateView): template_name = 'personal/disease.html' def get(self, request): dform = DiseaseForm() ddata = Disease.objects.all() args = {'dform': dform,'ddata': ddata} return render(request,self.template_name,args) def post(self, request): … -
Django get_or_create with icontains
I'm getting an unexpected result using icontains in my get_or_create call. Take the following example: >>>team_name = "Bears" >>>Team.objects.get(name__icontains=team_name) # returns DoesNotExist as expected >>>team, created = Team.objects.get_or_create(name__icontains=team_name) >>>print(created) # Prints True as expected >>>print(team.name) # Prints an empty string! Why does this create a team with a blank name rather than "Bears"? The reason I'm using get_or_create here is that if a subsequent user posts something like "BearS" I want to get the correct team, not create a duplicate team with incorrect capitalization. -
how to upload picture in django and get real time upload
how can i upload a picture in django and see it upload instantly without the page reloading and how can i make my own gavatar just like the ones in twitter and Instagram and make a profile picture for the users -
Aligning posts in a django project + mdl
I am making a blog with django but when I try to align them next to each other, they appear under each other. the posts appear under each other. how can i make them horizontally aligned. here is my html: {% extends "blog/base.html" %} {% load blog_tags %} {% block content %} <div class="mdl-layout mdl-js-layout "> {% for post in posts %} <main class="mdl-layout__content"> <div class="mdl-grid "> <div class="mdl-card mdl-cell mdl-cell--6-col mdl-cell--4-col mdl-shadow--2dp"> <figure class="mdl-card__media"> <img src="{{ post.photo }}" alt="" /> </figure> <div class="mdl-card__title"> <h1 class="mdl-card__title-text">{{ post.title }}</h1> </div> <div class="mdl-card__supporting-text"> <p>{{ post.body|truncatewords:11 }}</p> </div> <div class="mdl-card__actions mdl-card--border"> <a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect kal" href="{{ post.get_absolute_url }}">Read More</a> <div class="mdl-layout-spacer"></div> <button class="mdl-button mdl-button--icon mdl-button--colored kal"><i class="material-icons">favorite</i></button> <button class="mdl-button mdl-button--icon mdl-button--colored kal"><i class="material-icons">share</i></button> </div> </div> {% endfor %} </div> </div> </main> </div> {% endblock %} -
get() got an unexpected keyword argument 'pk'
On an earlier question I asked about How to have two separate query-sets under the same class based view. The initial problem was a simple due to a syntax error but adter fixing it i got**:get() got an unexpected keyword argument 'pk'** I believe it to be a problem on how i wrote my views but i don't know how to fix it or what question to ask for research. views.py class ViewProfile(generic.ListView): model = Post template_name = 'accounts/profile.html' def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user kwargs = {'user': request.user} return render(request, 'accounts/profile.html', kwargs) def get(self, request): users =User.objects.all() object_list= Post.objects.filter(owner =self.request.user).order_by('-timestamp') args ={'object_list':object_list,'users':users} return render (request, self.template_name, args) urls.py # profilepage url(r'^profile/$', views.ViewProfile.as_view(), name='view_profile'), # profilepage url(r'^profile/(?/P<pk>\d+)/$', views.ViewProfile.as_view(), name='view_profile_with_pk'), profile <div class="col-md-4"> <h1>Friends</h1> {%for user in users %} <a href="{% url 'accounts:view_profile_with_pk' pk=user.pk %}"> <h3>{{user.username}}</h3> </a> {%endfor%} </div>