Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nav-pills load content with ajax?
I have a Dashboard which stores informations about users in a database. If I call a user page the whole informations of this user will be loaded at once with a lagy loading time. The stored data is ordered behind different bootstrap nav-pills. <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active author-tabs" id="pills-summary-tab" data-toggle="pill" href="#pills-summary" role="tab" aria-controls="pills-summary" aria-selected="true"> Summary </li> <li class="nav-item"> <a class="nav-link author-tabs" id="pills-contact-tab" data-toggle="pill" href="#pills-contact" role="tab" aria-controls="pills-summary" aria-selected="true"> Contact Information </li> [...] </ul> <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-summary" role="tabpanel" aria-labelledby="pills-summary-tab"> [...content...] </div> [...] </div> Is it possible to lead each nav-pill content by clicking on the pill? Maybe that each content behind these tabs is separated in its own html and will be loaded if I click on the tab? I think there must be a way to do this with an ajax call but I'm not able to find the matchin .load function... If this is not possible what would be the correct way to load content from a view by clicking on a button and loading this content with an ajax call? -
Filtering objects in Django
Its not possible to filter in templates. So what are the other ways to get filtered objects in templates, in Django? Other than passing parameters with render? -
Django - download file from FileField()
I'm struggling with the following problem. I have a database model with FileField(). models.py class InputSignal(models.Model): input_file = models.FileField(upload_to='signals/', null=False, ) A view that displays records from this table. It also supports deleting specific rows. views.py def storage_list(request): signals = InputSignal.objects.filter(author=request.user) if request.method == 'DELETE': id = json.loads(request.body)['id'] signal = get_object_or_404(InputSignal, id=id) signal.delete() return HttpResponse('') else: return render(request, 'storage_list.html', {'signals': signals}) Template for this view looks like this: template.html {% for signal in signals %} <li> <h4>{{ signal.name }}</h4> <p class="mb-0 pb-0">Date of addition: <b>{{ signal.add_date_pretty }}</b> </p> <p class="mb-1">Date of the last analysis: {{ signal.last_edit_date_pretty }}</p> <h6 class="mb-1">Adnotations:</h6> <p>{{ signal.adnotations | safe | linebreaks | truncatewords:16 }}</p> <button class="btn btn-outline-warning mr-3">Download</button> <button data-id="{{ signal.id }}" onclick='delteSignal(this)' class="btn btn-outline-danger">Delete</button> </li> {% endfor %} What I would like to do is to download the file in signal.input_file via the browser to the disk after clicking the 'Download' button. -
How to get all related_name fields in django with serializers?
here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE) def __str__(self): return self.name here is my seralizers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) return totalprice,totalpieces class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') class UserSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' here is my view.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer class CompanyView(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer here is my urls.py from django.conf.urls import url, include from django.contrib … -
Update/Upgrade Django 1.8 project code to Django 2.0
I have a large django project built in 1.8 with about 14 apps and a large amount of dependencies. I already have a good idea about how I'm going to update the 2.7 code to 3.6 or possibly just make it compatible with both, however, I'm not sure what is the best practice and most efficient way to refactor/upgrade the django framework to 2.0 from 1.8. Bare in mind this thousands of lines of code so efficiency in terms of work is crucial. Thanks in advance for all suggestions! -
Django / DRF: Filter Reverse Foreign Key
I'd like to be able to filter on the relationship ONLY of a Django Model. Here's what the models look like: Identity(models.Model): username = model.CharField(max_length=512, unique=True) PaymentSource(models.Model): identity = models.ForeignKey( 'identity.identity', related_name='payment_sources', on_delete='CASCADE', blank=True, ) deleted_at = models.DateTimeField(blank=True, null=True, default=None) There's also complete serializer code for both. With Identity referencing the PaymentSerializer. How would I get an Identity serializer with DRF to pass back as a response, without including any PaymentSource models in the foreign key if deleted_at is not None? -
How to redirect page to other after validating recaptcha using "django-recaptcha "
I am working on this project: https://github.com/jypsi/opencabs. I have integrated django-recaptcha(https://github.com/praekelt/django-recaptcha) in the booking page.But when the recaptcha is validated the page doesn't proceeds further, I mean it doesn't redirects me to the next page. Is there some changes to be done in the views.py page? But when I comment out the captcha field page code(Booking.py) it redirects me to the next page. kindly help. Booking.py class BookingTravelForm(BaseBookingForm): captcha = ReCaptchaField( public_key="6LccU20UAAAAAI1twyn3TZT-feMSdy-U-I7iGFIn", private_key="my private key", ) Views.py FORMS = [ ('itinerary', booking_form.BookingTravelForm), ('vehicles', booking_form.BookingVehiclesForm), ('contactinfo', booking_form.BookingContactInfoForm) ] TEMPLATES = { 'itinerary': 'opencabs/index.html', 'vehicles': 'opencabs/booking_vehicles.html', 'contactinfo': 'opencabs/booking_contactinfo.html' } class BookingWizard(CookieWizardView): form_list = FORMS def get_context_data(self, form, **kwargs): context_data = super().get_context_data(form, **kwargs) context_data['settings'] = settings return context_data def get_form_kwargs(self, step): data = {} if step == 'vehicles': itinerary_data = self.get_cleaned_data_for_step('itinerary') data.update({'source': itinerary_data['source'], 'destination': itinerary_data['destination'], 'booking_type': itinerary_data['booking_type']}) return data def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, form_dict, **kwargs): data = form_dict['itinerary'].cleaned_data data.update(form_dict['vehicles'].cleaned_data) data.update(form_dict['contactinfo'].cleaned_data) booking = Booking(**data) booking.save() try: msg = ("Dear customer,\n" "We've received your booking request with ID: {}\n" "You'll receive a notification when your booking " "is confirmed!").format(booking.booking_id) if booking.customer_mobile: send_sms([booking.customer_mobile], msg) if booking.customer_email: send_mail('Booking request received', msg, settings.FROM_EMAIL, [booking.customer_email]) except Exception as e: print("SMS Error: %s" % e) return redirect( … -
Django url/route order not maintained
I have the following in my root URLconf module (there's more, but not important, so left out): urlpatterns = [ re_path(r'^password-reset-redirect-view/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_redirect, name = 'password_reset_confirm'), path('', include('search.urls')), path('', include('customer_portal.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), Here's the customer_portal.urls: urlpatterns = [ path('customer/contact/', views.contact), path('', views.home), re_path(r"^confirm-email/(?P<key>[-:\w]+)/$", views.email_verification, name="account_confirm_email"), ] Here's the rest_auth.registration.urls: urlpatterns = [ url(r'^$', RegisterView.as_view(), name='rest_register'), url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'), url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), ] As you can see both included urls.py urlpatterns have a view named 'account_confirm_email'. Somewhere in the code this is ran: url = reverse( "account_confirm_email", args=[emailconfirmation.key]) Since customer_portal.urls is included before rest_auth.registration.urls, I expect the route 'account_confirm_email' in customer_portal.urls to be returned by the above reverse method. But instead I get the rest_auth.registration.urls route URL. Just to be sure I commented out the route in rest_auth.registration.urls, and then I did get the correct URL (customer_portal URL) returned. (It is filled into an email, I check that email and see that I have the wanted url: http://127.0.0.1:8000/confirm-email/......./, instead of: http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/...../) Can anyone tell me why the customer_portal URL isn't the one being reversed in both cases? Django docs say: Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. -
Django dropdown filter with ajax?
I need to update my template when the user chooses a value of the dropdown list. Is there a possibility to do this with an ajax call or similiar? It would be perfect that if the user is selecting a value of the dropdown, this value would be send to my view and the content in my page would update without page refresh. I tried different things but nothing worked... Any suggestion is welcome. Here's my shortened code: models.py class Author(models.Model): id = models.IntegerField(primary_key=True) author = models.CharField(max_length=50) status = models.CharField(max_length=50) [...] views.py def authors(request): authors = Author.objects.all() if request.method="GET": authors = Author.objects.filter(status = filter) template <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Choose status </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">Staff</a> <a class="dropdown-item" href="#">Admin</a> [...] </div> </div> {% for author in authors %} {{author.author}} {% endfor %} -
django x++ in template
this is my code: {% for d in do %} {% x=0 %} <tr class="{{ class.x }}"> {% x++ %} <td>{{ d.year }}/{{ d.month }}/{{ d.day }}</td> <td>{{ d.customer }}</td> <td>{{ d.cost }} تومان</td> <td>{{ d.forwhat }}</td> <td>{{ d.description }}</td> </tr> {% endfor %} how I can do x++ in template? i get do from datebase and sort by year , month and day, now i want for each d in do add 1 to x and call class.x data from class: ['red', 'yellow', 'green', ...] -
Wrong URL returned after deploying on Google Cloud Platform using Dokku
Having used dokku to deploy my django/flask applications previously on EC2 AWS instances, I'm having trouble to do the same in Google Cloud VM instances. The returning URL after deploying the application happens to be: Application deployed: http://[vm-instance-name].[vm-instance-region-nmae].c.[project-name].internal Whereas, I'm supposed to get something similar to: Application deployed:http://[hostname]:[portname] -
pip wheel created without any python sub-packages
operating system and version Ubuntu 18.04 VM hosted by WIN10 Python version Python 2.7.15rc1 version of pip pip 18.0 description *I'm trying to package Django project and wheel created but without any python sub-packages what i'm missing please ?? * ## Folder structure ## <pre><font color="#729FCF"><b>.</b></font> ├── <font color="#8AE234"><b>manage.py</b></font> ├── setup.py └── <font color="#729FCF"><b>todobackend</b></font> ├── __init__.py ├── <font color="#729FCF"><b>todo</b></font> │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── <font color="#729FCF"><b>migrations</b></font> │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py └── <font color="#729FCF"><b>todobackend</b></font> ├── <font color="#8AE234"><b>__init__.py</b></font> ├── <font color="#729FCF"><b>settings</b></font> │ ├── base.py │ ├── __init__.py │ ├── release.py │ └── test.py ├── urls.py └── wsgi.py </pre> setup.py from setuptools import setup, find_packages setup( name = "todobackend", version = "0.1.0", description = "TodoBackend Djnago REST service", package = find_packages(), include_package_data = True, scripts = ["manage.py"], install_requires = ["Django>=1.9,<2.0", "django-cors-headers>=2.4.0", "djangorestframework>=3.8.2", "MySQL-python>=1.2.5", "uwsgi>=2.0" ], extras_require = { "test": [ "colorama>=0.3.9", "coverage>=4.5.1", "django-nose>=1.4.5", "nose>=1.3.7", "pinocchio>=0.4.2" ] } ) -
Django unique_together not working as expected
Consider the following model: BLOG = 'blog_post' TESTIMONIAL = 'testimonial' POST_TYPES = ( (BLOG, 'blog_post'), (TESTIMONIAL, 'testimonial'), ) class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=255, blank=True) content = models.TextField() post_type = models.CharField(max_length=20, choices=POST_TYPES, default=BLOG) class Meta: unique_together = (('slug', 'post_type',)) If I exclude any one of the fields in the unique_together constraint in my form. Django skips the validation of unique constraint on the model instance and I get the following error: (1062, "Duplicate entry 'another-article-blog_post' for key 'app_post_slug_post_type_dc5412bf_uniq'") After doing some googling I found that it is the default behavior. But I still have no idea how to approach this problem -
How can i access one model data from another and viceversa with reverse relartion ship
api for catalogs here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE) def __str__(self): return self.name here is my seralizers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Avg,Max,Min,Count,F,Q class CatalogSerializer(serializers.HyperlinkedModelSerializer): dynamic_data = serializers.SerializerMethodField() class Meta: model = Catalog fields = '__all__' def get_dynamic_data(self, obj): totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs')) totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price')) return totalprice,totalpieces class CompanySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Company fields = '__all__' class UserSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' here is my view.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer class CompanyView(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer here is my urls.py from django.conf.urls import url, include from … -
Background and other css features not showing in Django
base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DPU</title> <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"/> <style> h1 {color:red;} p {color:blue;} </style> </head> <hr> <h1>Disease Polling Unit</h1> <hr> {% block main_content %} {% endblock %} </body> </html> The background,fonts are not showing after including it as staticfiles in base.html.What could I be doing wrong? polls/static/polls/style.css li a { color:red; font-size:20px; } body { background:white url('images:pil1.jpg') no-repeat; } -
Django access raw ajax response in template
I've been successfully adding pre-populated ajax retrieved data to my templates like so (where I load the response data into the html attribute of data-resp): <img id="profile-pic" data-resp="profile_picture" /> However, now I want to be able to check the value of the response {{ if response.node_group == "Employee"}} {{ elif response.node_group == "Department"}} {{ endif }} But I can't seem to access the response data (below doesn't render). <p>{{response}}</p> <p>{{response.GET}}</p> <p>{{response.GET['node_group']}}</p> -
Unit Test django, not work for testing Login Page
I not understand. I use the technique since the official doc, but nothing work for me, it's very very boring. I always the status code 200, even when I make errors myself. I not understand, I want just execute a test for login page and inscription page. And when I connected, I want testing user profile page. This is my code : class LoginPageTests(TestCase): def test_login_user(self): c = Client() response = c.post('/login/', {'username': 'john', 'password': 'doe'}) self.assertEquals(response.status_code, 200) response = c.get('/profil/') print(response.content) same with username and password void I have status code 200.., same with any erros : class LoginPageTests(TestCase): def test_login_user(self): c = Client() response = c.post('/login/', {'DHSJDHSJKD': 'john', 'SJDSJDLKJ': 'doe'}) self.assertEquals(response.status_code, 200) response = c.get('/profil/') print(response.content) I have the status code 200..and response.content not work. Where is the problem ? I want just.. testing user login and profile page after login Thanks guys ! -
How to write a URL pattern for "/index/" and "/index/number/" pages?
In my django project, I would like to write a regex statement in the url file to cover the following addresses : http://example.com/activity http://example.com/activity/2018 my urls.py: urlpatterns = [ re_path(r'^(?P<year>[0-9]{4})/$', activity_index, name='index'), ] I can't do what I want when I write this way. So I have sent the {% url "activity: index" 2018%} code from the template file for now. But I want a code script without this statement. How can I make it more dynamic ? -
Handling media django
I am trying to handle the django static and media content. This is my code in settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am uploading files and videos to my site, everything is working fine even static and media content is being displayed. My actual doubt is- I am actually running in development environment. In production for collecting the static content generally python manage.py collectstatic is used and then it is handled. But in development according to docs, app called django.contrib.staticfiles is used serve static files. But what about media files, how are they served actually ?? When I upload a image it is getting stored to project_name/media/app_name insted of project_name/app_name/media/app_name as static files are being accessed from path similar to latter, why are media files being stored in different manner. Finally: How the media files got served in development ? How to serve media files in production ? -
django rest framework: How to not allow validation on a nested serializer data?
I have a serializer BookSerializer of model Book with a nested PageSerializer of model Page. Updating of a Book instance involves deleting all its Page instances followed by creation of these Page instances, maybe with or without this updation involving some new data of pages or nothing or existing. But my Book model holds a constraint where each Book instance can only have max 100 pages each. And the validation check is done inside the PageSerializer's validate method. I have another reason to do this here: def validate(self, attrs): #some logic here raise some error if book instance already has 100 pages or if it will have more than 100 pages when combined with new pages when added. The update method definition of a serializer or say BookSerializer is: def update(self, instance, validated_data): ... ... So, the data being sent to update is already being validated and can be accessed as validated_data inside the update method. Now, here's the problem. The nested serializer PageSerializer has a validate method which checks how many pages of that Book instance are already there and validates against them. Let B be an instance of Book already having 100 pages. If I try to udate … -
Is it safe to use Django south for handling migration on big project
From long time i am having migration issues. Each time i am droping my postgres database and creating a new When i add new 3/4 table or a relation or Circular migration happens. Or most of the time some unwanted issue comes in migration. But it's okay as long i am in development phase. But very soon when it will be on production i can't do that. Removing database each time. I have heard a lot about django-south. But the issue is it's not updated from long time i think last time it was updated December,14(according to it's bitbucket repo). Now is it a good choice for a project of 2018 ? Or any other 3rd party i can use. I just don't want to take rick writing raw sql each time in production as i am not too good on it as well. So i want to depend on django 100% in migration. Please share you ideas on the migration issue Thanks in advance :) -
django.urls.exceptions.NoReverseMatch: Reverse for 'results' not found. 'results' is not a valid view function or pattern name
Views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from . models import Question from django.template import loader, RequestContext # Create your views here. def index(request): latest_questions = Question.objects.all()[:5] context = {'latest_questions': latest_questions} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except(): return render(request, 'polls/detail.html', {'question': question, 'error_message' : "Please select a choice"}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I get this no reverse match for results dues it not being a valid view function. I am new to django. How can I solve this?Does it mean there's an issue with my view.py code or what could be the issue as I am following a tutorial. polls/urls.py from django.conf.urls import url from . import views urlpatterns=[ url(r'^$', views.index,name='index'), url(r'^(?P<question_id>[0-2]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-2]+)/results', views.results, name='result'), url(r'^(?P<question_id>[0-2]+)/votes', views.vote, name='vote'), ] -
Django ORM group by with IN
Долго искал, ничего не нашел. Есть модель: class Rating(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='Пост') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Пользователь') rating = models.IntegerField(verbose_name='Оценка') date = models.DateTimeField(auto_now_add=True, verbose_name='Дата', blank=True, null=True) class Meta: db_table = 'rating' ordering = ['-id'] И мне надо на основе этой модели вывести средний рейтинг у определенных постов Запрос: select post_id, AVG(rating) from rating where post_id in (1,2,3,4,5,6) group by post_id order by post_id Пытался сделать так: Rating.objects.values('post_id').filter(post_id__in=post_ids).annotate(avg_rating=Avg('rating')) Но в конечном запросе идет группировка по id: SELECT `rating`.`post_id`, AVG(`rating`.`rating`) AS `avg_rating` FROM `rating` WHERE `rating`.`post_id` IN (1,2,3,4,5,6) GROUP BY `rating`.`id` ORDER BY `rating`.`id` DESC Как сделать группировку только по полю post_id? -
Passing parameters to a view function
Very new to Python and django so please bear with me. urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home) ] views.py from django.http import HttpResponse def home(request): return HttpResponse("Hello") What's unclear to me is how exactly the 'home' function is being called. If the that function requires a "request" parameter, how come it does not error out as you call it WITHOUT passing one? Or perhaps at least without explicitly passing one. I would have expected the calling to be something like "views.home(param)". -
djano rest framework error whilefetching through APIVIEW
here is my models.py from django.db import models class country (models.Model): country_name = models.CharField(max_length=200, null=True) def __str__(self): return self.country_name class state (models.Model): state_name = models.CharField(max_length=200, null=True) country = models.ForeignKey(country, on_delete=models.CASCADE, null=True) def __str__(self): return self.state_name class city (models.Model): city_name = models.CharField(max_length=200, null=True) country = models.ForeignKey(country, on_delete=models.CASCADE, null=True) state = models.ForeignKey(state, on_delete=models.CASCADE, null=True) def __str__(self): return self.city_name class publication(models.Model): title= models.CharField(max_length=300, null=True) country=models.ForeignKey(country, on_delete=models.CASCADE, null=True) state=models.ForeignKey(state, on_delete=models.CASCADE, null=True) city=models.ForeignKey(city, on_delete=models.CASCADE, null=True) def __str__(self): return self.title here is my seralizers.py from rest_framework import routers, serializers, viewsets from .models import * from django.contrib.auth.models import User from rest_framework import permissions class publicationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = publication fields = '__all__' here is my view.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import * from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,mixins,generics from django.http import Http404 from rest_framework import renderers class SnippetHighlight(APIView): def get(self,request): queryset = publication.objects.select_related('country','state','city') serializer_class = publicationSerializer(queryset,many=True) return Response(serializer_class.data) here is my urls.py from django.conf.urls import url, include from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns from api.models import * from api import views # from api.serializers import UserSerializer urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^snippets/', views.SnippetHighlight.as_view()), # url(r'^users/$', views.UserList.as_view()), # …