Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: attempted relative import with no known parent package, from .models import User, Blog, Topic
Here is a stucture of my app >db __init__.py (nothing is there) models.py (contains models User, Blog, Topic for django orm) query.py (contains functions with queries) query.py: from .models import User, Blog, Topic (I've tried to import User, Blog, Topic from models in query.py like "from db.models import User, Blog, Topic", "from myproject.db.models import ...", anyway result is the same) Please, help me. I don't know why this is happened -
Filter problem in DJango with Soft Delete
I implemented a soft delete for DJango based on the link below: https://adriennedomingus.medium.com/soft-deletion-in-django-e4882581c340 I have a model Client with a list of Account. When I remove the account: Account.objects.filter(id=1).delete() Account.objects.filter(id=1) # <- returns empty Client.objects.filter(accounts__id=1) # <- returns the client The client should returns empty (like hard delete). Is there any solution to this filter problem? -
Django Page Not Found / No Post matches the given query
I won't go to blog/develops but I get this error: Page not found (404) No Post matches the given query. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I don't understand why I am getting this error and how can I solve it. This is my urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name="post_list"), path('<str:adres>/', views.post_detail, name='post-detail'), path('develops/', views.develop_list, name='develop_list') ] This is views.py file: from django.shortcuts import render , get_object_or_404 , redirect from .models import Post from .forms import EmailAbonelikForm def post_list(request): best_post = Post.objects.filter(best=True) posts = Post.objects.filter(best=False, dev = False) return render(request, 'blog/post_list.html', {'posts':posts , 'best_post':best_post}) def post_detail(request, adres): posts = get_object_or_404(Post , adres=adres) if request.method == 'POST': form = EmailAbonelikForm(request.POST) if form.is_valid(): form.save() return redirect('post_list') else: form = EmailAbonelikForm() return render(request, 'blog/post_detail.html', {'posts':posts , 'form':form}) def develop_list(request): posts_dev = Post.objects.filter(dev=True) return render(request, 'blog/develop_list.html', {'posts_dev':posts_dev}) How can I see blog/develops. -
AttributeError: module 'articles.views' has no attribute 'about'
I've been following The Net Ninja Django tutorial on YT (as closely as possibly), but I've hit bit of a snag adding my app (articles) url to the views.py of my main project (website). I keep receiving this error: File "C:File\Path\ToProjects\web_app\website\articles\urls.py", line 6, in <module> url(r'^about/$', views.about), AttributeError: module 'articles.views' has no attribute 'about' I've got Python 3.6 and my pip freeze output is as follows: appdirs==1.4.4 asgiref==3.3.1 distlib==0.3.1 Django==3.1.5 filelock==3.0.12 importlib-metadata==3.1.1 importlib-resources==3.3.0 pytz==2020.5 six==1.15.0 sqlparse==0.4.1 virtualenv==20.2.1 zipp==3.4.0 urls.py in project folder: from django.contrib import admin from django.urls import path, include from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^articles/', include('articles.urls')), url(r'^about/$', views.about), url(r'^$', views.homepage), ] views.py in app folder: from django.http import HttpResponse from django.shortcuts import render def article_list(request): return render(request, 'articles/article_list.html') urls.py from app folder: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.article_list), ] Output of my directory structure Any help is very welcome! -
Why is the data from the combobox not assigned in the variables of my data structure?
I am trying to save the record of the sale with the data that the employee assigns, however, it is not assigning them in the corresponding variables. {id_cliente: undefined, id_empleado: undefined, fecha_venta: "20/01/2021", forma_pago: undefined, precio_total: "4000"} But if you save the ones that are not combobox JS $('form').on('submit', function (e) { e.preventDefault(); ventas.items.id_cliente = $('input[name="id_empleado"]').val(); ventas.items.id_empleado = $('input[name="id_empleado"]').val(); ventas.items.fecha_venta = $('input[name="fecha_venta"]').val(); ventas.items.forma_pago = $('input[name="forma_pago"]').val(); ventas.items.precio_total = $('input[name="precio_total"]').val(); console.log(ventas.items) var parametros = new FormData(); console.log(parametros); parametros.append('action', $('input[name="action"]').val()); console.log($('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); console.log(JSON.stringify(ventas.items)); submit_with_ajax(window.location.pathname, 'Notificación', '¿Esta seguro de realizar la siguiente acción?',parametros, function () { location.href = 'crear_venta'; }); }); -
unable to save venue field
model.py class venue(models.Model): name = models.CharField('Venue name',max_length=120) address = models.CharField(max_length=300) zip_code = models.CharField('zip/post code',max_length=120) phone = models.CharField('contact phone',max_length=20, blank=True) web = models.URLField('web Address', blank=True) email_address = models.EmailField('Email Address', blank=True) admin.py from django.contrib import admin from .models import venue admin.site.register(venue) unable to save data into fields, its occuring OperationErrors -
Does passing a json file as argument makes the rendering html template lose performances?
I have an html webpage: quiz.html returned by the urls.py script of a django application. The questions are just words that are rendered as a ul list of input boxes which I want to transform into related photos where I would be able to do a multi selection click on them. As the ul-input combination looks very heavy I wanted to transform it into a json file that I would pass as an argument of the related function in urls.py wouldn't make me lose performance and if it was a good practice? <!-- Header --> <header class="intro-header"> <div class="container"> <div class="col-lg-5 mr-auto order-lg-2"> <h3><br>Tell me something about you... </h3> </div> </div> </header> <!-- Page Content --> <section class="content-section-a"> <div class="container"> <div class="row"> <div class="col-lg-5 mr-auto order-lg-2"> <div class="recommendations"> <form action = "/getmatch" method="POST"> <p> <label>Your gender</label> <label><input type="radio" name="gender" value="女香">Female</label> <label><input type="radio" name="gender" value="男香">Male</label> </p> </div> <div> <p> <dl class="dropdown"> <dt> <span>Pick the keywords you want to express when wearing perfume</span> <!-- <p class="multiSel"></p> --> </dt> <dd> <div class="mutliSelect"> <ul> <li> <input type="checkbox" name='note' value="甜美" />Sweet</li> <li> <input type="checkbox" name='note' value="温柔" />Gentle</li> <li> <input type="checkbox" name='note' value="优雅" />Elegant</li> <li> <input type="checkbox" name='note' value="成熟" />Mature</li> <li> <input type="checkbox" name='note' value="性感" />Sexy</li> … -
password reset with configuration SMTP
This is my SMTP configuration for my web page. #SMTP (Simple Mail Transfert Protocole) Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*****************' EMAIL_HOST_PASSWORD = '*************' I created a web page using python and Django where the user has to login before. When the user has forgotten his password, he has the possibility to reset his password. to reset his password, the user has to enter his email then the link will be sent to his email provided during his registration. *but when the user enters his email then clicks on send, instead to send the link into his email account, the link is redirect/ sent, to the "EMAIL_HOST_USER".* Problem/Error How should I configure the SMTP (Simple Mail Transfert Protocole) so that the user receives the link of the password reset into his email account provided during his registration? please help me. -
Django Rest Framework not showing form fields for PATCH/PUT request
I have a Django project that is using Django Rest Framework. For some reason, when I go to one of my endpoints (to make a PATCH/PUT request), I am not seeing any of the form fields in the browsable API. Here is the code for the resource: models.py from django.db import models class Patient(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) diagnosis = models.CharField(max_length=200) primary_doctor = models.ForeignKey('Doctor', related_name='patients', on_delete=models.CASCADE, null=True) born_on = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{0.first_name} {0.last_name}".format(self) views.py from rest_framework.views import APIView from rest_framework.generics import RetrieveUpdateDestroyAPIView from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from ..models.patient import Patient from ..serializers import PatientSerializer class Patients(APIView): def get(sef, request): patients = Patient.objects.all()[:10] serializer = PatientSerializer(patients, many=True) return Response(serializer.data) serializer_class = PatientSerializer def post(self, request): patient = PatientSerializer(data=request.data) if patient.is_valid(): patient.save() return Response(patient.data, status=status.HTTP_201_CREATED) else: return Response(patient.errors, status=status.HTTP_400_BAD_REQUEST) class PatientDetail(APIView): def get(self, request, pk): patient = get_object_or_404(Patient, pk=pk) serializer = PatientSerializer(patient) return Response(serializer.data) serializer_class = PatientSerializer def patch(self, request, pk): patient = get_object_or_404(Patient, pk=pk) serializer = PatientSerializer(patient, data=request.data['patient']) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): patient = get_object_or_404(Patient, pk) patient.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py from rest_framework import … -
Django model multiple inheritance
I am using Django 3.1 to build a rudimentary events notification app. Here are my models models.py class Event(models.Model): # WHAT just happened ? (i.e. what kind of event) # these three fields store information about the event that occured content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,related_name='%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # WHO caused it ? (this could also be the system user) actor = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, on_delete=models.CASCADE,related_name='%(class)s_user') # WHEN did it happen ? created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['content_type', 'object_id', 'actor'],name='%(class)s_unique_name')] class Welcome(Event): pass class Goodbye(Event): pass views.py (simplified) def say_welcome(request): data = get_params_from_request(request) Welcome.objects.create(data) def say_goodbye(request): data = get_params_from_request(request) Goodbye.objects.create(data) My question is that will I be able to carry out CRUD functionality on the Welcome and Goodbye models and then also be able to query ALL events through the Event model? -
(django) Showing posts according to interests of users
I am pretty new to Django and still learning it, but I have to create something like medium.com. I want to show posts to users according to their interests. I added an interests field with a checkbox in a sign-up form. And of course, I added a category to the Post model. So, how can I show (to logged-in users only) publications that they interested in? Here is my models.py file in posts app from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): CATEGORY = ( ('sport', 'Sport'), ('science', 'Science'), ('it', 'IT'), ('art', "Art"), ) title = models.CharField(verbose_name="Title for publication", max_length=50) category = models.CharField(verbose_name="Category", choices=CATEGORY, max_length=50) author = models.ForeignKey("accounts.User", verbose_name="Author:", on_delete=models.CASCADE) body = models.TextField(verbose_name="Body for publication") pub_date = models.DateTimeField(verbose_name="Date:", auto_now_add=True) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def __str__(self): return self.title And here is my vies.py file in posts app from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Post from django.urls import reverse_lazy class PostListView(ListView): model = Post template_name = "index.html" def get_queryset(self): return Post.objects.order_by('-pub_date') class PostDetailView(DetailView): model = Post template_name = "./posts/post_detail.html" class PostCreateView(CreateView): model = … -
How to show DB data in my HTML page in Django website?
I checked my DB table and the data I entered is on my db, but I see nothing on my HTML page in my Django website. this is my View: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Article # Create your views here. def home(request): context = { "articles": Article.objects.filter(status="publish").order_by("-publish") } return render(request, 'website/home.html', context) This is my model: from django.db import models from django.utils import timezone # Create your models here. class Article(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) title = models.CharField(max_length=300) slug = models.SlugField(max_length=100, unique=True) description = models.TextField() thumbnail = models.ImageField(upload_to="images") publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) def __str__(self): return self.title this is my HTML page: <div style="text-align: center;"> {% for article in articles %} <img src="{{ article.thumbnail.url}}" alt="{{ article.title }}"> <h1><a href="{{ article.slug }}"> {{ article.title }}</a></h1> <small>{{ article.publish }}</small> <p>{{ article.description }}</p> {% endfor %} -
Login page is verifying all users as good Django
I'm trying to build a login page in Django. But whenever I try to authenticate the user it doesn't work. The user passes each time even if the user doesn't exist. Any help I would really appreciate it! def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) form = CreateUserForm() return render(request, "leadfinderapp/login.html", context={"form":form}) -
Django cart Timer
i am developing a commerce website with limited quantities so I need to have the option (like most travel, concerts, cinema etc. websites) to reserve the item for let's say 10 minutes. Basic idea is that when you add item to the cart available quantity decreases and Timer starts. If checkout proceeds, cool, nothing hapens. If cart is abandonned or timer goes to zero, item becomes again available (qty increases). I started with JS timer. When added to the cart i decrese the qty and if it reaches zero i increment the qty. It works fine if the customer stays on the page. But if he closes his page/computer i lose the timer info and qty is never incremented back in the DB. Second idea was to store timer in the backend, but again how do i run timer on the server. For info, i have cart stored in django.request.session.cart Can someine give me some guidance? Thanks Mali -
DoesNotExists query in python Django when I build eccomerce website
I am making a website for myself. When I tried making cart it was crushing but everything else works perfectly. Please help, i wasted 3 days already trying to solve it. Ask for any files you need, I will post. [here is error: Traceback (most recent call last): File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\shop\mainapp\views.py", line 47, in get customer = Customer.objects.get(user=request.user) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( mainapp.models.Customer.DoesNotExist: Customer matching query does not exist. 1 is my error [1]: https://i.stack.imgur.com/A6j9n.png I will also attach my homepage and all directories -
Mark a user as logged in using Django-two-factor-auth
I am using the Django-two-factor-auth library for my sites login. Everything is working fine, however when I try to login and redirect a new user to their profile page after sign up using login(request, user) I keep getting redirected to the login page. The login works fine when the user re-enters their new login credentials however I want to redirect the user straight to their profile page after signup instead. I am aware Django-two-factor-auth overides Django's built in authentication (Django.contrib.auth), however I am unsure why the login() function is not marking the user as authenticated. views.py from django.contrib.auth import login def signup(request): ... user = signup_form.save() login(request, user) return redirect('/profile') -
Django Models Exercise
Im new using django models, so I started doing some practice exercises that a friend did to me. But I got stuck 😅, this is the problem that I wanted to solve. Requirement: A Game company requires a solution which allow them store next information in the best way possible: server: Field which correspond to server's name and is representated as a slug name(ie: korea as kr, europe as eu, etc) game_id: Unique field which correspond to a game identifier and is representated as a integer (ie: 8234, 7324, etc) game_data: Field which contains all information of the determinated game_id stored in JSON format. Relationships: Server has many game_Id. Game_id has only a single game_data. To Consider: Game_id is an unique field, but into differents servers. By the momment, this is my code. models.py class Game(BaseModel): server = models.ForeignKey(Server, on_delete=models.CASCADE) game_id = models.CharField("gameId", max_length=25) game_data = JSONField(blank=True, False=True) class Server(BaseModel): name = models.SlugField("server", unique=True, max_length=25) I could said It works "well", but I've still having troubles about repeated game_ids on determinated servers, because my code it always will save all data without consider anything about server field. I tried to set unique = True on game_id field, but that validation … -
Auto foreign key in django models
It is possible to do this in Django. I have models and I want every new user to register in Model User and automatically in models Customer in foreign key register class Customer(models.Model): here auto user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=11,null=True) likecus=models.ManyToManyField(smartphone ,verbose_name="b",null=True) def __str__(self): return "User: {}, phone: {}".format(self.user, self.phone) -
My serializer that returns a 0 for Null value is not working
I'm trying to create a serializer that returns the value 0 instead of Null when API data is requested. class MyIntegerField(serializers.IntegerField): def to_representation(self, value): if value is None: return 0 return super(MyIntegerField, self).to_representation(value) class ListSerializer(serializers.ModelSerializer): post_count = MyIntegerField(initial=0) class Meta: model = Post fields = (..., 'post_count', ...) model.py: post_count = models.IntegerField(blank=True, null=True) If a user has no posts, then I would like to return the value 0, instead of Null. What is the issue with my current serializer? I think the field that's inputted is still pulling from my model field, and not the new serializer function. Currently I'm still receiving a Null when user requests data. -
Django API test not working for post request.with payload
I am writing some test for an API that I am working on. I am quit new to Django Rest-framework. This is the code for my 'create' test. The strange thing is that my test is failing (BAD request 400) but my published reat-api is working, at least via the django api-web-browser. I can't find the mistake. Can anyone see what I am doing wrong? The Vacancy_url is correct, I checked that by printing in in code. The get request don't have any problems. So I can conclude that my client is working. Then I thought it must the payload That I am sending. Here I show my test script and my model and view. TESTSCRIPT: from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Vacancy from vacancy.serializers import VacancySerializer VACANCY_URL = reverse('vacancy:vacancy-list') class PrivateVacanciesApiTests(TestCase): """ Test the Private vacancy API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( email='test@uxstudio.nl', password='testpass') self.client.force_authenticate(self.user) def test_create_vacancy_successful(self): """Test create a new vacancy""" payload = { "title": "titel", "description": "wat tekst om te testen", "is_active": True, } self.client.post(VACANCY_URL, payload) exists = Vacancy.objects.filter( company_id=self.user, title=payload['title'] ).exists() self.assertTrue(exists) MODEL class Vacancy(models.Model): """Vacancy … -
passing dictionary to view ,with multiple key:value pairs
def status_(request,id): stages=['Vendor Quotation','Estimate Generation','Purchase Requsition','Purchase Order','Provision To Invoice','Reimbursement Invoice','Request Receipt#(PTI+RI+PO)','Receipt# Received(Updated PTI)','Request Sales Tax Invoice','Uploaded to Jazz Portal'] ctx={'invoice':Invoices.objects.get(pk=id),'stages':stages} return render(request,"Invoices/status.html",ctx) Hi I am trying to pass multiple objects of data for displaying to the template for displaying , I am creating a ctx dictionary with multiple 2 key value pairs ,second Key-value pair is array ,when i access this array in by using {% for idx in range(0,len(ctx.get("stages")) %} I get following parsing error **Could not parse the remainder: '(0,len(ctx.get("stages"))' from 'range(0,len(ctx.get("stages"))'** -
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js please someone helps me -
Django Rest Views: How to access a class variable in another class?
Here's how my authentication works: I get an email and check if that email exists in the database, if it doesn't, I generate a random 8-digit number and then email it to the entered email address and inform the user to confirm his/her email address by entering the emailed code. Here's the View: class CheckEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = CheckEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = Account.objects.filter(email=serializer.data['email']) if user.exists(): return Response({'is_member': True}) else: confirm_code = randint(10000000, 99999999) context_data = {'code': confirm_code} email_template = get_template('email.html').render(context_data) email = EmailMessage( 'Confirm Email', email_template, settings.EMAIL_HOST_USER, [serializer.data['email']], ) email.content_subtype = 'html' email.send(fail_silently=False) return Response({'is_member': False}) I'm using another View to check if the user enters the correct confirmation code, so now I have to send the value of confirm_code variable to the new class. which Looks like this at the moment: class ConfirmEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): user_input_code = request.data print(confirm_code) return Response(True) But I have no idea how to pass the value from CheckEmailView to ConfirmEmailView class. I'm new to Django so despite the solution, any tips on how to make my code any better or any faster or more logical solution to manage this whole process … -
Django - item created by logged user ViewSet
What I want: A logged user creates an item which is stored in the database with that user ForeignKey. I have 2 codes: both should do the same thing (create item linked to current user), but one of them works and the other one doesn't. GET requests work, I'm focusing on POST requests. First code (POST working): class UserPortfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserPortfolioSerializer(serializers.ModelSerializer): class Meta: model = UserPortfolio exclude = ('id', 'user') class UserPortfolioViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserPortfolioSerializer queryset = UserPortfolio.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return UserPortfolio.objects.filter(user=self.request.user).order_by('last_updated') def perform_create(self, serializer): serializer.save(user=self.request.user) Second code (POST not working): class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolios = models.ManyToManyField(UserPortfolio, blank=True) exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'exchange_connection' verbose_name_plural = "Exchange Connection" def __str__(self): return self.user.username class ExchangeConnectionSerializer(FlexFieldsModelSerializer): class Meta: model = ExchangeConnection fields = '__all__' expandable_fields = {'exchange': ExchangeSerializer, 'portfolios': (UserPortfolioSerializer, {'many': True})} class UserExchangeConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.ExchangeConnectionSerializer queryset = ExchangeConnection.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return ExchangeConnection.objects.filter(user=self.request.user).order_by('last_updated') @action( detail=True, methods=['post'], url_path='create-exchange-connection', ) def post(self, serializer): serializer = serializers.ExchangeConnectionPostSerializer(user=self.request.user) if serializer.is_valid(): serializer.save() return Response({'status': 'Exchange created.'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error I get when I POST … -
Trouble Importing module in Django
I am working inside of a Django project and I'm trying to import a class from the models.py file. Screen shot of file scaffold shows the google_locator.py file I am trying to import Truck instance from models. I have tried .models, ..models, ../models, ./models, truck.models, and several more combinations. I either get an "invalid syntax" error or "ImportError: attempted relative import with no known parent package"