Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
modal does not load form data
I have the data form and the data update views, when I'm not using the modal, it works perfectly, however when using modal, it loads the empty forms, and if I load without the modal, the data saved in the database appear . I do not know where I'm going wrong. views.py class UserNameUpdate(LoginRequiredMixin, UpdateView): model= User fields = ['username'] template_name=' /change-username.html' def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() # This should help to get current user # Next, try looking up by primary key of Usario model. queryset = queryset.filter(pk=self.request.user.usuario.pk) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404("No user matching this query") return obj def get_success_url(self): return reverse('sistema_perfil') change-username.html {% load static %} {% load bootstrap %} {% load widget_tweaks %} {% load crispy_forms_tags %} {% block main %} <div class="container"> <div class="card text-white bg-primary mb-3"> <div class="card-header"><small class="text"> <a href="{% url 'sistema_index' %}" class="text-white ">Home /</a> <a href="{% url 'sistema_perfil' %}" class="text-white ">Perfil /</a> <a class="text-white">Usúario</a> </small></a></p> Alterar Nome do Usúario</div> <div class="card bg-light text-center "> <div class="card-body text-secondary text-center"> <form method="post" action="{% url 'sistema_change_username' %}" class="form-signin" enctype="multipart/form-data" id="form" name="form" validate> {% csrf_token %} <div class="form-row … -
How to run Django unit tests against a postgre database
Im using coverage.py and django-nose to run unit tests. All was working fine with the 'default' sqlite database. Yet when i swapped this out for a postgre database I get the following error: django.db.utils.ProgrammingError: relation "authentication_user" does not exist In test_settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'PORT': 5432, 'NAME': 'testing_db', 'USER': 'user_name', 'PASSWORD': 'password' } } Command used to run tests (found in the 'tests' folder): coverage run manage.py test tests Oddly enough if i run an individual TestCase as follows, the test runs fine (error only occurs when running a collection of tests): coverage run manage.py test tests.test_something Any ideas of what is going wrong here? -
Django: Image upload and choose / pick photo from gallery with thumbnails
Can anyone please point me in the direction to an example or project that shows (with implementation in Django, Bootstrap, PIL): User can upload a picture (basic crop ability is ideal), pictures are saved in a static media folder. User can choose from a simple gallery among the pictures in the static media folder at the same time. The implementation I am trying to achieve: In a form, User can choose to upload their own picture or choose from a library of pictures residing in a static media folder. There is a visual feedback in form of a thumbnail. The whole functionality I am planning to put into a modal window. My own rudimentary/initial steps below, but need to look at some existing examples to being able to generate a gallery and being able to pick from it: # models.py class Product(models.Model): image = models.ImageField(default='default.jpg', upload_to='product_pics') # forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image'] # views.py def product(request): if request.method == 'POST': p_form = ProductForm(request.POST, request.FILES, instance=request.product) if p_form.is_valid(): p_form.save() return redirect('product') else: p_form = ProductForm(instance=request.product) context = { 'p_form': p_form } return render(request, '/product.html', context) -
Limit dropdown results in generic UpdateView
Working on my first Django project! I have an UpdateView and I want to limit the dropdown results of program_code so it only shows items that the user owns. I think I have to pass kwargs to the view to limit the queryset but not sure where to begin or how to go about doing that. Any advice would be greatly appreciated. View: class ContactsUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView): model = Contact fields = ['first_name1', 'last_name1','address1','address2','city','province','postal_code','country','active_status','program_code'] template_name = 'contacts/contacts_form.html' success_message = "Contact was updated successfully" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): contact = self.get_object() if self.request.user == contact.author: return True return False model: class Contact(models.Model): first_name1 = models.CharField(max_length=100, verbose_name='First Name', null=True) last_name1 = models.CharField(max_length=100, verbose_name='Last Name', null=True) address1 = models.CharField(max_length=100, verbose_name='Address 1', null=True) address2 = models.CharField(max_length=100, verbose_name='Address 2', null=True, blank=True) city = models.CharField(max_length=100, verbose_name='City', null=True) province = models.CharField(max_length=2, choices=PROVINCE_CHOICES, default='Ontario', verbose_name='Province') postal_code = models.CharField(max_length=7, verbose_name='Postal Code', null=True) country = models.CharField(max_length=100, verbose_name='Country', null=True, default='Canada') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) active_status = models.BooleanField(default=True) program_code = models.ForeignKey(Program, on_delete=models.CASCADE) def __str__(self): return self.first_name1 + ' ' + self.last_name1 def get_absolute_url(self): return reverse('contacts-home') template form: <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-2 mt-2">Update Contact</legend> <p>Created by: {{ … -
NGINX not finding static files in Dockered Django project
I'm new to using Docker and Nginx. I'm taking a project I have working locally which includes flatpages and a couple of simple apps and combining it with this guide to utilise Docker, NGINX and Gunicorn. For some reason, it can't find my Static files or even the standard Django admin static files. Console error GET http://0.0.0.0:8000/static/flatpages/CSS/flatpages.css net::ERR_ABORTED 404 (Not Found) Django Admin Django Admin local.conf upstream hello_server { server djangoapp:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://hello_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { autoindex on; alias /opt/services/djangoapp/static/; } location /media/ { alias /opt/services/djangoapp/media/; } } settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "static"), '/static/flatpages/', ] Amongst many other things, so far I've tried: Using STATIC_ROOT and STATICFILES_DIRS My understanding from the Django docs is that with static files in multiple locations I need to use STATICFILES_DIRS If I use STATIC_ROOT and collect static the Django Admin does find the static files but won't find any others. Navigating the apps Docker container to find the files manually. I can't locate them or any of the templates that do work. I find this very odd. Please … -
How to get table alias for inner join in django
I'm using django 2.1, python 3.6 and SQL Server 2012 as backend. I have following models: class ModelA(models.Model): name = models.CharField(...) value = models.PositiveIntegerField(...) class ModelB(models.Model): name = models.CharField(...) values = models.ManyToManyField(ModelA, through='ModelC') class ModelC(models.Model): model_a = models.ForeignKey(ModelA, ...) model_b = models.ForeignKey(ModelB, ...) info_a = models.CharField(...) info_b = models.CharField(...) How can I achieve following SQL query: SELECT t1.model_a_id AS a_id, t3.value AS a_value FROM ModelB AS t0 INNER JOIN ModelC t1 ON t1.model_b_id = t0.id INNER JOIN ModelC t2 ON t2.model_b_id = t0.id INNER JOIN ModelA t3 ON t3.id = t2.model_a_id INNER JOIN ModelC t4 ON t4.model_b_id = t0.id WHERE t1.model_a_id in (1,2) AND t2.model_a_id in (8,9,10,11) AND t4.model_a_id in (21,22) What I have so far: ModelA.objects.filter(values__in=[1,2]).filter(values__in=[8,9,10,11]).filter(values__in=[21,22]) Which produces the correct filtered QuerySet. But how can I get the correct fields? I tried to use annotate function but I failed. Using django's Subquery as described in the docs generates database error, because SQL Server does not support subqueries in the SELECT part. Any recommendations? Thanks! -
Django Admin Generic content type multiple models inline form
I'm getting started with Django and I'm a bit stuck on a multi-models field, AKA Generic Relation (Content Type) I have a generic content type "student_solution" that can belong to either: a Org model a Institution model a Campus model Therefore, in each of those 3 models, I have a reversed relationship as follow, in each models.py: # Reverse generic relation - XXX See https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations student_solutions = GenericRelation('student_solution.StudentSolution') I'm not sure whether this is the right approach, I think so, but a confirmation is welcome :) It's working fine as it is now, but it's not user-friendly in the Django Admin UI, see how it display on django admin, when creating a Student Solution (I would expect a select box showing a label field, instead of entering the Content Type ID by hand): When creating either an Org, Institution or Campus, the field doesn't show at all in the Django Admin (so I probably misconfigured something) I tried following How to replace content_type and object_id fields by a field with actual object in admin inline? to improve the UI by allowing to select the right Content Type and "object" using the object's label. But it doesn't work at this time. … -
Get the query set for HyperlinkedRelatedField(many=True)
How would I get the query set for a HyperlinkedRelatedField field within a template (or anywhere!). I have tried with many=False and I am able to iterate over the instances with the code below, but not when many=False. {% for atomic in serializer.atomic.queryset.all %} {{ atomic.name }} {% endfor %} TIA! -
Nginx and Django Rest Api Call
I'm currently developing a web NER application with following stack: Ubuntu 18.04.1 x64 nginx version: nginx/1.14.0 (Ubuntu) Django 1.11.20 (I just followed this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04) My goal is to create a REST API endpoint. Because I do not use any Django model, ive decided not to use Django rest api framework. I have created a simple view handler functio: @csrf_exempt def test(request): data = json.loads(request.body.decode('utf8')) data['res'] = "šščšč ščšččťťž" return JsonResponse(data, safe=False) -
How to export the list or dictionary selenium python POST to Django Database or Get?
Like the following code I do not want to be saved in the file I want to #go straight to the Django database my code enter image description here -
Django I want to create a password, email, and username validation
I am creating a user registration form in Django python. I want to create a password, email, and username validation. Some how it let me to register it but when I type mismatch password it not give me any error. I am attaching the whole project and here is my Form.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import validate_email class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) def clean_username(self): user = self.cleaned_data['username'] try: match = User.objects.get(username = user) except: return self.cleaned_data['username'] raise forms.ValidationError("Username already exist") def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user View code: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: form = RegistrationForm() args = {'form': form} return render(request, 'reg_form.html', args) else: form = RegistrationForm() args = {'form': form} return render(request, 'reg_form.html', args) Html Registeration {% csrf_token %} {{ form.as_p }} Submit … -
redirect path not found
I wanted the user to be able to make a new blog and after he makes the blog he should be redirected to the detailed view of the blog, however i feel there is some problem with the get_absolute_url and in the urls code is given below urls.py from django.urls import path from . import views from .views import PostCreateView urlpatterns=[ path('',views.BlogsList.as_view(),name='blog-home'), path('<int:blog_id>/like/', views.like_post, name='like_post'), path('post/<int:id>/', views.post_detail, name='post-detail'), path('post/new/',PostCreateView.as_view(),name='post-create'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) likes=models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def get_absolute_url(blog_id): return reverse('post-detail',args=[str(blog_id)]) views.py(shortened) class BlogsList(ListView): model=Blog template_name='blog/home.html' context_object_name='blogs' ordering=['-date_posted'] def post_detail(request, id): post=get_object_or_404(Blog, id=id) comments=comment.objects.filter(post=post).order_by('-id') if request.method=="POST": comment_form=CommentForm(request.POST) if comment_form.is_valid(): content=request.POST.get('content') new_comment=comment.objects.create(post=post, user=request.user, content=content) new_comment.save() return HttpResponseRedirect(Blog.get_absolute_url(blog_id=id)) else: comment_form= CommentForm() context={ 'post':post, 'is_liked': post.likes.filter(id=request.user.id).exists(), 'comments':comments, 'comment_form':comment_form, } return render(request, 'blog/post_detail.html',context) class PostCreateView(CreateView): model=Blog fields=['title','content'] def form_valid(self,form): form.instance.author=self.request.user return super().form_valid(form) return HttpResponseRedirect(Blog.get_absolute_url()) -
cannot access a development server on a server im ssh'd into
I am deploying a django app from a Centos server. When i do a python3.6 manage.py runserver 8000 command it starts a development server no problem. I am not able to access this page from my local computer to test it. so the steps i take are: i ssh into the server by doing ssh <user>@url.com and then run the dev server with the above command. I then go to the browser on my laptop and type url.com:8000 and will come up with Unable to connect I also have this problem when running my apache server for production. i would have no problems putting up the server on the server im ssh'd into but cannot access the webpage. I know this is very little information to go on but does this sound like a server side issue at url.com? Should i be contacting the administrators with this, or is this something on my end possibly? Maybe i need to configure the address my settings.py in my django app? -
Extending Django User Model and Adding to Admin List Display
I am trying to extend my user model with a profile and then add the new profile fields to the user list display so that it is searchable. Everything is working up until adding it to the admin list display. I keep getting this error 'User' object has no attribute 'MyProfile' models.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from userena.models import UserenaBaseProfile class MyProfile(UserenaBaseProfile): user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='my_profile') dealer_num = models.CharField(blank=True, max_length=15, verbose_name="Dealer Number") Admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import MyProfile class ProfileInline(admin.StackedInline): model = MyProfile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' fields = ('user', 'dealer_num') class UserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('username', 'get_dealer_num') def get_inline_instances(self, request, obj=None): if not obj: return list() return super(UserAdmin, self).get_inline_instances(request, obj) def get_dealer_num(self, obj): return obj.MyProfile.dealer_num admin.site.unregister(User) admin.site.register(User, UserAdmin) -
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied?
I am following this tutorial to enable my django application to upload the file directly to S3. https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html When created a new IAM user, I enabled the full access to my S3. AmazonS3FullAccess But when i uploaded the file I still got the error of An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I tried to add a policy to my S3 bucket then. But i constantly got the error of Policy has invalid action { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets", "s3:GetBucketLocation" ], "Resource": "*", "Principal": { "AWS": "[my-IAM user]" } }, { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::[s3-bucket-name]", "Condition": { "StringLike": { "s3:prefix": [ "", "home/", "home/${aws:username}/*" ] } }, "Principal": { "AWS": "[my-IAM user]" } }, { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::[bucket-name]/home/${aws:username}", "arn:aws:s3:::[bucket-name]/home/${aws:username}/*" ], "Principal": { "AWS": "[my-IAM user]" } } ] } What exactly should i do then? -
Django query set filter
I'm trying to create a query set that filters all the cars hired by a user. the car hire model has a foreignkey which stores the user's ID when a car is hired My current solution is like this, where I get current users ID and then try filtering the Cars database against the user's ID. def view_hire(request): current_users_id = request.user.id car_hired = Cars_hired.objects.filter(user_id__in=current_users_id) However, I can't seem to get this to work and I am getting the error "'int' object is not iterable" I would like to create a query set that returns the row of data that matches the query for example, if the current user's id is 10 I would like to get all the cars hired by the user. All the data stored in the rows where car_hirer_is == 10 -
Django: updating only edited data from modelform
I have a page where I show a person profile. I only show 9 of 10 fields in the template. When I save changes in the form, that "not shown" field is always changed to empty. I´m getting the dict of changed_data and setting the update_fields with it, but I still have the problem. It seems like you HAVE to show ALL the form fields in the template. How can I solve this. def PerfilPersonasView(request, persona_id): persona_id = persona_id persona = Personas.objects.get(pk=persona_id) if request.method == "POST": perfil_persona_form = FormularioPersonas(request.POST, instance=persona) if perfil_persona_form.is_valid(): esta = perfil_persona_form.save(commit=False) campos_editados = perfil_persona_form.changed_data esta.save(update_fields=campos_editados) -
How to convert multiple HTML pages to PDF file one-by-one? (Python/Django/Wagtail)
I want to convert a several Wagtail pages to PDF file and save them. Previously, It was done in case of single page, and now I need to modify the code to be able to convert several ProjectPage objects from so-called portfolio to PDF file. Here is what I've already tried, but the PDF file which is downloaded always is broken. import time from django.conf import settings from django.http import HttpResponse from django.shortcuts import render from django.utils.safestring import mark_safe from rest_framework import views from portfolio.models import ProjectPage class ConvertToPdfView(views.APIView): def get(self, request, *args, **kwargs): path = request.META['PATH_INFO'] if path.find('portfolio') == -1: return HttpResponse() slug = path[path[1:].find('/') + 2:] slug = slug[:slug.find('/')] if slug == 'pdf': return HttpResponse() file_name = str(round(time.time())) render_file = 'media/temp/render/' + file_name + '.html' response_file = 'media/temp/response/' + file_name + '.pdf' projects = self._get_projects() for project in projects: rendered_template = mark_safe(render( request=None, template_name='pdf_export/project_page_pdf.html', context=project.get_context(request), content_type="text/html" ).content).decode("utf-8").encode('ascii', 'ignore') text_file = open(render_file, "a+") text_file.write(str(rendered_template)[2:-1].replace('\\n', '').replace('\\r', '\n').replace("\\'", "\'")) text_file.close() response = HttpResponse(rendered_template, content_type='text/html') response['Content-Disposition'] = \ 'attachment; filename="' + project.title + '.' + settings.RESPONSE_EXTENSION + '"' return response @staticmethod def _get_projects(): return ProjectPage.objects.all()[:4:] -
how update webapp realtime by new scraper data
I would like to have some tips on how to set up my own personal project. I have a scraper python that looks for data in real time. I would like to create a web app to view these data, it would be good through a push of the scraper so as not to make continuous requests to a possible database. I would like to use Ruby on rails for the web app or even django, but I think it is irrelevant. How should I set everything? -
How to deploy django Project on Live server?
This is my first time when i am deploying my site on live server(my company server).I have built small django project which i want to deploy on my company server. can anyone tell me how to do it because when i have tried same precedure what we do in our local server it is not working ? thanks -
Django: How to serialize a one to many relationship
I can't seem to figure out how to serialize a one to many relationship in Django, The information doesn't seem to even appear. My models class DataInfo(models.Model): component_id = models.CharField(max_length=4) component_name = models.CharField(max_length=255) data_id = models.IntegerField() data_name = models.CharField(max_length=255) class Data(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='data_owner') subject = models.CharField(max_length=255) init_date = models.DateField() fin_date = models.DateField() data_info = models.ForeignKey(DataInfo, related_name="datainfo", on_delete=models.CASCADE) My View class DataViewSet(viewsets.ModelViewSet): serializer_class = serializers.DataSerializer def list(self, request): data = models.Data.objects.using(db_to_use).select_related('data_info').all() return Response(self.get_serializer(data, many=True).data) My serializers class DataInfoSerializer(serializers.ModelSerializer): class Meta: model = models.ConversationInfo fields = ('id', 'component_id', 'component_name', 'data_id', 'data_name') class DataSerializer(serializers.ModelSerializer): datainfo = ConversationInfoSerializer(source="datainfo", read_only=True) class Meta: model = models.Conversation fields = ('id', 'subject', 'init_date', 'fin_date', 'owner_id', 'data_info_id', 'datainfo') I'm essentially just trying to do a join between Data and DataInfo, showing all the fields of Data and DataInfo in one view (not nested). I tried doing a select_related, putting a source attribute, nothing seems to work. The response I get is just all fields of the Data table with no fields of the DataInfo table. Am I missing something with the serialization? -
Where should i use transaction in save method Django?
I have some problem to choose where should i use atomic transaction, should i use it like this? def save(self, **kwargs): try: with transaction.atomic: super(User, self).save(**kwargs) if self.image: img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) except (OSError, IOError): self.image = None with transaction.atomic: super(User, self).save(update_fields=['image']) raise PValidationError('Image can`t be saved') Or there is more intresting way to use this? -
How to setup registration and signals in django 2.0
Can someone help me figure out what i am doing wrong trying to setup authentication and signals to work along with the models created in django 2.0. models.py from django.db import models from django.conf import settings.AUTH_USER_MODEL from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.TextField(foo) location = models.CharField(foo) # Override save method # Run after the method is saved to add signal functionality below def save(self, *args, **kwargs): super().save(*args, **kwargs) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() forms.py from django import forms from django.contrib.auth import get_user_model from django.forms import ModelForm from .models import Profile Profile = get_user_model() class UserRegisterForm(forms.ModelForm): email = forms.EmailField(foo) first_name = forms.CharField(foo) last_name = forms.CharField(foo) password = forms.CharField(foo) password2 = forms.CharField(foo) class Meta: model = Profile fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ] views.py from django.shortcuts import render, redirect from django.contrib.auth import get_user_model from .forms import UserRegisterForm from .models import Profile from django.conf import settings def register(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) if next: return redirect(next) return redirect('accounts:login') context = { 'form': … -
Chrome says 'No manifest detected' when manifest.json is served by Django
I have an SPA with Django on backend. I try to make it a progressive web app. I made a manifest.json and linked it in my index.html: <link rel="manifest" href="/static/manifest.json"> Chrome can't detect it. I think it's because index and manifest are in different directories. My index.html is a Django template and is stored in templates directory and can't be accessed but by Django route /. Manifest.json is in static folder and served to front-end as a regular static file. I think this is the reason manifest can't be detected - files being in different dirs. If so, could you give me an advice as to how to make it work please? -
How to get child model having foregin key of parent model in Django rest framwork?
now i want output such a way that there for each list i must get entire timing record how to achieve it below is my model model.py class Refreshment(models.Model): title = models.CharField(max_length=200, unique=True) charges = models.DecimalField(max_digits=12, decimal_places=2, help_text="Charges per hour") class Timeing(models.Model): refreshment = models.OneToOneField(Refreshment,on_delete=models.CASCADE) sunday_open = models.TimeField(blank=True, editable=True) Below is my views.py @api_view() def all_games_sports(request): entertainment = Refreshment.objects.filter(type=1) serialize = EntertainmentSerializer(instance=entertainment, many=True) main = {'status': True, 'code': "CODE_SUCCESSFUL", 'msg': "SUCCESS", 'all_games_sports': serialize.data} return Response(main)