Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS static files are not working in Django, I am a beginner in Django and main.css properties are not being applied to my store.html
This is added in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.store, name="store"), ] urlpatterns += staticfiles_urlpatterns() views.py from django.shortcuts import render from django.template.context import RequestContext def store(request): context ={} return render(request, 'store/store.html',context) store.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <h3>store</h3> <img src="{% static 'images/cart.png' %}"> main.css body{ background-color: blue; } folder tree store->store->store.html static->css->main.css static->images->cart.png -
want to implement owl carousel but but but
I am trying to create a website using django and bootstrap. I am extending base.html into index.html. I have implemented navbar(from bootstrap) in base.html and want to implement owl carousel in index.html. Both base.html and index.html are in templates folder of my project. I tried placing css and js files like owl.carousel etc in <!-- THIS IS base.html--> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/owl.carousel.css"> <link rel="stylesheet" href="/static/css/owl.theme.green.min.css"> <script src="/static/js/jquery.min.js"></script> <script src="/static/js/owl.carousel.min.js"></script> <title>BURGERZONE-{% block title %} {% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/"> <h1>BURGERZONE</h1> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/menu">Menu<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/contact">Contact Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Today's special </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="/about">About Us</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> … -
Django DRF access parent serializer instance in many=True
Tl;dr: I need to access instance of parent serializer in child one while serializing in many=True mode. In my Blog model, I have field tabs = JSONField (stores list of tabs, showed in blog) I have ModelSerializer like this: class BlogShortListSerializer(serializers.ModelSerializer): tabs = TabsSerializer(read_only=True) class Meta: model = Blog fields = ['id', 'name', 'type', 'tabs'] and TabsSerializer: class TabsSerializer(serializers.ListField): def to_representation(self, data): # Taking list (generated by base class ListField) res = super().to_representation(data) # Taking Blog from parent serializer blog = self.parent.instance # Taking user from request user = self.context["request"].user # If it's not alowed to user to see "peoples" tab, remove it before showing. if not is_user_able_to_see_peoples(blog, user): if "people" in res: res.remove("people") return res When I use BlogShortListSerializer on a single instance, everything working fine: return Response(BlogShortListSerializer(blog).data) But if I use it on many objects, it doens't work. return Response(BlogShortListSerializer(blogs, many=True).data) Because in second case blog = self.parent.instance doesnt put Blog object into blog variable it put a whole list of blogs that was supplied to BlogShortListSerializer constructor. I've debugged DRF code, and found that, when in many=True mode, serializer walks through list of supplied items, and call child.to_representation just attribute value, and instance not being stored anywhere … -
How to add custom view in django adminlte?
I created an environment using pycharm & installed adminlte by git clone from https://github.com/app-generator/django-dashboard-adminlte.git. And installed adminlte3 , django3.1 & all requirements. Then run python manage.py runserver and registered a new user & was able to login ,view all pages, added new link to a html page. But I am unable to add view with jsonresponse to a button click on new page, geting Error 500 - Server Error. My new html page is {% extends "layouts/base.html" %} {% block title %} Layout Boxed {% endblock %} <!-- Element injected in the BODY element --> {% block body_class %} sidebar-mini layout-boxed {% endblock body_class %} <!-- Specific Page CSS goes HERE --> {% block stylesheets %} <!-- Google Font: Source Sans Pro --> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <!-- Font Awesome --> <link rel="stylesheet" href="/static/assets/plugins/fontawesome-free/css/all.min.css"> <!-- Theme style --> <link rel="stylesheet" href="/static/assets/css/adminlte.min.css"> <link rel="stylesheet" href="/static/assets/css/mapstyle.css"> <link rel="stylesheet" href="/static/assets/js/pages/gis/dist/map.css"> <style> .map { margin: 0; padding: 0; width: 900px; height: 500px; background:white !important; border:1px solid #ccc; } </style> {% endblock stylesheets %} {% block content %} <div class="content-wrapper"> <div id="lyrDiv"></div> <div id="map" class="map"></div> <button id="search">Search</button> </div> {% endblock content %} <!-- Specific Page JS goes HERE --> {% block javascripts %} <!-- jQuery --> … -
Why won't Django load my CSS files when I already used static?
I'm trying to create a website but idk why some of my CSS is not working on the page. I followed the format my teacher gave and his worked so idk why mine won't. in urls.py of the project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('system/', include ('system.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in HTML file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> in CSS file: .body{ background-color: yellow; } .title { color: #000; font-family: Arial Black; position: absolute; top: 0; left: 4%; } .list { color: #000; font-family: Arial; position: absolute; top: 10%; left: 10%; } When I python manage.py runserver, the page background is still white and the text is also white so I have to block them to see it. I tried to do the collectstatic but it gave a warning that it will overwrite existing files so I canceled it. My teacher also haven't taught us the collectstatic command. What am I doing wrong here? -
Why do my changes not save in static css files in django?
They used to save before, but all of a sudden they do not. I even have DEBUG = True and I have django.contrib.staticfiles in my installed apps. I'm not really what code I should provide, so if anyone needs any, please ask, and I'll send you the code. Thank You! -
How to send image from SketchCanvas to server
Application Image I use RNSkecthCanvas in React-Native then I want to send a drawing image to my server that use Django when I click save button in the bottom what keyword I have to search.I search then I see only how to upload image by select file in phone -
Trying to add a "add to wishlist button" in my Django web application
I'm trying to add an "add to wishlist" button to my page that lists books. When a user presses the button, it will add the isbn (pk of the books) along with the user id into the wishlist table. For some reason, it's not adding them into my database when I press the button. There are no errors shown so i don't know what's the problem. Here's my code #views.py class wishlistView(TemplateView): template_name = 'TextSearch/wishlist.html' def post(self, request, pk): isbn = self.request.POST.get('isbn') current_user = request.user book = wishlist(userid_id = current_user.id, ISBN_id = isbn) book.save() return my HTML code {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="hidden" value="{{book.pk}}" name="isbn"> <a href="{% url 'TextSearch:wishlist' book.pk %}" >Add To WishList</a> </form> {% else %} <a href="{% url 'User:RegisterView' %}" >Add To WishList</a> {% endif %} Thank You in advance, I'm new to Django. -
How to order by a field in an another model in Django
I have two tables here, one is called SystemPushLog and another called UserPermission, they are both have a user_id field with IntegerField. class SystemPushLog(models.Model): ... user_id = models.IntegerField(null=True) class UserPermission(models.Model): user_id = models.IntegerField(primary_key=True) expire_datetime = models.DateTimeField(null=True) # 会员过期时间 ... The reason why they are chosen IntegerField rather than an Foreignkey is bacause the User model is in another system. And we have to retrieve user info by gRPC remote function calls. So, we just save the user_id as an IntegerField. Now, I am stucking in how to order by expire_datetime field on another model UserPermission in queryset of SystemPushLog. The two table does not have relations except sharing the same user_id field. I have tried to implement using raw SQL like this: qualified_ids = [item.id for item in queryset] queryset = SystemPushLog.objects.raw("""RAW SQL IGNORED""") ordered_log_ids = [item.id for item in queryset] clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(ordered_log_ids)]) ordering = 'CASE %s END' % clauses queryset = SystemPushLog.objects.filter(id__in=ordered_log_ids).extra( select={'ordering': ordering}, order_by=('ordering',) ) # Now the queryset is ordered... But, it runs really slowly. Maybe it is because of clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in … -
Trouble using python dictionary in a Django template
So I have a python dictionary storing the size and the amount each size has, titled final_list. Then I'm passing that to the template using "sizes": final_list. In the html template, I'm trying to create a drop-down selection with all the sizes, and only display sizes that are available, or have an amount not equal to 0. The problem is, it seems as if it isn't accepting the dict or something, since the dropdown shows up empty. Below is the code I have, any help would be much appreciated. Views.py I'm getting the sizing info from a model called 'Size' then checking if there are 0 objects of that size. Then I'm creating the dictionary to only have sizes that are actually available. from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key) def product(request, code): sizes = Size.objects.get(code=code) all_size = ['small', 'medium', 'large', 'XL'] final_list = {} for size in all_size: if getattr(sizes, size) == 0: pass else: final_list[size] = getattr(sizes, size) return render(request, "website/listing.html", { "sizes": final_list }) HTML (website/listing.html) <form method="POST"> <select name="sizes" style="width: 90px; height: 20px;"> {% csrf_token %} {% for size in sizes %} {% if final_list|get_item:size != 0 %} <option>{{size}}</option> {% endif %} {% … -
My django custom form validation errors are not being rendered
In my project, i am applying some custom validation to some fields in my forms rewriting the clean method in the form class, however when i simply render the error itself, it is displayed in my template, but when i render it as text it does not. Forms class InsuranceInformationForm(forms.ModelForm): expiration_date = forms.DateField(widget=forms.SelectDateWidget(years=years)) class Meta: model = InsuranceInformation exclude = ('patient',) def clean(self): cleaned_data = super().clean() carrier = cleaned_data.get('insurance_carrier') insurance_type = cleaned_data.get('type_of_insurance') if (carrier and not insurance_type) or (insurance_type and not carrier): self._errors['Insurance'] = self.error_class(["Insurance information incomplete."]) return cleaned_data Models class InsuranceInformation(models.Model): INSURANCE_TYPE_CHOICES = ( ('MEDICAL', 'Medical'), ) insurance_carrier = models.OneToOneField(InsuranceCarrier, on_delete=models.CASCADE, blank=True, null=True, verbose_name='insurance carrier', related_name='insurance', unique=True) type_of_insurance = models.CharField('insurance type', max_length=50, blank=True, null=True, help_text='Type of insurance', choices=INSURANCE_TYPE_CHOICES) expiration_date = models.DateField('insurance date expiration', help_text='insurance date expiration') patient = models.OneToOneField(Patient, on_delete=models.CASCADE, blank=True, null=True, verbose_name='insurance owner', related_name='insurance') def __str__(self): return str(self.patient)+ "'s" + ' ' + 'Insurance Information' Template {%if insurance_form.errors%} {%for error in insurance_form.errors%} <p class="error">{{error.as_text}}</p> {%endfor%} {%endif%} -
Django request.POST.items() not behaving as expected
I have an incoming ajax request, if I print post that like this: print("post_data %s" % request.POST) I get this: post_data <QueryDict: {'csrfmiddlewaretoken': ['...'], 'contact_method 1[]': ['Facebook', 'https://www.facebook.com/aandro.veinilla/', 'Send me a message'], 'contact_method 2[]': ['Whatsapp', '+593998375445', 'contact me after 8pm']}> As you can see, it is a dict with some keys and the values are lists. But if I print it like this: for k, v in request.POST.items(): print("k: %s" % k) print("v: %s" % v) I get this: k: csrfmiddlewaretoken v: ...hEm9OcUE k: contact_method 1[] v: Send me a message k: contact_method 2[] v: contact me after 8pm It only prints the last item in each list, why? I need to iterate over the all the values received, not only the last item in the list. Also One weird thing that might have something to do (not sure) is that django appends '[]' to the dictionary keys. I'm sure I didn't do that in js. -
Sending a simple message from user to user in Django
I am trying to create a simple form that allows users to send messages to each other in Django. My model looks like this: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages_to') sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages_from') message = models.TextField(blank=True) unread = models.BooleanField(default=True) And my form looks like this: class MessageForm(forms.ModelForm): class Meta: model = Message fields = ('message',) I would like to display the form on the recipients profile page. I think I need to include the senders id in the url for django to know where the message is coming from, so I link to the recipients page with this url: path('profile/<int:user_id>/<int:sender_id>', ProfileDetailView.as_view(), name='profile_detail') Finally here is my view which renders the users profile page and the form to send the message: class ProfileDetailView(FormMixin, DetailView): model = Profile template_name = 'users/detail.html' form_class = MessageForm def get_object(self): profile = Profile.objects.get(pk=self.kwargs['user_id']) return profile def form_valid(self, form): instance = form.save(commit=False) instance.user = Profile.objects.get(pk=self.kwargs['user_id']) instance.sender = Profile.objects.get(id=self.kwargs['sender_id']) instance.save() return super(ProfileDetailView, self).form_valid(form) def get_success_url(self): return reverse('/') Currently the page and form are rendering correctly however when I type a message into the form and click send the page only refreshes and turns blank. No message object is recorded in django-admin. Can anyone please help … -
Generating a default value based on the current number of items from a Django database - Circular Import Problem
I was working on a Django project but I can't really figure out on how can I avoid a circular import between a Django model and a custom python file generators.py accounts/models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils import timezone from core.generators import make_id_number class UserManager(BaseUserManager): def create_user(self, email, username, fname, lname, password, **others): if not email: raise ValueError(_('Please Provide Email Address!')) if not username: raise ValueError(_('Please Provide User Name!')) if not fname: raise ValueError(_('Please Provide First Name!')) if not lname: raise ValueError(_('Please Provide Last Name!')) email = self.normalize_email(email) user = self.model( email=email, username=username, fname=fname, lname=lname, password=password, **others ) user.set_password(password) user.save() return user def create_superuser(self, email, username, fname, lname, password, **others): others.setdefault('is_staff', True) others.setdefault('is_superuser', True) others.setdefault('is_active', True) if others.get('is_staff') is False: raise ValueError(_('Superuser must have \'staff\' permissions!')) if others.get('is_active') is False: raise ValueError(_('Superuser must be active!')) if others.get('is_superuser') is False: raise ValueError(_('Superuser must have \'superuser\' permissions!')) return self.create_user(email, username, fname, lname, password, **others) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email'),max_length=150,unique=True) username = models.CharField(_('Username'),max_length=150,unique=True) fname = models.CharField(_('First Name'),max_length=150) mname = models.CharField(_('Middle Name'),max_length=150,null=True,blank=True) lname = models.CharField(_('Last Name'),max_length=150) date_joined = models.DateTimeField(_('Date Joined'),default=timezone.now) last_login = models.DateTimeField(_('Last Login'),auto_now=True) is_staff = models.BooleanField(_('Staff'),default=False) is_active = models.BooleanField(_('Active'),default=False) … -
file upload to django rest application without using requests module
I am working on a system where i couldn't install any external library due to security reason so i have to depend upon inbuilt python module which will send http request to server. current python version in system is 2.7 For example below is my file upload code in django rest application views.py class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format='jpg'): up_file = request.FILES['file'] destination = open('/tmp/' + up_file.name, 'wb+') for chunk in up_file.chunks(): destination.write(chunk) destination.close() return Response(up_file.name, status.HTTP_201_CREATED) urls.py urlpatterns = patterns('', url(r'^uploadFile', views.FileUploadView.as_view()) Script to upload the file scripts.py file = "data.txt" with open(file, "w") as outfile: outfile.write() # writing some data to file headers = { 'Content-Type': 'text/plain', 'Content-Length': os.stat(filename).st_size, } request = urllib2.Request('http://localhost:8000/uploadFile/', open(file,'rb'),headers=headers) response = urllib2.urlopen(request) while executing i am getting below error in server side, i know i can easily do it using requests module but i am stuck because i couldn't use requests module and i am struggling to figure out how to do without using requests module. please help File "/code/pipeline/views.py", line 83, in post up_file = request.FILES['file'] File "/usr/local/lib/python3.9/site-packages/rest_framework/request.py", line 438, in FILES self._load_data_and_files() File "/usr/local/lib/python3.9/site-packages/rest_framework/request.py", line 275, in _load_data_and_files self._data, self._files = self._parse() File "/usr/local/lib/python3.9/site-packages/rest_framework/request.py", line 350, in … -
DateTimeField is null but doesn't appear for __isnull=True
I have a model with this field: block_date = models.DateTimeField(default=None, null=True) I want the block date to be unset when the model instance is created. Later, if the user gets blocked then the date is set. I want to select users that are not blocked meaning block_date is None. So I try to query all the models like this: Profile.objects.filter(block_date__isnull=True) <QuerySet []> Profile.objects.all()[0].block_date ***empty line*** Profile.objects.all()[0].block_date=="" False Profile.objects.all()[0].block_date==None True So if the block_date is None, why is the first queryset empty? -
Cannot disable label in Django modelformset_factory
On Django 2.2.16, Im trying to disable Django modelformset_factory with 'label': '' and 'label':False not showing any error but doest'n work, the forms.py looks like below, both version doesn't work. Bahanformset = modelformset_factory( Bahan, fields=('item', 'jumlah'), extra=10, widgets={'item': forms.Select(attrs={ 'class': 'tail-select w-full col-span-8', 'data-search': 'True', 'placeholder': 'Bahan', 'label':False, }) } ) or Bahanformset = modelformset_factory( Bahan, fields=('item', 'jumlah'), extra=10, widgets={'item': forms.Select(attrs={ 'class': 'tail-select w-full col-span-8', 'data-search': 'True', 'placeholder': 'Bahan', 'label':'', }) } ) -
Setting up OIDC for a backend API + frontend SPA
I’ve got a project using a Django backend, with Django Rest Framework to serve an API, and a Vue.js frontend SPA to consume the API. I’m running into some kind of CORS issue during authentication. I’ve been using mozilla-django-oidc to implement the Authorization Code flow with Okta. This works fine pretty much out of the box, and if I navigate to the API in my browser, I can login to Okta and I get a Django session. I’ve also enabled SessionAuthentication for DRF, which allows the same session cookies generated by Django to be accessible by the SPA (both SPA and API are on the same domain), provided I login first directly through the API. This all works fine until the id token expires. In Django, when the id token expires, I get a redirect to https://example.okta.com/oauth2/v1/authorize?..., the Authorization Code flow completes and I get sent on through to the originally requested page. Where things fail is in an ajax request from the SPA to the API with an expired id token. I get the same redirect, but this time it fails due to CORS. Access to XMLHttpRequest at 'https://example.okta.com/oauth2/v1/authorize?response_type=code&client_id=X&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Foidc%2Fcallback%2F&state=X&scope=openid+email+profile&prompt=none&nonce=X' (redirected from 'http://127.0.0.1:8080/api/X') from origin 'http://127.0.0.1:8080' has been blocked by … -
Referencing to self in Django Model
There are two user models in my application. amcdb.models.User django.contrib.auth.models.User First one is extended from second one. I have added a field creator to amcdb.models.User. Now I want to reference it to id field of django.contrib.auth.models.User What I have done ? class User(User): creator = models.ForeignKey(auth.models.User, on_delete=models.CASCADE, null=True, related_name='maker') But I'm facing error. ValueError: Cannot alter field amcdb.User.creator into amcdb.User.creator - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) What I'm missing ? Please help. -
Why isn't my bootstrap css applying in Django
I am currently learning django and I tried to apply bootstrap css for my little project but it keeps throwing this following error and doesn't apply. Refused to apply style from 'https://stackpath.bootstrapcdn.com/%20%20%20%20bootstrap/4.4.1/css/bootstrap.min.css' because its MIME type ('application/xml') is not a supported stylesheet MIME type, and strict MIME checking is enabled. This is my code. <!Doctype html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/ bootstrap/4.4.1/css/bootstrap.min.css" integrity=" sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>crm1</title> </head> <body> {% include 'accounts/navbar.html'%} {% block content %} {% endblock %} <hr> <h5>Our footer</h5> </body> </html> -
Trying a write a simple program and keep getting this error
Error : TemplateDoesNotExist at /1 forms.py class SpotifyForm(forms.Form): SpotifyForm = forms.CharField(label= "Spotify Form") views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.views import View from .forms import SpotifyForm from .api import SpotifyAPI from .forms import ClientId class Search(View): form = SpotifyForm initial = {"initial" : "Error"} template_name = "homepage.html" context = {"form": form} def get(self, request, *args, **kwargs): form = self.form(initial = self.initial) return render(request , self.template_name, self.context) urls.py from django.urls import path from .views import Search urlpatterns = [ path("1" , Search.as_view()) ] templates directory: spotify_client\spotify_calls\spotify_calls\templates urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path("" , include("spotify_calls.urls")) ] Basically, all I am doing is trying to access the Spotify API in the views.py(not done yet), just wanted to render the html to at least see if the form will show but nothing did. Also, all recommendations with class based views will be appreciated since this is my first time -
gcloud FileNotFoundError lib64
Why do I get the following error when trying to deploy to Google Cloud App Engine? gcloud crashed (FileNotFoundError): [Errno 2] No such file or directory: '/home/.../.../venv/lib64' That directory exists on my local machine but the only reference to lib64 in my code is in the .gitignore file. The Error seems to be connected to my environment, but I'm not sure how to fix this. Any ideas? -
XMLHttpRequest blocked due to a CORS related issue?
I'm somewhat new to programming and would very much appreciate any help or guidance. I'm working on a project where the back end is made up of Python/Django and I have a React.js front end. Everything works fine when I'm in my local host or development environment, but when I deployed to heroku and switched to production I'm not able to make any requests with my API. I receive the following error in the console: Access to XMLHttpRequest at 'heroku-project-app.com' from origin 'current-github project.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Admittedly, some of my project came from a template my former coding bootcamp provided, but I know nothing of CORS. Is there some kind of configuration or setup I have to create? Are there any resources that cant help me better understand? I don't even know if there is code I should be providing to help anyone better understand my question. If there is, please ask me and I'll be more than happy to follow up. -
URLs with no prefixes
I wonder if it is possible to access all pages and its detail pages without any extra prefix. Example: ''' /vegetables /carrot --> (detail page for vegetables) /fruits /apple --> (detail page for fruits) ''' and different views should be used for fruits and vegetables. Sample URL patterns, #urls.py urlpatterns = [ path('', views.index, name='index'), path('fruits/', views.all_fruits, name='fruits'), path('vegetables/', views.all_vegetables, name='vegetables'), path('<slug:slug>/', views.fruit_detail, name='fruit'), path('<slug:slug>/', views.vegatable_detail, name='vegetable'), ] Predictably; when trying to access the vegetable detail page, gives an error because of using fruit's views. Thanks in advance for your help and feedback. -
KeyError: 'request' in DRF with ModelSerializer
serializers.py from rest_framework import serializers from .models import Flight, Segment, Airport class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) fields = self.context['request'].query_params.get('fields') if fields: fields = fields.split(',') # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class SegmentSerializer(serializers.ModelSerializer): class Meta: model = Segment fields = ( # TODO - Could be __all__ if no fine tuning 'id', 'flight_id', 'dep_code', ... ) class FlightSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): segments = SegmentSerializer(many=True, source='segment_set') class Meta: model = Flight fields = ( # TODO - Could be __all__ if no fine tuning 'id', 'dep_air', 'dest_air', ... ) class AirportSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): dep_air = FlightSerializer(many=False, source='dep_air_airport') class Meta: model = Airport fields = ('iata_code', 'name', 'continent', 'iso_country',) I get the following error when starting up the server: File "/Users/me/PycharmProjects/fly_baby/flight_data/serializers.py", line 55, in AirportSerializer dep_air = FlightSerializer(many=False, source='dep_air_airport') File "/Users/me/PycharmProjects/fly_baby/flight_data/serializers.py", line 15, in __init__ fields = self.context['request'].query_params.get('fields') KeyError: 'request' The goal is to have the flights nested under the airports, or vice versa but it doesn't seem possible when I …