Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display text with HTML-markup? (I use ckeditor)
I heard about filter '|safe', but if i undersand coorectly, that's unsafe and create a backdoor for injections. What are the alternatives to display full posts with formatting text? -
Django: Related model 'users.UserProfile' cannot be resolved
I tried running makemigrations and after migrate and I am constantly getting this error: ValueError: Related model 'users.UserProfile' cannot be resolved What I was trying to do is Link a UserProfile model to Django's own User Model: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) website = models.URLField(blank=True) bio = models.CharField(max_length=250, blank=True) full_name = models.CharField(max_length=250, blank=True) The "Contests" model (as you can see in my installed apps below) uses the User Model as well without any errors. My Installed apps look like this : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'social.apps.django_app.default', 'crispy_forms', 'pages', 'contests', ] My migration file 0001_initial.py is the following: # -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-30 15:45 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('website', models.URLField(blank=True)), ('bio', models.CharField(blank=True, max_length=250)), ('full_name', models.CharField(blank=True, max_length=250)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] Other notes: I use multiple settings files but my installed apps are all in my base setting file so this should not be the issue. … -
Parametrize django's migration to be skipped
Django 1.9 prepared me this migration (sqlmigrate output): ALTER TABLE `order` DROP FOREIGN KEY `order_manager_id_refs_id_2c366637`; ALTER TABLE `order` ADD CONSTRAINT `order_order_manager_id_20bba80d_fk_auth_user_id` FOREIGN KEY (`order_manager_id`) REFERENCES `auth_user` (`id`); it's just remove and add the same thing. I've just removed default values there, but according to django docs Django never sets database defaults and always applies them in the Django ORM code, so how to parametrize this migration to be just marked as done and do nothing on database ? -
Split python list in filtered list of multiple list and store them in single list
I have an exhaustive list of different categories with me: myList = [ {'name': 'Sasha', 'category': 'Dog'}, {'name': 'Meow', 'category': 'Cat'}, {'name': 'Bark', 'category': 'Dog'} ] I want them to break and a create smaller list within this bigList. It would be similar to this: bigList = [ [ {'category': 'Dog', 'name': 'Sasha'}, {'category': 'Dog', 'name': 'Bark'} ], [ {'category': 'Cat', 'name': 'Meow'} ] ] Here is the python logic for iterating the loop: bigList = [] prev = '' for s in myList: newList = [] if s['category'] != prev: for m in myList: if m['category'] == s['category']: newList.append(m) bigList.append(newList) prev = s['category'] This has done the trick for me but I would like to know how can I optimize the above logic in for loop for more shorter and efficient code. -
Django - ReverseManyToOneDescriptor' object has no attribute 'all'
I can see alot of related questions to mine and when i check them out, from what i can see my code should be working, but im getting the below error? models: class Circuits(models.Model): site_data = models.ForeignKey(SiteData,verbose_name="Site") order_no = models.CharField(max_length=200,verbose_name="Order No") expected_install_date = models.DateField() install_date = models.DateField(blank=True,null=True) circuit_type = models.CharField(max_length=100,choices=settings.CIRCUIT_CHOICES) circuit_preference = models.CharField(max_length=20,verbose_name="Circuit Preference",choices=settings.CIRCUIT_PREFERENCE,blank=True,null=True) circuit_speed = models.IntegerField(blank=True,null=True) circuit_bearer = models.IntegerField(blank=True,null=True) class CircuitMaintenance(models.Model): circuit = models.ForeignKey(Circuits,verbose_name="Circuit", related_name='maintenance') ref = models.CharField(max_length=200,verbose_name="Ref No") start_time = models.DateTimeField() end_time = models.DateTimeField() notes = models.TextField(blank=True,null=True) error circuits = Circuits.objects.filter(site_data__id=1) for i in Circuits.maintenance.all(): print i AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all' -
How to make AWS credentials accessible to boto in django environment?
I'm unable to create an S3 connection in my django environment via django-s3-storages middleware (I'm getting a 403 response from S3). Boto doesn't seem to be able to pick up the environment settings, and I suspect this is the cause (the traceback isn't helping much). As a diagnosis in manage.py shell: import boto boto.connect_s3() >>> boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials from django.conf import settings boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) >>> S3Connection:s3.amazonaws.com The docs (and other posts) indicate that these settings should work: MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = 'my-bucket.s3-website-eu-west-1.amazonaws.com' AWS_S3_HOST = 's3-website-eu-west-1.amazonaws.com' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'django_s3_storage.storage.StaticS3Storage' #S3 settings from https://github.com/etianen/django-s3-storage AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "yyy" AWS_S3_BUCKET_NAME = "my-bucket" AWS_S3_CALLING_FORMAT = "boto.s3.connection.OrdinaryCallingFormat" # Make user uploaded files public AWS_S3_BUCKET_AUTH = False AWS_S3_MAX_AGE_SECONDS = 60*60*24*365 # 1 year AWS_S3_GZIP = True Why isn't boto able to connect? -
Django user first_name is not required but has NOT NULL constraint in database
In my Django project I would like to have nullable User's first and last name. Django documentation say that last_name and first_name fields are optional. However when I want to insert values to auth_user table via SQL without first_name and last_name I got an error of not-null constraint INSERT INTO auth_user(id, password, last_login, is_superuser, username, email, is_staff, is_active, date_joined) VALUES (8, 'secret', null, false, 'user5', 'user@one.pl', false, true, current_date); ERROR: null value in column "first_name" violates not-null constraint I am using: Django 1.10 (upgraded from django 1.9 during project development) Postgresql 9.6 (upgraded from pg 9.5 during project development) django.contrib.auth.User By django admin site it is possible to create User without providing first_name and last_name. Could you please help me to know why there is such a mismatch and how can I insert via SQL User with empty first and last name? -
How to make "Article of the day"?
Want to show an unique Article or quote of the day. How can I organise that? One solution, I was thinking, is to create a cron task, that will change one field of my articles, like a weight, using Day–Stout–Warren algorithm. -
403 when trying to upload to s3 using django-s3-storages
I have a bucket my-bucket (with no periods) in eu-west-1 (Ireland). I'm trying to host my media files there using django-s3-storage middleware. MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = 'my-bucket.s3-website-eu-west-1.amazonaws.com' AWS_S3_HOST = 's3-website-eu-west-1.amazonaws.com' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'django_s3_storage.storage.StaticS3Storage' #S3 settings from https://github.com/etianen/django-s3-storage AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "yyy" AWS_S3_BUCKET_NAME = "my-bucket" AWS_S3_CALLING_FORMAT = "boto.s3.connection.OrdinaryCallingFormat" # Make user uploaded files public AWS_S3_BUCKET_AUTH = False AWS_S3_MAX_AGE_SECONDS = 60*60*24*365 # 1 year AWS_S3_GZIP = True I can do in manage.py shell: from boto.s3.connection import S3Connection from django.conf import settings conn = S3Connection(settings.AWS_S3_ACCESS_KEY_ID, settings.AWS_S3_SECRET_ACCESS_KEY) b = conn.get_bucket('my-bucket') key = b.get_key('test.txt') print(key.get_contents_as_string()) >>>this is a test from boto.s3.key import Key k = Key(b) k.key = 'test2.txt' k.set_contents_from_string('another test') >>>12 So I can read and write to the bucket via boto. I have enabled website hosting on the bucket, so I can view test.txt in my browser. I've set a completely open CORS policy too (while trying to get this working from my dev machine): <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> So, I don't know why I would get 403 Forbidden: Access Denied when actually trying to save a file from my app (it's not … -
Django - Can two or more templates be extended by one template?
Let's say there are base_a.html, base_b.html, a.html, b.html, c.html. a.html extends base_a.html and b.html extends base_b.html. And c.html have to extend both base_a.html and base_b.html. It will be easier to understand this situation if you think base_a.html contains reply functionalities and base_b.html contains search functionalities. Can I use multiple inheritance in Django template? Or do I have to use include instead of extends? -
Is there a way to create a django Template from a string with the configured backend?
New to django, I am loading template from a string, from django.conf import settings from django.template import Template, Context settings.configure() a= Template(template_variable) but getting exception: "No DjangoTemplates backend is configured.") ImproperlyConfigured: No DjangoTemplates backend is configured. -
django_prometheus model count() with caching
I have an django application with Apache Prometheus monitoring and model called Sample. I want to monitor Sample.objects.count() metric and cache this value for concrete time interval to avoid costly COUNT(*) queries in database. From this tutorial https://github.com/prometheus/client_python#custom-collectors i read that i need to write custom collector. What is best approach to achieve this? Is there any way in django to get Sample.objects.count() cached value and update it after K seconds? I also use Redis in my application. Should i store this value there? Should i make separate thread to update Sample.objects.count() cache value? -
Django-extension runscript No (valid) module for script
I'm trying to create a script that will populate my model "families" with informations extracted from a text file. This is my first post in StackOverflow, please be gentle, sorry if the question is not well expressed or not correctly formatted. Django V 1.9 and running on Python 3.5 Django-extensions installed This is my model: #it's in an app called "browse". from django.db import models from django_extensions.db.models import TimeStampedModel class families(TimeStampedModel): rfam_acc = models.CharField(max_length=7) rfam_id = models.CharField(max_length=40) description = models.CharField(max_length=75) author = models.CharField(max_length=50) comment = models.CharField(max_length=500) rfam_URL = models.URLField() Here I have my script "familiespopulate.py". Positioned in the PROJECT_ROOT/scripts directory. import csv from browse.models import families file_path = "/Users/work/Desktop/StructuRNA/website/scripts/RFAMfamily12.1.txt" def run(file_path): listoflists = list(csv.reader(open(file_path, 'rb'), delimiter='\t')) for row in listoflists: families.objects.create( rfam_acc=row[0], rfam_id=row[1], description=row[3], author=row[4], comment=row[9], ) When from Terminal i run: python manage.py runscript familiespopulate it returns: No (valid) module for script 'familiespopulate' found Try running with a higher verbosity level like: -v2 or -v3 The problem must be in importing the model "families", I'm new to django and I cannot find any solution here on Stackoverflow or online. This is why I ask for your help! Do you know how the model should be imported? Or... Am I … -
How can i make signals in django which can differentiate between put and post method?
I am using in built Django user and want to generate notification for each added user but I don't want notification to generate on put method.It should only generate on post request . My model is... Models.py class User(AbstractUser): gender= models.CharField(choices=GENDER, max_length=10, null=True, blank=True) role= models.CharField(choices=ROLE_CHOICE, max_length=15, null=True, blank=True) designation=models.CharField(max_length=225,null=True,blank=True) employee_id = models.CharField(max_length=20, default=None, null=True) class Notification(models.Model): text = models.CharField(max_length=225) recipient=models.ForeignKey(User,related_name='notification') timestamp = models.DateTimeField(null=True,blank=True,auto_now_add=True) unread = models.BooleanField(default=True, blank=False) send_by= models.ForeignKey(User, null=True,blank=True, related_name='Notification') and in my signals I have made like.... Signals.py @receiver(post_save, sender= Any_model) def comment_recieved(sender,**kwargs): obj= kwargs.get('instance') recipient=User.objects.get(is_superuser=True) Notification.objects.create( recipient= recipient, comment= obj, project=obj.project, type="commented", send_by=obj.supporter, text= "%s has commented on %s" % (obj.supporter, obj.project) ) return None Now the problem is everytime you do either a put or post request,it saves the user instance and so it creates a Notification object.I want to create Notification only when new user is created. -
Unable to access django admin panel in a django angular project
I am using AngularJS for my front-end and Django with Django rest framework as back-end. I have used angular's ui-router to connect to backend via DRF's rest api. I want to access django's admin panel and DRF's browsable api in development environment. Should I create a route in angular to access it and put some permission's on the server side or is there a better way to achieve this? -
Accessing dictionary in django template engine
lets say I have a dictionary called credit_facilities, where I map credit facility id to its verbal reprsentation. credit_facilities = {1 : 'Yes',2:'No',3:'Not sure'} I have model object where I retrieve values to be used as key for the dictionary. For instance lets say the model is named "customer" and it has attribute called "credit_facility". So, customer.credit_facility give either 1,2 or 3. I want to use this value as a key in dictionary. Meaning, is there an equivalent in django template language for the follwoing epression. credit_facilities[customer.credit_facility] -
django formset validating even though there are way too many
I have a formset that I wanted to have a somewhat arbitrary amount of forms with. Here are the formset classes. class ChartDatasetForm(forms.Form): """Giving the form a dataset, meant to be repeated with formsets""" data_label = forms.CharField(label="Data Label", max_length=100) dataset = forms.CharField(label="Data", max_length=1000) ChartDatasetFormset = formset_factory( ChartDatasetForm, min_num=1, validate_min=True, max_num=1000, validate_max=True) and then I have some tests like this... class FormTests(TestCase): """Testing that the forms work as expected""" def setUp(self): """Setting up data for forms""" self.dataset = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MIN_NUM_FORMS': 1, 'form-MAX_NUM_FORMS': 1000, 'form-0-data_label': '', 'form-0-dataset': '', 'form-1-data_label': '', 'form-1-dataset': '', } def test_chart_dataset_validates_with_2_sets(self): """Testing that the form validates when there are two datasets""" for n in range(2): self.dataset['form-%s-data_label' % n] = 'the labels' self.dataset['form-%s-dataset' % n] = '1, 2' form = ChartDatasetFormset(self.dataset) self.assertTrue(form.is_valid()) def test_chart_dataset_validates_with_3000_sets(self): """Running up to the max amount of forms to see if it validates""" for n in range(3000): self.dataset['form-%s-data_label' % n] = 'the labels' self.dataset['form-%s-dataset' % n] = '1, 2' form = ChartDatasetFormset(self.dataset) form.clean() self.assertTrue(form.is_valid()) as you can see, the chart is validating when there are 3000 forms even though I set the max_num at 1000. Why is this? -
django load pickle with functional reference
I am tring to load the final model from pickle from django for live scoring. Below is the code: from sklearn.grid_search import GridSearchCV pipeline = Pipeline([ ('tfidf', TfidfVectorizer()), ('lreg', LogisticRegression()) ]) parameters = [{'tfidf__ngram_range': [(1, 2)], 'tfidf__max_features': [num_features], 'tfidf__stop_words': [None], 'tfidf__lowercase': [True], 'tfidf__preprocessor': [None], 'tfidf__sublinear_tf': [False], 'tfidf__tokenizer':[tokenize], 'tfidf__strip_accents': [None]}, {'lreg__n_jobs':[-1], 'lreg__max_iter': [10000], 'lreg__C': [1], 'lreg__random_state':[65] }] def tokenize(document): words = [] for sentence in sent_tokenize( tokens = [ preprocessor(t.lower()) for t in wordpunct_tokenize(sentence) if t.lower() not in stop_words] if tokens != "": words += tokens return words grid = GridSearchCV(pipeline, parameters, cv=2, verbose=1) grid.fit(X_train, y_train) Here "tokenize" is a custom defined tokenizer. I am dumping the final estimator into a pickle file as belows: from sklearn.externals import joblib joblib.dump(grid.best_estimator_, '__final_model.pkl', compress=1) Now if I load it from django view, it throws the following error: AttributeError: Can't get attribute 'tokenize' on <module '__main__' from 'manage.py'> Not sure how to solve this problem. Your help is highly appreciated. -
Aldryn Newsblog - Related articles from one blog instance in another
I am using Django CMS with two Aldryn NewsBlog instances. When I create an article I can set related articles only from that instance. Is it possible that I could see articles from all instances there? If it is not possible from NewsBlog settings any advice where to look for it in the code would be appreciated. -
Django 1.10 query a table using username from logged in user
I'm new to Django, creating a site where I want logged in users to see there own data provided in a table. This table has a field username. I want the users to see there own data in a listview. I can't figure out how I can query, using the username from User. To give you an idea of what I am doing, this is what I have as code: (I tried multiple other ways, but I can't get a string with the User login Name. from django.contrib.auth.models import User from django.views.generic import ListView username = User.username class RoosterListView(LoginRequiredMixin, ListView): queryset = Roosters.objects.filter(startvc__range=(DatumStart, DatumEind),username=CurrentUser).order_by("startvc")[:35] Thanks so much in advance. -
real time messaging and notifications django 1.10 python 3.4
i have been searching google with past 1 year in tools i got a few answers but i cant figure out what most of them are saying. i found swampdragon but the their website is down! django-socketio gives this error File "C:\Users\PRATIR~1.MO-\AppData\Local\Temp\pip-build-6xzx6fz5\django-socketio\django_socketio\utils.py", line 44 except IndexError, KeyError: ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\PRATIR~1.MO-\AppData\Local\Temp\pip-build-6xzx6fz5\django-socketio\ please help me out am stuck at it what other packages can i use ? -
Create a custom Query in Django 1.8
Consider below example: class Customer(models.Model): first_name = models.CharField() last_name = models.CharField() rental_date = models.DateTimeField() rented_car = models.ForeignKey(Car) class Car(models.Model): color = models.CharField() reg_no = models.IntegerField() I want to group all cars by customers (assuming that a customer cannot rent more than one car) and for each group return only the car with the most recent rental_date and get the name of the customer and the car reg_no. The SQL would look something like this: SELECT * FROM Customer c where rental_date = (SELECT max(rental_date) FROM Customer WHERE rented_car_id = c.rented_car_id); or like this: SELECT *, max(rental_date) from Customer group by rented_car; The resulted query-set would then be sorted by customer first_name or car reg_no and other filters may be applied (for example, getting only the blue cars or customers whose name starts with 'A'). Things that I have tried: Aggregation: from django.db.models Max Customer.objects.values('rented_car').annotate(max_start_date=Max('rental_date')) but this returns a dict containing primary keys of Car objects. I would need values from Customer too. Modifying the query to include a field from Customer (.values('rented_car', 'first_name')) would change the SQL and alter the final result. The second method I used is raw: Customer.objects.raw("""SELECT * FROM Customer c where rental_date = (SELECT max(rental_date) FROM … -
The `.create()` method does not support writable nested fields by default.
I have a big problem regarding the serialization of a Many to Many relationship with intermediate model in DRF: If the request method is get everything works perfectly. But as soon as i try to POST or PUT Data to the API I get the following Error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/generics.py", line 243, in post return self.create(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/mixins.py", line 21, in create self.perform_create(serializer) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/mixins.py", line 26, in perform_create serializer.save() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 888, in create raise_errors_on_nested_writes('create', self, validated_data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/djangorestframework-3.5.3-py2.7.egg/rest_framework/serializers.py", line 780, in raise_errors_on_nested_writes class_name=serializer.__class__.__name__ AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `manager.serializers.EquipmentSerializer`, or set `read_only=True` on nested serializer fields. I am not really sure … -
Django dynamically choose a foreign key relation model
I have a Comment model that I've been using for the News model: class Comment(models.Model): news = models.ForeignKey(News, on_delete=models.CASCADE) posted_by = models.ForeignKey(Student, on_delete=models.CASCADE) content = models.TextField(max_length=2048) posted_on = models.DateTimeField(auto_now_add=True) edited = models.BooleanField(default=False) last_edited_on = models.DateTimeField(auto_now=True) def __str__(self): return '{} - {}'.format(self.posted_by, self.news) But now I have a Materials model and I want to have comments there too, but to use the same Comments model. Is there a way to dynamically choose the foreign key relation (news = models.ForeignKey(...) -> news_or_material = ... or something like this). Of course I can write a separate model (MaterialComment), but I want to reuse my code. Then in my viewset I should do something like this (I am using Django REST Framework): def create(self, request, news_pk=None): news = get_object_or_404(News, id=news_pk) context = {'request': request, 'news': news} serializer = self.get_serializer_class()( context=context, data=request.data ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.validated_data, status=status.HTTP_201_CREATED, headers=headers ) I need to turn news_pk parameter from the URL to a pk of News or Material and respectively news_or_material = get_object_or_404(...) -
Django HTML POST parameters causes NoReverseMatch
I have an HTML post with two drop down lists, I want to send selected Country in those lists to the search() method that's in views.py and then send me to the results view. Whenever I add government and location as parameters for the html POST action or add their value in the search regex, I try this I get a NoReverseMatch from my index page: Reverse for 'search' with arguments '('', '')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['search/(?P[A-Z]{3})/(?P[A-Z]{3})/'] and I don't what I'm doing wrong to cause this error. (See comments in code) appname/views.py: from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from .models import Country, Embassy from django.template import loader from django.urls import reverse def index(request): country = Country.objects.filter() template = loader.get_template('appname/index.html') context = {'countries': country} return render(request, 'appname/index.html', context) def results(request, government, location): return HttpResponse("Here are the Embassies sent by %s, located in %s." % (government, location)) def search(request): countries = Country.objects.all() form = request.POST if request.method == 'POST': try: selected_government = get_object_or_404(pk=request.POST['government']) except (KeyError, Country.DoesNotExist): return render(request, 'appname/index.html', { 'error_message': "You didn't select a government.", }) try: selected_location = get_object_or_404(pk=request.POST['location']) except (KeyError, Country.DoesNotExist): return render(request, 'appname/index.html', { 'error_message': "You didn't …