Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django using ajax to call backend has problem
I'm new to Django. There is a heart icon in my html file, and I want when I click it, it turns to red and then call a function in backend to change a number in database and send back the new number to the template, all using Ajax. What should I do, and where is the problem? In html file: <i class="fas fa-heart"></i> <b>{{ note.like }}</b> The script part: <script> $(document).ready(function() { $('.fa-heart').click(function(e){ this.style.color = this.style.color == 'red' ? 'white' : 'red'; e.preventDefault(); $.ajax({ type:'POST', url:"vote/like/", data:{ num:"niloofar", csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ alert(data); }, error : function() { console.log("Error"); } }); }); }); </script> In views: def like(request): if request.method == 'POST': print(request.POST) return HttpResponse('done') And the error is: Internal Server Error: /notes/1/vote/like/ Traceback (most recent call last): File "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: like() got an unexpected keyword argument 'id' -
Facing problem with 'request.POST.get()' method it is not fetching the right data
I have just started learning Django. But, I couldn't resolve one problem I am facing, any kind of help will be appreciated here is my views.py from django.shortcuts import render def homeGrade(request): print(request.method) if request.method == "POST": num = float(request.POST.get("marks")) # here print(num) if num >= 80: grade = "Grade A" elif num >=60: grade = "Grade B" else: grade = "Grade C" msg = "Your marks are " + str(num) + " and your grades are " + grade return render(request, 'findgrade/home.html', {"msg":msg}) else: return render(request, 'findgrade/home.html', {}) And here is my template home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Find Grade</title> <script> function validate() { var m = document.getElementById("marks"); var e = document.getElementById("err"); var a = document.getElementById("ans"); if( m.value = "" | m.value < 0 | m.value > 100) { alert("Invalid Marks"); e.style.visibility = "visible"; m.value = ""; m.focus(); a.textContent = ""; return false; } else { return true; } } </script> </head> <body> <center> <h2> Find grade app </h2> <form method="POST" onsubmit="return validate()"> {% csrf_token %} <input type="number" name="marks" placeholder="Enter the marks" id="marks"> <label id="err" style="color:red; visibility: hidden"> Invalid Input </label> <br><br> <input type="submit" name="Find"> </form> <h2 id="ans"> {{ msg }}</h2> </center> </body> </html> for some reason, … -
Django chat how to store logged user data
I'm creating simple django chat. I need to fetch the "checkuser" from first function and use it into another function "def chat()" in "USERHERE" field def home_view(request): if request.method == "POST": form = LoginForm() global username username = request.POST['username'] password = request.POST['password'] try: global checkuser checkuser = chat_user.objects.get(username=username, password=password) except: form = LoginForm() return render(request, 'incorrect/incorrect.html', {'form': form}) return render(request, 'login.html', {'form': form}) def chat(request): chatform = ModelChatFormSave() if request.method == "POST": chatform = ModelChatFormSave(request.POST) if chatform.is_valid(): cdata= chatform.cleaned_data['message'] chat_message.objects.create(message=cdata, sender="USERHERE", chatuser=chat_user.objects.get(name="USERHERE)) chatform = ModelChatFormSave() return render(request, 'grats/grats.html', {'chatform': chatform}) -
what is the right way to test django channels?
I tried this , but got error TypeError: object.__init__() takes exactly one argument (the instance to initialize) class MyTests(TestCase): async def test_my_consumer(self): communicator = HttpCommunicator(Alerts, "GET", "/alerts/") res = await communicator.get_response() print(res) also i treid this, but the res always null class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome('./chromedriver') except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): res = self.driver.get(self.live_server_url + '/alerts/') print(res) -
'Post' object has no attribute 'get_absolute_url' Django
I am trying to create a sitemap in Django but I am getting an error 'Post' object has no attribute 'get_absolute_url' Here is my anotherfile/sitemap.py from django.contrib.sitemaps import Sitemap from somefile.models import Post class site_map(Sitemap): changefreq = "daily" priority = 0.8 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.time_stamp and here is my somefile/models.py class Post(models.Model): number=models.AutoField(primary_key=True) slug=models.CharField(max_length=130) time_stamp=models.DateTimeField(blank=True) def __str__(self): return self.number -
django form no errors
I am trying to create a custom login form, when I validate the form there are no errors and it is not valid Is there a better way to implement what I want? At least I want just to get the values from the form fields. class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', } )) def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): print(True) else: print(False) print(username) print(password) # authUrl = "" # authData = {'usname': request.POST['username'], # 'psword': request.POST['password'], # } # s = requests.Session() # rAuth = s.post(authUrl, data=authData).json() # if rAuth["status"] == 200: # pass else: form = LoginForm() return render(request, 'users/login.html', {'form': form}) -
How to deploy React and Django REST framework on kubernetes using minikube?
In minikube, my Django app is properly working but now I want to use my backend API in React frontend but I'm not able to do this can anyone help me ? Here my backend deployment.yml file, apiVersion: apps/v1 kind: Deployment metadata: name: movie-deployment spec: replicas: 1 selector: matchLabels: app: movie-backend template: metadata: labels: app: movie-backend spec: containers: - name: movie-backend image: javiercode/movie-backend env: - name: SECRET_KEY valueFrom: configMapKeyRef: name: movie-env key: SECRET-KEY - name: DEBUG valueFrom: configMapKeyRef: name: movie-env key: DEBUG --- apiVersion: apps/v1 kind: Deployment metadata: name: postgres-deployment spec: replicas: 1 selector: matchLabels: app: postgres-container template: metadata: labels: app: postgres-container spec: containers: - name: postgres-container image: postgres:12.0-alpine volumeMounts: - name: postgres-volume-mount mountPath: /var/lib/postgresql/data volumes: - name: postgres-volume-mount persistentVolumeClaim: claimName: postgres-pvc --- apiVersion: batch/v1 kind: Job metadata: name: django-migrations spec: template: spec: containers: - name: django image: javiercode/movie-backend command: ["/bin/sh","-c"] args: ["python3 manage.py makemigrations;python3 manage.py migrate"] env: - name: SECRET_KEY valueFrom: configMapKeyRef: name: movie-env key: SECRET-KEY - name: DEBUG valueFrom: configMapKeyRef: name: movie-env key: DEBUG restartPolicy: Never backoffLimit: 5 backend service.yml apiVersion: v1 kind: Service metadata: name: movie-backend-service spec: selector: app: movie-backend ports: - protocol: TCP port: 8000 targetPort: 8000 type: LoadBalancer --- apiVersion: v1 kind: Service metadata: name: … -
Are fixtures supported in Djongo?
I'd like to create fixtures and use them in tests. But when I try to load them e.g. by running ./manage.py loaddata test.json, I get DeserializationError. Traceback: django.core.serializers.base.DeserializationError: Problem installing fixture '/app/test.json': Value: OrderedDict() stored in DB must be of type dict/listDid you miss any Migrations?: (template.template:pk=5) field_value was 'OrderedDict()' This is just one example, but, basically, it complains about any JSON string it encounters. So it looks as though test.json is deserialized once and values for JSONFields are left as JSON strings. So it throws an error here: # from Djongo's JSONField class def to_python(self, value): if not isinstance(value, (dict, list)): raise ValueError( f'Value: {value} stored in DB must be of type dict/list' 'Did you miss any Migrations?' ) return value There is a kinda similar issue on Github that is abandoned. So I am not sure if fixtures are even supposed to work with Djongo at this point. Thanks in advance for any clarifications. -
How can I render all data to invoice page?
How can I render all data to the invoice page? data line product quality, cost, total price, etc. whenever I click on the make bill button it is redirected to the invoice page but data is not showing. views.py def makebill(request): if request.method == "POST": cart = request.POST.get('cart') price = request.POST.get('price') n = request.POST.get('name') phone = request.POST.get('phone') data = json.loads(cart) for c in data: name = c['name'] qty = c['qty'] prod = Product.objects.get(name=name) prod.qty = prod.qty - int(qty) if prod.qty <= 0: messages.warning(request, f'{prod.name} has finished') prod.delete() else: prod.save() p = Sales(items_json=cart, amount=price, name=n, phone=phone) p.save() return redirect('home:invoice') total = price else: product = Product.objects.all().order_by('name') product_list = list(product.values('name', 'cost')) context = {} context["product"] = json.dumps(product_list) try: context["total"] = total except: pass return render(request, 'makebill.html', context) How can I do? Thanks in Advance! -
DRF filtering with `fieldset_filters` using multiple queries for the same queryparam
I'm using Django and DRF, with DjangoFilterBackend for filtering the queryset results. How do you pass multiple queries to the same queryparam? For example if I had 'id' set in filterset_fields=['id'], to enable filtering Users by their ID. To filter for id 99, the url would look like this: api/user/?id=99. How would you filter for multiple ID's in one request? Is it even possible? I would like to be able to do something like this: api/user/?id=99,133,234 or maybe api/user/?id=99&id=133&id=234. This is currently NOT working for me, it just returns the first param. Thanks! -
Hide few fields in django view
I want to dynamically show/hide fields of django forms in views. Currently i am able to disable fields from views and able to dynamically render fields but cannot hide (without consuming field space in html). For example i have address field in django form and i am disabling like below in view registration_form.initial['address'] = register[0]['address'] registration_form.fields['address'].disabled = True To hide field i have tried below but it occupies space of field in html registration_form.initial['address'] = register[0]['address'] registration_form.fields['address'].widget = HiddenInput() How can i hide field from django form? -
related_name doesn't work in Django about some different objects
I have trouble about calling related models. my models: class Product(models.Model): product_model = models.CharField(max_length=255, default='') product_url = models.SlugField(max_length=200, default='') product_category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True, related_name="products", ) product_subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, default='', null=True, related_name="products", ) description = tinymce_models.HTMLField(verbose_name="text") product_img = models.ImageField(upload_to="product_imgs/" ,default='') class Stock(models.Model): ONE = '1' TWO = '2' FREE = 'free' PRODUCT_SIZES = [ (ONE, '1'), (TWO, '2'), (FREE, 'free'), ] size = models.CharField(max_length=60,default=" ", choices=PRODUCT_SIZES) quantity = models.PositiveIntegerField(default=0) price = models.FloatField(default=0, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="pro") each product can has 3 stock object with different sizes, I want show a product quantity in stock with all sizes, for example (size1 has 10, size2 has 10, sizefree has 10, I want show 30) my views: def products(request): if request.user.is_staff or request.user.is_superuser: products = Product.objects.filter() ctx = {'products':products} return render(request, 'staff/products_list.html',ctx) else: return redirect('/staff') and my html <td class="text-info"> {% for product in product.pro.quantity.all %} {{product}} {% endfor %} </td> how can I solve this problem ? -
Django Model ListAPIView serializer for counting objects
I have a model as follows, Entity : class Entity(models.Model): uuid = models.CharField(max_length=12, default=None) description = models.CharField(max_length=255, default="") I want to provide a serialization for the all entity objects where the response will provide the count of each description type that is available in the database. For instance, the table has the following content: 1.cat 2.dog 3.cat 4.dog 5.bird 6.bird 7.dog The serialization will be : dog : 3 cat : 2 bird :2 How should I modify the following serializer code to make this happen ? #Entity Count(per Intelligence) Search class EntityFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('description') class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class EntityList(generics.ListAPIView): model = Entity serializer_class = EntityFilterSerializer filter_backends = [filters.SearchFilter] queryset = Entity.objects.order_by('id') search_fields = ['=uuid', ] pagination_class = StandardResultsSetPagination -
permission login django redirects to login
I'm trying to implement user permission. Based on the user logged in different pages will be shown. But for some reason, it keeps redirecting me to same the login page with a path that includes the desired direction something like that (dashboard/login/?next=/dashboard/index/) instead of the admin view or user view (based on the inputs). I suspect that the issue is in login.html but not sure where it is login.html <form method="POST" action="" class="user"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Username..."> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <a href="{% url 'index'%}" class="btn btn-primary btn-user btn-block"> Login </a> <hr> </form> <hr> <div class="text-center"> <a class="small" href="{% url 'forgot_pass'%}">Forgot Password?</a> </div> <div class="text-center"> <a class="small" href="{% url 'register'%}">Create an Account!</a> </div> decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = … -
Django radio widget with free input value
I'd like to implement/find a multiple radio select with an "other" option that allow users to enter their own answer. Something like that: http://garmoncheg.blogspot.com/2014/05/implementing-multiple-radio-select.html I'm affraid this link points to a code that is outdated (I'm using django 2.2) Do you know such a module? If not, what approach would you take to implement it? -
Pagination in DRF gives "'list' object is not callable"
Using Django Rest Framework I'm trying to expose a read-only endpoint. Unfortunately I get an error which (if I read it correctly) relates to the pagination. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/mixins.py", line 40, in list page = self.paginate_queryset(queryset) File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 169, in paginate_queryset if self.paginator is None: File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 162, in paginator self._paginator = self.pagination_class() Exception Type: TypeError at /api/v1/machines/ Exception Value: 'list' object is not callable I've got no pagination set up for this viewset though. My serializer looks like this: class MachineSerializer(serializers.Serializer): class Meta: model = Machine fields = '__all__' my viewset like this: class MachineDataViewSet(viewsets.ReadOnlyModelViewSet): queryset = Machine.objects.all() serializer_class = MachineSerializer and in my setting I've got my pagination class set up like this: DEFAULT_PAGINATION_CLASS=('rest_framework.pagination.LimitOffsetPagination',), Does anybody know what … -
Django social media Login(google)
i have a problem in google login. after login with google auth in my django proj, i can't do anything with it tokne! in other app,i can easily take username with request.user but with google loging,i cant! djnago said you are loging with AnonymousUser.i konw why but i cant handle it. Token list's are Separately in google login and Local Login. in my other app, i do everything with request.user, but now, i stucking. how can i get information from user's who logged in with google login? -
'AssertionError' object has no attribute 'message'
I'm dealing with form in django that once its filled sends an email to the user but im getting the following error: error image I have checked in my code and my problem comes from this function: def send_manually_exception_email(request, e): exc_info = sys.exc_info() reporter = ExceptionReporter(request, is_email=True, *exc_info) subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989] message = "%s\n\n%s" % ( '\n'.join(traceback.format_exception(*exc_info)), reporter.filter.get_request_repr(request) ) mail.mail_admins(subject, message, fail_silently=True, html_message=reporter.get_traceback_html()) What can I do? -
Django - How to declare IntegerChoice & IntegerField for the whole django project (globally)
I defined following class: class LocationInterestRegion(models.Model): class LocationInterestRegionTypes(models.IntegerChoices): CITY = 0 , _('city level') COUNTY = 1 , _('province level') STATE = 2 , _('regio/state level') COUNTRY = 3 , _('country level') INTERNATIONAL = 4 , _('international level') __empty__ = _('Select the region from where to find candidates.') location_interest_region = models.IntegerField(choices=LocationInterestRegionTypes.choices, null=True) And then tried to use this in another model as a ForeignKey class Job(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True) location_interest_region = models.ForeignKey(LocationInterestRegion, on_delete=models.CASCADE,blank=True, null=True) Now I cannot access the options in my form. class JobCreateForm(forms.ModelForm): class Meta: model = my_model fields = [ 'location', 'location_interest_region', ] I could solve the issue by not using the foreign key and intergrating the first model in the second one. But if I want to use these "choices" in several other models. I need to redefine them in every model. Is there a way to define these choices globally ? -
Django values_list() lowercase
I have query set that I am exporting to CSV. models.One2OneInfoLog.objects.filter(one_2_one_info=pk).values_list('name', 'location', 'created').order_by('created') I want the 'name' field to be in lowercase. Is their a way to do that? -
Django ModelTranslation
Hello guys i need a help for translating models values. I use django-modeltranslation package. I have managed to register my models. class Institution(models.Model): title = models.CharField(_('Title'),max_length = 200) address = models.CharField(_('Address'),max_length=50) pobox = models.CharField(_('Pobox'),max_length=5) city = models.CharField(_('City'),max_length=64) country = models.CharField(_('Country'),max_length=50) telephone = models.CharField(_('Telephone'),max_length = 10) def __str__(self): return self.title class Department(models.Model): title = models.CharField(_('Title'),max_length = 200) address = models.CharField(_('Address'),max_length=50) pobox = models.CharField(_('Pobox'),max_length=5) city = models.CharField(_('City'),max_length=64) country = models.CharField(_('Country'),max_length=50) telephone = models.CharField(_('Telephone'),max_length = 10) institution=models.ForeignKey(Institution,on_delete=models.CASCADE,verbose_name=_('User')) def __str__(self): return self.title Register @register(Institution) class InstitutionTranslationOptions(TranslationOptions): fields = ('title', 'address','city','country') @register(Department) class DepartmentTranslationOptions(TranslationOptions): fields = ('title', 'address','city','country') Here is how i change language: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> Ok i open admin i put values for the 2 languages but in template i cant get them... I get only the default value... I use: {{ department.title }} Am I doing something wrong? -
when i enter the django admin using python manage.py runserver, occur 'ValueError at /admin'
when operate runserver, and then enter ther url 'http://127.0.0.1:8000/admin', occur this error. At the terminal, occur this error ValueError: Field 'id' expected a number but got 'favicon.ico'. At the browser, occur thie error ValueError at /admin Field 'id' expected a number but got 'admin'. Request Method: GET Request URL: http://127.0.0.1:8000/admin Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'admin'. code here How can solve this problem?? -
How to make a generic List Filter in Django using django-filters?
I want to have a FilterSet class that allows all of the fields to be filtered as a list. I was thinking of overriding the default FilterSet class of django-filters and having the fields be dynamically set as well as setting a method to each one. So, something like this for example: ModelName_fields = {'names': 'name', 'ids': 'id', 'second_ids': 'second_id'} class ListFilter(FilterSet): def __init__(self, *args, **kwargs): # self._meta.fields = [field_name for field_name in modelNameHere + '_fields'] super(FilterSet).__init__(*args) class SomeAPIView(mixins.ListModelMixin): model = ModelName filterset_class = ListFilter Basically, ModelName_fields is a declared constant that maps the query parameter to the field name of the model. In this case, I declare the model on the view as well as the filterset class and in the __init__ method of the filterset class, I dynamically attach the fields as well as the query parameter name. In all essence, I just want to make the ListFilter as generic as possible to be used on different views as well. My question is, is this the correct way or is there some other better way to accomplish this? Also, how can I get the name of the model, which is an attribute of the view class, in the … -
I Can't able to pass a values(id) in urls in django
After user login their account, it is redirect to home page. In that home page i added profile option for user to edit and view their profile. but logged user only view his profile.so i need add id in url for show the specific profile page for the user.but i cant do that with my code. I need like this [" 121.0.0.1:8000/profile/1 or 121.0.0.1:8000/1/profile]..But i got this ['121.0.0.1:8000/profile/'] cant add id in url and it throws page not found error Views.py class ShowProfilePageView(DetailView): model = Profile template_name = 'bgmiapp/user_profilepage.html' def get_context_data(self,*args,**kwargs): context = super(ShowProfilePageView,self).get_context_data(*args,**kwargs) page_user = get_object_or_404(Profile,id=self.kwargs['pk']) context["page_user"] = page_user return context views.py/home def home(request): profile=Profile.objects.all() return render(request,'bgmiapp/home.html',{'profile':profile}) URLS.py from django.contrib import admin from django.urls import path from . import views from .views import ShowProfilePageView urlpatterns = [ path('home/',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.login_view,name='login'), path('<int:pk>/profile/',ShowProfilePageView.as_view(),name='show_profile_page') templates : home.html {% extends 'bgmiapp/base.html' %} {% load static %} {% block title %} Home {% endblock %} {% block content %} <h3> homepage coming soon!!!!</h3> <a href="/profile/{{ profile.id }}">profile</a> {% endblock %} -
Django : Not able to add solution to a particular question using CBV
I am having an app where people can ask and answer questions views.py class SolutionsCreateView(CreateView): model = Solutions template_name = "log/add_solution.html" slug_url_kwarg = 'solution' slug_field = 'slug' context_object_name = 'solution' fields = ['solution', 'image'] def form_valid(self, form): solution = form.save(commit=False) solution.author = self.request.user #solution.log = I need to set this solution.save() return super(SolutionsCreateView, self).form_valid(form) There is a model Log and another model Solutions models.py: class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): super().save() self.slug = self.slug or slugify(self.title + '-' + str(self.id)) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("log-detail", kwargs={"question": self.slug}) class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" {self.solution} " def get_absolute_url(self): return reverse("log-solution", kwargs={"solution": self.slug}) How do I access log in Log model …