Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Select Option Value in Views Django
This is my HTML form template <form action="" method="post"> {% csrf_token %} <div class="d-flex form-inputs"> <select class="form-select" aria-label=".form-select-lg"> <option selected>Spanish To English</option> <option selected>English To Spanish</option> <option value="1">French To English</option> </select> <input name="txt" class="form-control p-3" type="text" placeholder="Search..."> <a href="#"><img src="/static/assets/image/search.png" alt=""></a> </div> </form> I want to get User selected value from Select Option to views. This is views function def lang_convert_view(request): if request.method == "POST" and 'txt' in request.POST: txt = request.POST.get('txt') data = custom_function_name(txt) context = {'data': data} else: context = {} return render(request, 'index.html', context) Anyone, please help me -
How do I format Django form CharFields to be next to each other one the same line?
Currently, I'm using a the Django Form class to create a form. I'm trying to make it so that all of the CharField fields have their own row, except for a few specific one's that I would like to share a row. These are the CharFields I currently have: class ExampleForm(forms.Form): example_1 = forms.CharField(max_length=20, required=False) example_2 = forms.CharField(max_length=20, required=False) example_3= forms.CharField(max_length=20, required=False) def __init__(self, *args, **kwargs): super(MetadataForm, self).__init__(*args, **kwargs) self.fields['example_1'].widget.attrs['style'] = 'width:15%;' self.fields['example_2'].widget.attrs['style'] = 'width:15%;' self.fields['example_3'].widget.attrs['style'] = 'width:15%;' Here is how they're rendered in the HTML: <label for="id_example_1">Example 1:</label> <input type="text" name="example_1" maxlength="20" style="width:15%;" id="id_example_1"> <label for="id_example_2">Example 2:</label> <input type="text" name="example_2" maxlength="20" style="width:15%;" id="id_example_2"> <label for="id_example_3">Example 3:</label> <input type="text" name="example_3" maxlength="20" style="width:15%;" id="id_example_3"> In an attempt to format example_1 and example_2 on the same line, I tried floating the labels to the left and then adding space between them by increasing the margin: #example_1, #example_2, #example_3 { float: left; margin-left: 100px; } However, while this formats the boxes very oddly: It also doesn't do anything for the labels. I'm not sure how to reference the labels since they don't have id values I can use. If there's a way that I can have example 2 and 3 formatted on the … -
How to make queries to remote Postgres in different views in Django?
I'm making a project where I need to access to remote databases and get data from it. I'm connecting to remote postgres database and getting list of all tables in my class-based view like so: try: # connect to the PostgreSQL serve conn = psycopg2.connect( host='host', database='db_name', user='username', password='password', port='port', ) # create a cursor cursor = conn.cursor() cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") rows = cursor.fetchall() # close the communication with the PostgreSQL cursor.close() except (Exception, psycopg2.DatabaseError) as error: print(error) Now, in another view I want to make other queries (like retrieving specific rows from specific table). How am I able to do that? The goal is to take all credentials from user's input in template to connect to db. Then on another template choose which table and which rows to use to get certain data. -
Django Update view doesn't update an object during test
I'm writing tests for my views and I'm stuck with the UpdateView and the POST request. For this simple test I try just to change first_name but assertion fails. What am I doing wrong? However, when I call the response.context it gives me that: [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7f070ed6eee0>>, 'request': <WSGIRequest: POST '/employees/7/update'>, 'user': <SimpleLazyObject: <User: testuser@test.com>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7f070ecb33d0>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f070ed1b130>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Employee: John Smith>, 'employee': <Employee: John Smith>, 'form': <EmployeeUpdateForm bound=True, valid=False, fields=(first_name;last_name;user;position;reports_to;birthday;hire_date;address;phone_number;pfp)>, 'view': <employees.views.EmployeesUpdateView object at 0x7f070ed1b310>}] The test: class TestEmployeesUpdateView(TestCase): def setUp(self): self.test_user = User.objects.create_user( username='test_user', email= 'testuser@test.com', password='Testing12345') self.test_employee = Employee.objects.create( first_name='Bob', last_name='Smith', user=self.test_user, position='SM', birthday=date(year=1995, month=3, day=20), hire_date=date(year=2019, month=2, day=15), address='...', ) self.client = Client() def test_updateview_post(self): self.client.force_login(user=self.test_user) response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), {'frist_name': 'John'}) self.test_employee.refresh_from_db() self.assertEqual(self.test_employee.first_name, 'John') The view: class EmployeesUpdateView(LoginRequiredMixin, UpdateView): model = Employee template_name = 'employees/employee_details.html' form_class = EmployeeUpdateForm And the error: FAIL: test_updateview_post (employees.tests.test_views.TestEmployeesUpdateView) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/main/dev/project1/employees/tests/test_views.py", line 63, in test_updateview_post self.assertEqual(self.test_employee.first_name, 'John') AssertionError: 'Bob' != 'John' - Bob + John -
Exclude auto-generated files by Django within pre-commit-config.yaml using REGEX
Since the auto-generated Django files don't fulfill numerous pylint-requirements, my pre-commit checker fails: The files look usually like so: They seem to be located automatically in a sub-folder called "migrations": Now, I tried to leverage the pre-commit exclude expressions with a proper REGEX. This one seemed to work on an online REGEX-tester: [\w-]+\d+[^\\]*.py Here is the proof: Now, putting this into my pylint pre-commit checker does unfortunately nothing: I also tried to just exclude the "migrations" folder, but I could not find a working expression either. How can I make this work? -
Status: Select a valid choice. 1 is not one of the available choices Django 3
Here i am using Django 3.0 and Python 3.7. When i am trying to update the user phone number or email id i am getting this issue. Here is my views.py: class ClientUserInfoUpdate(CustomAdminMixin, UpdateView): model = ClientUser template_name = "core/user_info_mutiple_edit_form.django.html" form_class = ClientUserInfoUpdateForm user = None methods = None def get_success_url(self): return reverse("admin_user_update", args=[self.user.pk]) def get_form_kwargs(self): kwargs = super(ClientUserInfoUpdate, self).get_form_kwargs() self.user = kwargs['instance'] self.methods = self.user.get_userinfodata() kwargs['user'] = self.user kwargs['methods'] = self.methods return kwargs def get_context_data(self, **kwargs): context = super(ClientUserInfoUpdate, self).get_context_data(**kwargs) context['user'] = self.user context['methods'] = self.methods context['countries'] = countries_sorted for method in ContactInfoMethod.objects.all(): context['types_' + method.name.lower()] = ContactInfoMethodType.objects.types_by(method.name) return context Here is my forms.py: class ClientUserInfoUpdateForm(forms.ModelForm): user = None methods = None # sort of a copy of fieldsets, but utilising the dynamic capabiliities of the form #formsections = [] new_info = [] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.methods = kwargs.pop('methods') super(ClientUserInfoUpdateForm, self).__init__(*args, **kwargs) #self.formsections = [] # auto generate the form based upon self.methods (!!!) for dm in self.methods: methodtypes = ContactInfoMethodType.objects.types_by(dm['method'].name) methodtypes_choices = methodtypes.values_list('pk', 'type__name') if(dm['method'].use_dialling_code): dialling_code_choices = countries_sorted_with_dial_choices i = 1 methodname = "" for info in dm['items']: fn = info.dynamic_form_field_name() self.fields[fn] = forms.CharField() if(dm['method'].name.lower() == "email"): self.fields[fn] = forms.EmailField() self.fields[fn].name = fn self.fields[fn].verbose_name … -
Why doesn't it return the messages?
I'm trying to retrieve all messages in the chat, the messages are saved in the ChatMessage template. The insertion of a new message does not create problems for me, the recovery yes, in the send_message() function I use the send() with the correct data. {'command': 'messages', 'messages': [{'id': 204, 'author': 'C12VC08213@are.it', 'content': 'Ciao da tutti', 'timestamp': '2022-06-06 13:57:37.103215'}, {'id': 236, 'author': 'CCCVC08213@are.com', 'content': 'Ciao da tutti quanti', 'timestamp': '2022-06-07 07:59:50.818133'}, {'id': 269, 'author': 'C11VC0@are.it', 'content': 'Ciao da tutti quanti1', 'timestamp': '2022-06-07 08:51:58.980090'}]} I don't understand why it doesn't send it, the websocket restiusce nulls me or it doesn't respond. from concurrent.futures import thread from django.contrib.auth import get_user_model # from asgiref.sync import await from asgiref.sync import async_to_sync, sync_to_async from channels.db import database_sync_to_async import json from chat.models import ChatMessage, ChatRoom from users.models import Operator from chat.utils import ( get_chatmessages, get_operator_info, # get_current_chatroom, # get_operator, ) from channels.generic.websocket import AsyncWebsocketConsumer from chat.api.v1.serializers import ChatMessageSerialiser, ChatRoomSerializer class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): print("------------------ receive") text_data_json = json.loads(text_data) if text_data_json["command"] == "fetch_messages": await self.fetch_messages(data=text_data_json) # self.send(text_data=fetch['messages']) # await self.channel_layer.group_send( # self.room_group_name, # {"type": "chat_message", "message": messages}, # ) if text_data_json["command"] == "new_message": message = text_data_json["message"] await self.new_message(data=text_data_json) self.send(text_data=message) await self.channel_layer.group_send( self.room_group_name, {"type": "chat_message", "message": message}, … -
serializer error for list field when i run tests in Django
I have a weird problem when using TestCase and Client in Django. from django.test import TestCase, Client data is: data = { "match_status": MatchStatus.FINISHED, "winner_side": Side.CITY, "end_time": get_now(), "players": [ { "uuid": self.player.uuid, "role": self.role, "success_acts": [self.act1.id], "failed_acts": [self.act2.id, self.act3.id] } ] } from django.test import Clien as client self.client.post(reverse("match-finish", args=[self.match_create.uuid]), data=data) this is a custom serializer: class MatchFinishPlayerSerializer(BaseSerializer): uuid = UUIDField() role = IntegerField() success_acts = ListField() failed_acts = ListField() class MatchFinishSerializer(BaseSerializer): match_status = IntegerField() winner_side = IntegerField() end_time = DateTimeField() players = MatchFinishPlayerSerializer(many=True) Part of view.py: @action(methods=["POST"], url_path="finish", url_name="finish", detail=True) def finish(self, request, uuid: UUID = None): serializer = self.get_serializer_class()(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.validated_data) and when I run python manage.py test I got an error: {'players': ['This field is required.']} -
How to use default logger and custom logger in django but avoid duplicate logs
I have two sets of APIs in a Django project that I want to use my custom logger. So in every viewset I will be doing logger.info(...) or logger.error(...) before the responses. Everywhere else in the project, like Admin pages and other tools, I'd like to leave the logging as it is for now. This is how I have defined my LOGGING in settings.py. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': 'ts=%(asctime)s level=%(levelname)s caller=%(filename)s:%(funcName)s:%(lineno)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } The problem is that the way it is, the logging in the APIs is duplicated for every request, my logger and the existing django logger. How can I "disable" the default django logger in the APIs but keep it everywhere else? -
Testing a django `post_save` signal that includes function calls that occur after db transaction is committed
When django tests are running, database transactions are not committed. How do I test an event triggered by object creation but that happens after the db transaction has been committed? I have a Campaign model and the below post_save signal. Using Django TestCase it is difficult to assert that the functions within transaction.on_commit are called in the case when a new Campaign object is created. When the signal runs in the test context, it always thinks that an existing campaign object is being edited, not that one has been newly created. Therefore I cannot test the else branch of the if statement. How could I test the case when Campaign.objects.filter(pk=instance.pk).exists() is False? Signal: @receiver(post_save, sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting") def create_handwriting(sender, instance, **kwargs): """Whenever a campaign is created or updated, trigger the handwriting cloud function to (re)generate the handwriting image. """ if Campaign.objects.filter(pk=instance.pk).exists(): transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-edited", stage="campaign") ) transaction.on_commit(lambda: delete_campaign_pages(campaign_pk=instance.pk)) else: transaction.on_commit( lambda: log_campaign_progress(pk=instance.pk, status="t2h-created", stage="campaign") ) transaction.on_commit(lambda: enqueue_handwriting_generation(campaign_pk=instance.pk)) Test: class TestSignals(TestCase): def setUp(self): self.factory = RequestFactory() @mock.patch("lettergun.apps.writing.signals.log_campaign_progress") @mock.patch("lettergun.apps.writing.signals.enqueue_handwriting_generation") @mock.patch("lettergun.apps.writing.signals.delete_campaign_pages") def test_create_handwriting_edit_existing_campaign( self, delete_campaign_pages, enqueue_handwriting_generation, log_campaign_progress ): # disconnected in the factory so we need to reconnect it here signals.post_save.connect( sender=Campaign, dispatch_uid="apps.writing.signals.create_handwriting", receiver=create_handwriting, ) enqueue_handwriting_generation.return_value = True log_campaign_progress.return_value = True with self.captureOnCommitCallbacks(execute=True) … -
Share Django authentication for FastAPI
I have working Django project. Now i want to add FastAPI so at existing django templates i can make API requests to refresh data without reloading whole template (like tables for example). The question is how to connect FastAPI to existing django authentication system, so it can use sessions from db, so that user authenticate only once, when logging in to django project. Here some options i have investigated: Change django base authentication to oauth2, also set fastapi to oauth2 (though i desire to configure fastapi, not changing django) Fetch django sessions from db on each api request and verify user Both django and fastapi on the same server and can share the same db. Maybe some better options are possible. Please advice what would be the best approach to use django already authenticated user data with fastapi? Thx -
How to import images ImageField from excel, using Django import_export?
I am using django-import-export, Excel file as file.xlsx when importing an ImageField the image is saved as a link "C:\Users\hp\Desktop\images\gallery\29.jpg" and not an actual image into database. models.py class Product(models.Model): name = models.CharField( max_length=200, verbose_name='Nom') slug = models.SlugField( max_length=150, unique= True, verbose_name='URL') reference = models.CharField( max_length=200, verbose_name='Référence', unique=True, blank=True, null=True) def __str__(self): return self.name class PhotoProduct(models.Model): image = models.ImageField(upload_to='images/produits') actif = models.BooleanField(verbose_name='actif', default=True) product = models.ForeignKey(Product, related_name="photos", on_delete=models.CASCADE) def __str__(self): return str(self.product) ########### ressources.py class PhotoProductAdminResource(resources.ModelResource): product = fields.Field(column_name='product', attribute='product', widget=ForeignKeyWidget(Product, field='id')) class Meta: model = PhotoProduct fields = ( 'id', 'product', 'actif', 'image', ) ########### admin.py @admin.register(PhotoProduct) class PhotoProductAdmin(ImportExportModelAdmin): list_display = ('id', 'product', 'actif') list_display_links = ('id','product', ) list_editable = [ 'actif'] resource_class = PhotoProductAdminResource form = PhotoProductModelForm -
Why in DJANGO the Templates are not updated when I refresh the page with new data in the DB?
The problem is that when I change data through a form or by the django admin if it is saved in the database, but when redirecting to another view or refreshing the screen with f5 it does not show the changes in the user views unless I start session again or delete the cookies, something that for each change you have to perform this operation, however in the django admin views if everything is updated normally with a simple f5. This is very rare since the page has been working for more than 1 year without this problem and suddenly this happened. I'm using: Stevedore Nginx gunicorn 20.0.4 Django 3.1.4 python 3.9 sqlite 3 and bootstrap 4.6 for user views I thought it was just the update of my browser but in any browser the same thing happens I did not find a similar problem in any forum, I hope you can help me or give me an indication of what is causing this -
modelize schema procede withdjango
Is it possible to draw a dynamic schema procede with django ? i tried to draw shapes with #svg in HTML/CSS but it is a static solution ... And I need to do dynamic modification in the schema , hypertext for exemple Any help please ? -
Manytomay field is None or can't call field in a view in django
I have a problem in my code,I'm Trying to querying to my course model, I have a many to may field of course in user model,now I need to query to course model that course title or id is equal to user's courses My course model is: class Courses(models.Model): title = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) active = models.BooleanField(default=False) default_course = models.BooleanField(default=False) My user model in another app is: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) courses = models.ManyToManyField('academy.Courses', related_name='user_courses', blank=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_author = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_adviser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) I have to say my user model and course model are in different app This is my view: class CoursesListView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = UserSerializer def get_queryset(self, **kwargs): user = self.request.user course = Courses.objects.filter(title__in=user.courses.title) I tried so many code but none of them worked,please any one can help me how can I write this view? as I said I want to call courses that have same id or title with user courses -
Django can't get form to load in browser 404
I've got my LAMP setup with Ubuntu and MariaDB. The Django code managed to create some tables for me in the database but I just get 404 when I try to load my form in my browser. This is my first Django app. Maybe my urls.py is wrong. Maybe it's my settings.py. I've trying all sorts of things so my code has probably got a bit mangled. From TEMPLATES in settings.py I've hardcoded the path to my .html I've experimented with this a lot. 'DIRS': [ '/opt/vcm_project/vcm/templates/vcm' ], urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create_unit', views.create_unit, name='create_unit'), ] models.py from django.db import models # Create your models here. class Unit(models.Model): unit_code = models.CharField(max_length=15) unit_name = models.CharField(max_length=255) unit_sector = models.CharField(max_length=255) unit_application = models.TextField(max_length=65535) unit_url = models.URLField(max_length=255) superseded_equivalent = models.CharField(max_length=15) def __str__(self): return self.unit_name class Element(models.Model): element_number = models.CharField(max_length=100) element_name = models.CharField(max_length=255) def __str__(self): return self.element_name forms.py from django import forms from .models import Unit class UnitForm(forms.ModelForm): class Meta: model = Unit fields = ('unit_code', 'unit_name', 'unit_sector', 'unit_application', 'unit_url', 'superseded_equivalent') widgets = { 'unit_code': forms.CharField(label='Unit code', max_length=15) 'unit_name': forms.CharField(label='Unit name', max_length=255) 'unit_sector': forms.CharField(label='Unit sector', max_length=255) 'unit_application': forms.CharField(label='Unit application', max_length=65535) 'unit_url': forms.URLField(label='Unit URL', max_length=255) … -
Django: Override 404 template in some views
I have a custom 404 template for my whole django application but I would like to show a different one for specific views. Is there a way to overrride the 404 template at runtime for one specific view? -
Email sending through Gmail is not working in Django. Gmail less secure apps disabled
From May 30 2022 onwards Gmail removed Less Secure apps access in gmail. Is there any alternative email provider we can use or is there any solution for it? EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 if request.method == "POST": name = request.POST['form_name'] email = request.POST['form_email'] subject = request.POST['form_subject'] message = request.POST['form_message'] send_mail(subject,message,email,['mail@gmail.com'] ) return render(request, 'pages/contact.html', {'name': name}) else: return render(request, 'pages/contact.html', {}) Need help, Thanks in advance. -
Prevent User from creating instance for other users
I have 4 models each related to each other with ForeignKey. class User(models.Model): name = models.CharField() class Business(models.Model): name = models.CharField() //business name created_by = models.ForeignKey(User,related_name=businesses,on_del=models.CASCADE) class ProdCategory(models.Model): business = models.ForeignKey(Business,related_name=categories,on_del=models.CASCADE) name = models.CharField() class Product(models.Model): category = models.ForeignKey(ProdCategory,related_name=products,on_del=models.CASCADE) name = models.ForeignKey() price = models.DecimalField() Now If I try to get all the Products of the current authenticated user I get the Correct List of products (that coming from the same User>Business>ProdCategory>Product) But if I try to create a Product with authenticated user, I can create a Product with providing the id of ProdCategory(already created by different users) (User of Business>ProdCategory) != self.request.user In Short I can create product for other users. Which is not what I want. I want to prevent the current user from creating products if ProdCategory id provided is of different users. It should return error. User must provide the id of ProdCategory that was created by the same user. Serializer classes are defined with all fields using ModelSerializer. Here goes the View for creating and listing products: class ProductListCreateView(generics.ListCreateAPIView): serializer_class = ProductListCreateSerializer def get_queryset(self): return Product.objects.filter(category__business__created_by=self.request.user) -
Django How to Select One Foriegn Key Among Multiple Foriegn Keys
I have two models know i created a third one in which i want to link any one between these two forign keys but not both of them and i want to show both of them while linking then we choose one of them -
Must supply api_key with django app deployed on heroku
hello guys i've got a django app, and i'm using cloudinary to save images, on my localhost it working perfectly but once i deployed to heroku i keep getting this error message Must supply api_key and ive added the api_key to my config list -
Running a django project with documentation based in linux on windows
I want to run this project https://github.com/sajib1066/django-event-management in windows but its documentation is for linux. Please simplify the instructions for windows because I'm having trouble in setting this up. Especially since the source command is not in powershell. -
Object of type RefreshToken is not JSON serializable
I would like to trigger user_logged_in after a user is authenticated through rest_framework_simplejwt This is the code I have written: class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user) if not api_settings.USER_AUTHENTICATION_RULE(user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return { self.get_token(cls, user) } @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio token['photo'] = json.dumps(str(user.profile.profile_pic)) return token When I try to authenticate a user I get the error: Object of type RefreshToken is not JSON serializable -
Django 4.0 getting many to many field objects in List View
I'm really new to Django and have been stuck....I have a book model and a genre model that have a many to many relationship. How would I go about getting all the books for a specific genre in a list view. I'm assuming its faster to get a Genre object and get all the books from it using a query such as "genre.objects.book_set.all" rather than going through all books and seeing if they have the specified genre. However I'm not sure how I would do that in a ListView? I wanna take the genre name from the url and then use that to get the genre object. here is what I have URL: path('genre/<string:name>', GenreListView.as_view(), name='book-genre'), Models: class Genre(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) image = models.ImageField(default='book_imgs/default.jpg', upload_to='book_imgs') def __str__(self): return self.name View? class GenreListView(ListView): model = Genre def get_queryset(self): Not sure what to put here.... return Any help is appreciated, thanks. -
Vue Js and Django get fields from ForeignKey Objects
I am using Django Rest Framework with Vue JS and currently unable to get the foreignkey fields from the actual model of the api. I want to be able to get the store name of a particular product. Whenever I try to call [[ product.store.name ]] in my vue template it returns nothing. Also my href does not return the slug of a store. This could be an easy fix, but I am hopeful to get a solution. Below is my code, thanks. models.py class Store(models.Model): owner = models.ForeignKey("account.Profile", null=True, on_delete=models.SET_NULL) category = models.ForeignKey("store.Category", null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, unique=True) slug = AutoSlugField(populate_from='name', unique=True, editable=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class Product(models.Model): store = models.ForeignKey("store.Store", null=True, on_delete=models.SET_NULL, related_name='product_store') category = models.ForeignKey("store.Category", related_name='product_category', on_delete=models.CASCADE) sub_category = models.ForeignKey("store.SubCategory", related_name='product_sub_category', on_delete=models.SET_NULL, blank=True, null=True) created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) description = models.TextField(blank=True) slug = AutoSlugField(populate_from='title', unique=True) price = models.DecimalField(max_digits=10, decimal_places=0) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductListAPIView(generics.ListAPIView): pagination_class = MyCustomPagination queryset = Product.objects.all().order_by('-date_created') # queryset = Product.objects.all() serializer_class = ProductSerializer products.js <script> new Vue({ el: "#blog", delimiters: ['[[', ']]'], data() { return { products: [], currentPage: 1, hasNext: true, loading: true, …