Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 Page not found Django even though it is in urls.py
I don't know why I am getting a 404 error on the page flights/1 when clearly, I have a url pattern for <int:flight_id> (flights is a app). Help! My urls.py for the project from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('flights/', include('flights.urls')) ] My urls.py for the flights app from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"),\ ] And the views.flight def flight(request, flight_id): flight = Flight.objects.get(id=flight_id) return render(request, "flights/flight.html", { "flight": flight, "passengers": flight.passengers.all(), "non_passengers": Passenger.objects.exclude(flights=flight).all() }) -
How to implement a like system in Django templates
I am currently working on building a "like" system for a blog-style website in Django. I've been looking at several different examples for setting up the HTML templates and was hoping to better understand some of the logic. My first thought was to tie the "like" button to the corresponding view like so: <a class="btn btn-secondary" href="{% url 'post-like' post.id %}" role="button">Like ({{ post.likes.count }})</a> This seemed to work decently well (the "like" was registering and showing up in the count) but I was having trouble getting back to the right page after clicking the "like" button (i.e. when I clicked "like" it took me to some other page vs. staying on the home page). I then found another example online that created a get_like_url() function under the broader Post Model like this: def get_like_url(self): return reverse("post-like", kwargs={"pk":self.id}) And then called it in the template like this: <a class="btn btn-secondary" href="{{ instance.get_like_url }}" role="button">Like ({{ post.likes.count }})</a> I thought this was basically doing the same thing but when I used this method it would return me to the home page of my site but wouldn't register the like (i.e. didn't seem like the button actually did anything). Could anyone help … -
Is there a way to solve this ValueError in my django app?
I’ve created a school database intranet app for schools using the Django framework. I’m trying to get the teacher to update the registered student’s assessment within the Teachers account. I've used ForeignKey relations to relate the Student account with the Assessment models but I seem to be getting this “ValueError at /Teacher/Grade9_classA_teacher/Grd9_ClsA_math_Term_1_assesment1_createview2b2371fd-7e64-413a-adcd-43c8b68cd9d3/ Cannot assign "<QuerySet [<Grade_9_Student: account1>]>": "Grade_9_models_math_Term1_assesment_1.user_Name" must be a "Account" instance.” I don’t know what this means, somebody please help solve my problem. This is my assessment model codes from admin_app.models import Account #Assessment models class Grade_9_models_math_Term1_assessment_1(models.Model): user_Name=models.ForeignKey(Account, on_delete=models.CASCADE, default=None, max_length=250, blank=True, null=True) T1_A1_Maths_Title=models.CharField(max_length=50, blank=True, null=True) T1_A1_Maths_Desc=models.CharField(max_length=100, blank=True, null=True) T1_A1_Maths_is_Test=models.BooleanField(default=False) T1_A1_Maths_Marks=models.IntegerField(blank=True, null=True, default=0) T1_A1_Maths_OutOfMarks=models.IntegerField(blank=True, null=True, default=0) T1_A1_Maths_DatePosted=models.DateTimeField(verbose_name='date posted', auto_now_add=False, null=True, blank=True) This is my assessment form codes #Forms.py from Student.student_views.Grade9_std_views.Grade9_models import Term_11_math_assesment, Grade_9_Student #Term 1 #Maths assesment 1 class Grd9_ClsA_math_Term_1_assesment1_form(ModelForm): T1_A1_Maths_is_Test=forms.BooleanField(widget=forms.CheckboxInput) class Meta: model=Grade_9_models_math_Term1_assesment_1 fields=['T1_A1_Maths_Title', 'T1_A1_Maths_Desc', 'T1_A1_Maths_is_Test', 'T1_A1_Maths_Marks', 'T1_A1_Maths_OutOfMarks', 'T1_A1_Maths_DatePosted'] This is my main user model codes from django.db import models from django.urls import reverse import uuid # Create your models here. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager #from Teacher.Teacher_views.Grade9_views.Grd9_assesment_models import Grade_9_models_math_Term1_assesment_1 class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("email is not pressent") if not username: raise ValueError("username is not pressent") user=self.model( email=self.normalize_email(email), username=username ) … -
import couses ImportError only when in try except block
I have two modules that import some stuff from each other: urls.py: from helpers import helper urlpatterns = [ # patterns ] helpers.py: def helper(): # some magic def main(): from urls import urlpatterns # process urlpatterns __init__.py: from helpers import main main() And everything works fine, until I wrap from urls import urlpatterns to look like this: def main(): try: from urls import urlpatterns except Exception as e: print(str(e)) It prints: cannot import name 'combinations' from partially initialized module 'urls' (most likely due to a circular import) (/Users/MaxCore/Documents/www/project/urls.py) What can be a reason? -
Auto expanding textarea in Django
I want to have a textarea which will auto expand(vertically) with input text in Django crispy form. Is there any simple way to do this. -
DELETE method in django rest api not wiorking
**C:\Rest apps\withoutrestm>py test.py 200 Traceback (most recent call last): File "test.py", line 54, in delete_resource(3) File "test.py", line 53, in delete_resource print(resp.json()) File "C:\Users\home1\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 898, in json return complexjson.loads(self.text, kwargs) File "C:\Users\home1\AppData\Local\Programs\Python\Python37\lib\json_init_.py", line 348, in loads return _default_decoder.decode(s) File "C:\Users\home1\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\home1\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
how to use m2m_changes signals to update my ManyToManyField django
i want to to update field whenever an instance been created i tried signals but it seems complicate to ManyToManyField , i think i should use m2m_changes , but i havnt idea how to do it! i tried many ways but non of them worked class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i want to update active field in Imei model when MobileCustomer created !? i tried these in my CreateView form_valid imei = Imei.objects.filter(selectmobile__item=self.object).update(active=False) print(imei) #Imei.objects.filter(mobile__mobilecustomer=self.object).update(active=False) #Imei.objects.filter(mobile__selectmobile__item=self.object).update(active=False) and it all printed 0 while imei was not 0? i think i should use m2m_changes signals but i dont have any idea how to do it? i have not used m2m_changes before ! how to make it work either using signals or update() whenever an instance created inside createview -
Django and python, how to get a annotate from two different model?
I have the following model framework: class Subcategory(models.Model): nome=models.CharField() class Order(models.Model): order=models.CharField() class Quantity(models.Model): order=models.ForeignKey(Order) subcategory=models.ForeignKey(Subcategory) quantity=models.DecimalField() class Price(models.Model): order=models.ForeignKey(Order) subcategory=models.ForeignKey(Subcategory) price=models.DecimalField() Now I want to obtain a new value that give me the possibility to filter for subcategory and order both price and quantity queryset and give me the moltiplication of them. this is the code that I have set, but I don't know how obtain the price*quantity operation. cod='1234' price=dict() defaults=list(0 for m in range(1)) filter_quantity = list(Quantity.objects.values_list('subcategory__id', flat=True).distinct()).filter(order__order=cod) for subcategory__id, totals in(Price.objects.filter( subcategoty__in=filter_quantity ).values_list('subcategory__id').annotate(totals=ExpressionWrapper(Sum(F('price')), output_field=FloatField())).values_list('subcategory__id', 'totals'): if subcategory__id not in price.keys(): price[subcategory__id ]=list(defaults) index=0 price[subcategory__id][index]=totals total_costs={'Costs': [sum(t) for t in zip(*price.values())]} -
How to verify the Authorization header using OAuth 1.0a or HMAC-SHA1 and Django Rest Framework
I'm using Django 3.0.7 and Django Rest Framework. All logic specific to my endpoint works pretty fine. My serializers.py looks like this class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ['title', 'body', 'image', 'date_updated', 'username'] def get_username_from_author(self, blog_post): username = blog_post.author.username return username And views.py @api_view(['POST']) def api_create_blog_view(request): blog_post = BlogPost(author=request.user) if request.method == 'POST': serializer = BlogPostSerializer(blog_post, data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But my partner sever that sends to my API server requests uses OAuth 1.0a validation or HMAC-SHA1. The request Header looks like this: Method: POST URL: http://api.example.com/event?foo=bar Authorization header value: OAuth realm="",oauth_consumer_key="abcd1234",oauth_nonce="abcde",oauth_signature="abcd",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1234567890",oauth_version="1.0",xoauth_requestor_id="12345" As i understood Django Rest Framework support Django OAuth Toolkit with OAuth 2.0. I will be appreciated if you'll show how to handle Django Rest Framework with OAuth1.0a request. -
Elasticsearch_DSL_n_affiche_que_les_dix_premiers_résultats_de_recherche
J'essaie d'utiliser Elasticsearch-dsl-py pour indexer certaines données, lors de l'exécution d'une requête, j'ai trouvé que seuls les dix premiers résultats étaient affichés, lorsque j'ai fait une recherche, j'ai trouvé que Elasticsearch est par défaut affiche un résultat de taille ne dépassant pas 10. puis-je trouver quelqu'un ici qui a rencontré le même problème et l'a résolu? Merci. -
Django: Why is password not correctly encrypted after changing to a custom user model?
When I register a user, the password is passed to my backend not correctly. In my admin panel I get the error 'Invalid password format or unknown hash algorithm'. I have switched to a custom user model recently and assume that this could be the reason. Before the changed I was able to register users with an encrypted password. However, I cannot find my error. Im happy for any hint. Settings PY AUTH_USER_MODEL = 'user.User' User Model class User(AbstractUser): permissions = models.TextField(blank=True) user_group = models.TextField(blank=True) pass User Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from user.models import User admin.site.register(User, UserAdmin) User Register Serializer # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'groups') extra_kwargs = {'password': {'write_only': True}} User Register API # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) [1] }) URL urlpatterns = [ path('api/auth/register', RegisterAPI.as_view()), ] Signals: Here a new profile is created when the user is created. from django.db.models.signals import post_save from user.models import User from profiles.models import Profile from django.dispatch import receiver @receiver(post_save, sender= User) def create_profile(sender, instance, … -
Django model creation method
Not really experienced in Django and I had trouble while creating a form for a model that had OneToOneField with the Django's User model. models.py With the model I created with something random and the User class Account(models.Model): user_acc = models.OneToOneField(User, on_delete=models.CASCADE) date_joined = models.DateField(...) random_text = models.CharField(...) forms.py I spent a lot of time figuring out how to create the forms for this the right way and the best I found was to create 2 forms and use them in a view (Which I did and it gets the job done but I'm not sure if its the best solution class RegisterUserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password"] widgets = { 'username': forms.TextInput(attrs={'class': "form-control col-4", 'placeholder': "Username"}), 'email': forms.EmailInput(attrs={'class': "form-control col-4", 'placeholder': "Email"}), 'password': forms.PasswordInput(attrs={'class': 'form-control col-4', 'placeholder': "Password"}) } def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('Account with this email already exists') else: return email class AccountForm(forms.ModelForm): class Meta: model = Account fields = ["random_text"] widgets = { "random_text": forms.TextInput(attrs={'class': "form-control col-4", 'placeholder': "Random text"}) } And now I have the view where I put the 2 forms and when I use the POST method I first create the User object and than … -
How to use slug field of another model in HyperlinkedIdentityField
my models.py file as follows : **models.py:** class ProductType(models.Model): title = models.CharField(max_length=100) description = models.TextField() class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True) upc = models.CharField(max_length=255) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=255, db_index=True) My serializers.py file as follows **serializers.py** class ProductTypeSerializer(serializers.ModelSerializer): class Meta: model=ProductType fields='__all__' class ProductSerializer(serializers.ModelSerializer): product_type = serializers.HyperlinkedIdentityField( view_name='producttype-detail',lookup_field = 'slug') class Meta: model=Product fields='__all__' I'm getting the output of product API is as follows { "id": 1, "product_type": "http://127.0.0.1:8000/products/producttype_list/P1/", "title": "Do non officia labore sapiente ab", "description": "Dignissimos aute ius", "upc": "Autem", "slug": "P1", }, { "id": 2, "product_type": "http://127.0.0.1:8000/products/producttype_list/p2/", "title": "Exercitation repudiandae", "description": "Ut consectetur volu", "upc": "Blanditiis et cupidatat delectus beatae qui quos inventore", "slug": "p2", } Where the product_type is the foreign key. product_type contains Hyperlink with a slug of product .but I want to use a slug of product_type table in that hyperlink. Does anybody know how to use slug of another table? Thankx in advance -
Page not found (404) Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/
I'm doing my own portfolio website following a guide and even watched the source code but now it doesn't work and I dont know why This the part in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', ] And this the code in urls.py in the folder personal_portfolio from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("projects/", include("projects.urls")), ] I don't know what I should check in order to fix it -
Event listener not applying
I am trying to apply an on click event listener to buttons that are generated through django templating. My JavaScript file is linked up properly as if I do a standard console log it logs fine but the event listener loop doesn't seem to be doing anything. The for loop applying the event listener to each element with the class update-cart var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) }) } The buttons with the dataset attributes and update-cart class <button data-product="{{product.id}}" data-action="add" class="btn btn-primary update-cart">Add To Cart</button> My JavaScript file linked in the scripts which is included before the end of the Body tag {% load static %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script> <script src="{% static 'js/cart.js' %}"></script> Thanks for any help! -
Keep previous query parameter in url when submitting GET form in django
I have a url searchchoices/?q=sometext&paginate_by=2. When I change the paginate_by value to say 3 in my form, I get the url searchchoices/?q=&paginate_by=3 (notice the missing value for the q parameter). How can I maintain this parameter's value in the QUERY string when submitting the request? My template looks like this: {% load template_tags %} <form method="get"> <input id="q" type="text" placeholder="your search..."> <label for="paginate_by">Number of options per page:</label> <select name="paginate_by" id="paginate_by"> <option value="2">2</option> <option value="3">3</option> <option value="5">5</option> </select> <input type="submit" value="Paginate"> </form> My template_tags.py from django import template register = template.Library() @register.simple_tag(takes_context=True) def query_transform(context, **kwargs): query = context['request'].GET.copy() for k, v in kwargs.items(): query[k] = v return query.urlencode() Also in my views.py, there is this snippet # I believe this is the root of the hassle. q = request.GET.get('q', None) Please how can I get this done? P.S: Beginner in django. -
Rendering Plotly graph onto Django application using data from SQL
I'm trying to integrate a Plotly scatter graph into my Django application following the instructions laid out here: Embedding a Plotly chart in a Django template. The data I want to render on the Plotly graph is from the application's SQL database but I can't figure out how to query the data without dropping values from the dataset. Below is the views.py file: release_dates = list(models.Film.objects.values_list('release_date', flat=True).distinct()) gross = list(models.Film.objects.values_list('gross', flat=True).distinct()) title = list(models.Film.objects.values_list('title', flat=True).distinct()) class Graph(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): context = super(Graph, self).get_context_data(**kwargs) trace1 = go.Scatter(x=release_dates, y=gross, marker={'color': 'red'}, hovertext = title, mode="markers+text", name='1st Trace') data=go.Data([trace1]) layout=go.Layout(title="Films by Gross", xaxis= {'title':'Year'}, yaxis={'title':'Gross'}) figure=go.Figure(data=data,layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') context['graph'] = div return context The problem is that when the Plotly Graph is rendered on the webpage, the data comes out jumbled so that the films' titles don't match their release dates and their gross. I think the problem is that there are missing or "null" values in the database so when I call the list function on the "release_date", "gross" and "title" values_list, the data become misaligned. (I have checked the models on the backend of the site and the data is fine - the problem … -
503 error while using request while using request module
i am trying to get the response from a http web request, when i tried to enter the same url over the website it asked for user name and password, and it returned json after entering the user name and password, but next time it was directly fetching the json. Next i tried to get the response from requests.get in python django url = 'https://employee-dev.comserver/worker/Course&$format=json' r=requests.get(url,auth=HTTPBasicAuth('system', 'system123'),verify=False) when i tried to print the r.error_code its printing 503. How do i resolve it? let me know if you need more debug information -
Reverse for 'author' with keyword arguments '{'name': ''}' not found. 1 pattern(s) tried: ['author/(?P<name>[^/]+)$']
{{ p.catagory.name}} {{ p.title}} {{ p.article_author.name.get_full_name }} {{ p.posted_on}} -
How to unittest a ValidationError and assert the correct code is used?
I have a model with a ValidationError constraint: class MyModel(models.Model) title = models.CharField() def clean(self): error_dict = {} if self.title='invalid_title': error_dict['title'] = ValidationError( 'Title is invalid', code='invalid_title_code') if error_dict: raise ValidationError(error_dict) I want to unittest this ValidationError, but how do I test the code is correct? For example: def test_title_invalid(self): with self.assertRaises(ValidationError) as cm: MyModel.objects.create(title='invalid_title') exception = cm.exception # Test the key exists self.assertTrue(hasattr(exception, 'error_dict')) self.assertIn('title', exception.error_dict) # Test the message exists self.assertIn('Title is invalid', exception.messages) # Test the code exists self.assertIn('invalid_title_code', exception.code) This all works fine until self.assertIn('invalid_title_code', exception.code), which results in an AttributeError that states 'ValidationError' object has no attribute 'code' -
Grab username of User from model django
Not really sure if there is a duplicate question, probably is but I can't find it I've got this code here (models.py) # Create your models here. class UserProfileInfo(models.Model): # Create relationship (don't inherit from User!) user = models.OneToOneField(User, on_delete=models.CASCADE) # Add any additional attributes you want can_view_all = models.BooleanField(default=True) can_edit_all = models.BooleanField(default=False) can_add_admin = models.BooleanField(default=False) alias = models.CharField(default='none') @property def alias(self): return models.CharField(default=self.user.username) def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username @alias.setter def alias(self, value): self._alias = value As you can see, I'm trying to grab the username with the alias property, but it doesn't work, can someone help me, Basically, I'd like to be able to edit the boolean fields later on (I can do that) but I don't know which user I'm editing if there is a way to get the username directly via HTML injection that would be even better, but I just need a way to show which user I'm editing By the way, it isn't always the same user I'm signed in as, so I can't just use user Thank you -
psycopg2 gives error while installing in macOS Catalina 10.15.5
**I'm trying to install psycopg2 in my django project. it's gives me this error. I already install (psycopg2 binary, pillow & other packages these are working fine). I just reinstalled my macOS & Xcode. I'm using python 3.8.3 & Django 3.0.5 and Homebrew 2.4.5 and my PostgreSQL 12.3 ** Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-install-zr_qlm_k/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-install-zr_qlm_k/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-record-rc16k7t9/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/psycopg2 ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-install-zr_qlm_k/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-install-zr_qlm_k/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/hj/q_49d8351l11gj135qs6c01r0000gn/T/pip-record-rc16k7t9/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/psycopg2 Check the logs for full command output. -
Form is giving validation error in django template
I have a modelform. When I submit data pressing submit button, datas are not saving. I checked whether my forms are valid or not. I found that EducationForm is not valid. It has some error. Printing education_form error, I found this errors. <ul class="errorlist"><li>institution_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>degree<ul class="errorlist"><li>This field is required.</li></ul></li><li>passing_year<ul class="errorlist"><li>This field is required.</li></ul></li><li>result<ul class="errorlist"><li>This field is required.</li></ul></li></ul> I checked everything but I can not find any error. models.py: class Education(models.Model): """ Stores employee education background """ employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True) institution_name = models.CharField(max_length=128, null=True) degree = models.CharField(max_length=128, null=True) passing_year = models.DateField(null=True) result = models.DecimalField(max_digits=5, decimal_places=2, null=True) forms.py: class EducationForm(forms.ModelForm): """ Creates a form for saving educational info of an employee """ class Meta: model = Education fields = [ 'institution_name', 'degree', 'passing_year', 'result', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) views.py: class EmployeeAddView(LoginRequiredMixin,CreateView): """ Creates new employee """ login_url = '/authentication/login/' template_name = 'employee/employee_add_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm education_form_class = EducationForm queryset = Employee.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) # Override default get method def get(self, request, *args, **kwargs): form = self.form_class() work_form = self.work_form_class() education_form = self.education_form_class() return render(request, self.template_name, { 'form': form, 'work_form': work_form, 'education_form': education_form } ) # Override … -
How to get slug field in foreignkey HyperLink in django rest using HyperlinkedIdentityField?
I was trying the HyperlinkedIdentityField field in Django. I was getting output as follo { "id": 1, "product_type": "http://127.0.0.1:8000/products/producttype_list/P1/", "title": "Do non officia labore sapiente ab", "description": "Dignissimos aute ius", "upc": "Autem reiciendis quia magnam culpa enim", "slug": "P1", }, { "id": 2, "product_type": "http://127.0.0.1:8000/products/producttype_list/p2/", "title": "Exercitation", "description": "Ut consectetur volu", "upc": "Blanditiis et cupidatat delectus beatae qui quos inventore", "slug": "p2", } where product_type is FK.but slug link is of the current Product table.that's why it gives an error. I need to use the slug fields of the product_type table in that hyperlink. How to change the slug field in that hyperlink. serializer.py class ProductSerializer(serializers.ModelSerializer): product_type = serializers.HyperlinkedIdentityField(view_name='producttype-detail',lookup_field='slug') class Meta: model=Product fields='__all__' -
Calling function from other app into main app
I am trying to get navigation bar to work across all apps. But i am not able to call the function from there. this is my base.html. <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Main CSS file --> {% load static %} <link rel="stylesheet" href="{% static 'main/main.css' %}"> {% block style %} {% endblock %} <title>{% block title %} {% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Chili Pili</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item btn-login"> <a href="{url 'login.view.login'}" class="btn btn-primary">Login</a> </li> </ul> </div> </nav> <div class="main"> {% block content %} {% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> I am trying to call login function which goes to login page in login app on main page url. Also login is gonna work cross app. I am not able to call the …