Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery/redi infinite loading
Thanks in advance, i'm trying to get a litlle bit familliar with celery bit I can't solve my problem, it's been 4 hours i'm trying to figure what's wrong but I can't tell. Everything was working fine this morning but now i'm facing an infinite loading while submitting a form. first of all I'm on arch and using last version of each package, here's my code and messages i get from the terminal : configuration : demo/settings/base.py : INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'books', 'django_celery_results',] CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = f'redis://{config("REDIS_HOST")}:{config("REDIS_PORT")}/{config("REDIS_CELERY_DB")}' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_celery__.sqlite3'), } } .env : REDIS_HOST=localhost REDIS_PORT=6379 REDIS_CELERY_DB=0 my models books/models : from django.db import models from PIL import Image from django import forms from demo import tasks def resize_model(booquin): img = Image.open(bouquin.cover.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(bouquin.cover.path) bouquin.save() class Bouquin(models.Model): titre = models.CharField(max_length=200) cover = models.ImageField(upload_to="cover") def __str__(self): return self.title class Bouquin_Form(forms.ModelForm): def save(self, commit=True): book = super().save(commit) tasks.resize_book_celery.apply_async((book.id,)) return book class Meta: model = Bouquin fields = ["titre", "cover"] my demo/tasks.py ( I'm mixing up models andf forms in the same file cause … -
Slack printing raw JSON in message response from Django using JsonResponse
I am using Django 3.0 and python 3.6 to create a slack app that has a slash command. I am able to receive the request from slack in my app, but upon returning a Django JsonResponse object (https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects) slack just responds with the entire raw JSON in the message like the following: {"response_type": "in_channel", "blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": "Hello World!"}}]} Here is my Python code: def parse_command(self, text, **kwargs): response_json = { 'response_type': 'in_channel', 'blocks': [ { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': 'Hello World!' } } ] } response = JsonResponse(response_json, content_type="application/json; charset=utf-8", status=200) return response ... @slack_command('/test') def command_endpoint(text, **kwargs): command_handler_object = CommandHandler() return command_handler_object.parse_command(text, **kwargs) I am following the slack documentation here: https://api.slack.com/interactivity/slash-commands The documentation is pretty clear that in order to send a JSON response back to slack the Content-Type must be application/json I know the Django JsonResponse object sends a default header 'Content-Type': 'application/json', but that was not working and I read somewhere that charset needed to be specified as well. Using JsonResponse without specifying the content_type argument did not work either. I hit the endpoint with a curl command locally and was able to verify the content header was set … -
DJango REST Framework - Can't filter params from url
I am working on an android application with django as backend and I cant figure it how to filter params from url I want to get the 'page' parameter which is in this case '1' Kotlin Call @POST("item") fun getFoodItem(@Body map: HashMap<String, String>,@Query("page")strPageNo:String):Call<RestResponse<FoodItemResponseModel>> Urls.py path('api/category', Category.as_view()), path('api/item', Item.as_view()), Here's my django log [20/Jul/2020 23:01:19] "POST /api/item?page=1 HTTP/1.1" 200 3 -
inlineformset_factory Saves only Last Row data?
parent model data saved but formset data stored only last row information. Could not find the problem.Here i give all the related code .Could not find the problem. i am using jquery.formset.js. Here is my model: I create the inlineformset_factory using two models Meal & UserMeal. class Meal(models.Model): mess = models.ForeignKey( Mess, on_delete=models.CASCADE, related_name='mess_meals') active = models.BooleanField(default=True) meal_date = models.DateField(default=datetime.date.today) class UserMeal(models.Model): meal = models.ForeignKey( Meal, on_delete=models.CASCADE, related_name='meals') user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='user_meals') morning = models.FloatField( validators=[MinValueValidator(0.0)], default=0.0) noon = models.FloatField(validators=[MinValueValidator(0.0)], default=0.0) night = models.FloatField(validators=[MinValueValidator(0.0)], default=0.0) Here is My forms.py: class PreviousMealForm(ModelForm): class Meta: model = Meal exclude = ('mess',) widgets = { 'meal_date': DateInput(), } def clean_meal_date(self): meal_date = self.cleaned_data.get('meal_date') check_meal = Meal.objects.filter( mess=self.mess_obj, meal_date=meal_date).first() if check_meal: raise forms.ValidationError( f"Meal Was Created For {meal_date}") return meal_date def __init__(self, *args, **kwargs): self.mess_obj = kwargs.pop('mess_obj', None) super(PreviousMealForm, self).__init__(*args, **kwargs) class AddPreviousUserMealForm(ModelForm): class Meta: model = UserMeal fields = '__all__' def __init__(self, *args, **kwargs): self.mess_member = kwargs.pop('mess_member', None) super(AddPreviousUserMealForm, self).__init__(*args, **kwargs) self.fields['user'] = forms.ModelChoiceField( queryset=get_user_model().objects.filter(id__in=self.mess_member)) AddPreviousUserMealFormSet = inlineformset_factory( Meal, UserMeal, form=AddPreviousUserMealForm, extra=0, min_num=1, validate_min=True) Here is My Views.py class AddPreviousMealView(AictiveManagerRequiredMixin, CheckUserHasMessRequiredMixin, generic.CreateView): model = Meal form_class = PreviousMealForm template_name = 'manager/meal/add_previous_meal.html' success_message = "Meal Added SuccessFully" def get_mess_obj(self): mess_id = self.kwargs.get('mess_id') … -
How to dinamically inject HTML code in Django
In a project of mine I need to create an online encyclopedia. In order to do so, I need to create a page for each entry file, which are all written in Markdown, so I have to covert it to HTML before sending them to the website. I didn't want to use external libraries for this so I wrote my own python code that receives a Markdown file and returns a list with all the lines already formatted in HTML. The problem now is that I don't know how to inject this code to the template I have in Django, when I pass the list to it they are just printed like normal text. I know I could make my function write to an .html file but I don't think it's a great solution thinking about scalability. Is there a way to dynamically inject HTML in Django? Is there a "better" approach to my problem? -
Saving dynamic form checkbox input after submission or refresh
I need help saving the state of these checkboxes after i submit the form, and or after a page refresh. How can I do that? We cannot use normal jquery because the form inputs are dynamically created based on our DB. Any suggestions are appreciated. Code: <h6 id="filterheader">Brand:</h6> {% for s in sites %} <div class="form-check ml-4"> <input class="form-check-input" type="checkbox" value="{{s}}" id="checkBox" name='site_name'> <label id="filterlabel" class="form-check-label" for="defaultCheck1"> {{s}} </label> </div> {% endfor %} <h6 id="filterheader">Type:</h6> {% for p in prodtypes %} <div class="form-check ml-4"> <input class="form-check-input" type="checkbox" value="{{p}}" id="checkBox" name='prod_type'> <label id="filterlabel" class="form-check-label" for="defaultCheck1"> {{p}} </label> {% endfor %} Filter -
Filter current date between date ranges of django model
I want to get the equivalent of the following query in django ORM SELECT * FROM period WHERE '2020-07-06' BETWEEN star_date AND end_date; The Model: class Period(models.Model): start_date = models.DateField() end_date = models.DateField() The attempt: date = datetime.date.today() Period.objects.filter(date__range=[start_date, end_date]) but it does not work, What did I do wrong? -
dictionary update sequence element #0 has length 4; 2 is required while customize queryset in django form
i want edit queryset on manytomany based on loggedin user def add_view(self, request, form_url='', extra_context=None): # Do some extra queries that will get passed to the template # form = BeneficiaryForm(user=request.user) form = BeneficiaryForm(request.user) super(BeneficiaryAdmin, self).add_view(request, extra_context=form) this is form class BeneficiaryForm(forms.ModelForm): all_project = Project.objects.all() project = forms.ModelMultipleChoiceField(queryset=all_project) class Meta: model = Beneficiary fields = '__all__' def __init__(self, user, *args, **kwargs): super(BeneficiaryForm, self).__init__(*args, **kwargs) if self.request is not None: self.fields['project'].queryset = Project.objects.filter(Q(program=self.request) | Q(program='same-data')) -
Cannot insert explicit value for identity column in table 'Employee2' when IDENTITY_INSERT is set to OFF. (544) (SQLExecDirectW)")
****ERROR:('23000', "[23000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot insert explicit value for identity column in table 'Employee2' when IDENTITY_INSERT is set to OFF. (544) (SQLExecDirectW)") Hi,I am new to django. I am using MSSQL for my database The snapshot has the database table structure from django.db import models from django.urls import reverse # Create your models here. class Employee2(models.Model): Employeeid = models.CharField(max_length=200, primary_key=True) FirstName = models.CharField(max_length=100) LastName = models.CharField(max_length=100) SSN = models.IntegerField() Email = models.CharField(max_length=100) class Meta: db_table = 'Employee2' def __str__(self): return self.FirstName def get_absolute_url(self): return reverse('Employee_detail', kwargs={'pk': self.pk}) and i have my views.py as from django.views.generic import ListView, DetailView ,UpdateView, CreateView from .forms import * class EmployeeCreate(CreateView): model = Employee2 fields = ['FirstName', 'LastName', 'SSN', 'Email'] when i try to create a record it throws me an error shown above in the title.Is there any way i can prevent the passing of Employeeid column from the models.py? Is the error showing because the Employeeid from the models.py is also being passed while using the createView that inturn is trying to be inserted into Employeeid of my mssql table Employee2?Could anyone please help? -
IntegrityError at /create/ NOT NULL constraint failed: main_post.author_id
When i try to create an new post with http://localhost:8000/create/ , i get this error. I couldn't find the solution thought they seem similar. I follows some blog tutorial I can't paste the settings.py here because there to much code in the post but i think the settings.py is fine btw My models.py (* i deleted some code maynot involve) User = get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() detail = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField(config_name='post_ckeditor') comment_count = models.IntegerField(default=0) view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True) My views.py def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None pass def post_create(request): form = PostForm(request.POST or None, request.FILES or None) author= get_author(request.user) if request.method == 'POST': if form.is_valid(): form.instance.author = author form.save() return redirect(reverse('post-detail', kwargs={ 'id': form.instance.id })) context = { 'form': form } return render(request, 'post_create.html', context) pass My forms.py from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): … -
how do I fix (dictionary update sequence element #0 has length 211; 2 is required) error?
I need when someone registers a new account to add errors if there any. now, I tried to raise an error by ValidationError the first time seems to me it has triggered but when I closed the IDE and opened it again it shows me the next error: Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 211; 2 is required I have no idea what happened exactly? and why that error appears while it didn't appear before I close the IDE? views.py # User registration class Register(CreateView): template_name = 'account/register.html' form_class = SignUp success_url = reverse_lazy('account:login') forms.py # UserCreationForm class SignUp(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'email'] def clean_username(self): data = self.cleaned_data['username'] if User.objects.filter(username=data).exists(): raise ValidationError('username is already exists') return data def clean_email(self): data = self.cleaned_data['email'] if User.objects.filter(email=data).exists(): raise ValidationError('email is already exists') return data register.html <form method="post"> {% csrf_token %} <div class="form-group"> <div class="right-inner-addon"> {% for field in form %} {% if form.errors %} {% for error in field.errors %} <div class="text-danger"> <strong>{{ error }}</strong> </div> {% endfor %} {% endif %} {{ field }} {% endfor %} </div> … -
Like button Django3 - KeyError at /nutriscore/exemple-1/ 'pk'
I hope you're well. I'm beginner with Python and I'm trying to implement a like button in blog post like this. In admin part I can see who is clicking on the like. But I encounter two issues: first one: when I click on the like button, the "return" redirect me with this kind of url nutriscore/4/ or my article uses a slug (like that /nutriscore/exemple-1/. Do you have any idea? seconde one: when I want to display the number of like {{ total_likes }} I have this issue: KeyError at /nutriscore/exemple-1/ 'pk' Models.py: class Post(models.Model): ... likes = models.ManyToManyField(User, related_name='nutriscore_posts') def total_likes(self): return self.likes.count() Views.py: def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) class PostDetail(generic.DetailView): model = Post context_object_name = 'post' template_name = 'post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes context['total_likes'] = total_likes return context urls.py path('like/<int:pk>', LikeView, name="like_post"), post_detail.html <form action="{% url 'like_post' post.pk %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form> Thanks a lot :) -
Structuring React app and assigning user to django model through API
I am struggling with assigning users with react frontend through API to backend model so that authenticated users can register themselves in my event application. Despite my structure (i suppose my app is correctly structured) I can't really get my user somehow and there is something wrong in the backend part. I think the error is in views.py. Here I add parts of my source code (i try to be short but I also wanna know if there are some errors in my overall structure).: 1).Django models to include user as attendee, models.py: class Post(models.Model): def add_user_to_list_of_attendees(self, user, pk): registration = EventRegistration.objects.create(user=user, event=self, time_registered=timezone.now()) registration.save() def remove_user_from_list_of_attendees(self, user, pk): registration = EventRegistration.objects.get(user=user, event=self) registration.delete() class EventRegistration(models.Model): event = models.ForeignKey(Post, verbose_name='Event', on_delete=models.CASCADE) user = models.ForeignKey(User, verbose_name='Attendee', on_delete=models.CASCADE) time_registered = models.DateTimeField(null=True, default=timezone.now) def __str__(self): return self.user.username + ' registration to ' + self.event.title class Meta: verbose_name = 'Attendee for event' verbose_name_plural = 'Attendees for events' ordering = ['time_registered', ] constraints = [ models.UniqueConstraint(fields=['event', 'user'], name='user_to_training') ] def save(self, *args, **kwargs): if self.user is None and self.time_registered is None: self.time_registered = datetime.datetime.now() super(EventRegistration, self).save(*args, **kwargs) 2).Views under API, views.py: from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.models import User from django.shortcuts import render, redirect from … -
Query to check dates, disregarding the year in Django
I am looking for an efficient way to filter by date field, without taking the year into consideration. A simplified use case would be checking whether someone's birthday is in the next two weeks. given the model: class Profile(models.Model): birthdate = models.DateField() if I were to do the following, it would only find users that were born this year. today = datetime.datetime.now() two_weeks_time = datetime.timedelta(days=14) Profile.objects.filter(birthdate__gte=today, birthdate__lt=two_weeks_time) Is there some way of doing this in the query (also taking someone born on the 29th of February into consideration) or am I going to have to deal with that logic outside of the query? -
Partial credentials found in explicit, missing: aws_secret_access_key
I am trying to run my Django Application on heroku. Whenever I am running heroku run to run my website. I am getting this error. PartialCredentialsError at / Partial credentials found in explicit, missing: aws_secret_access_key Request Method: GET Request URL: https://ashaydjangoblog.herokuapp.com/ Django Version: 2.2.13 Exception Type: PartialCredentialsError Exception Value: Partial credentials found in explicit, missing: aws_secret_access_key Exception Location: /app/.heroku/python/lib/python3.6/site-packages/botocore/session.py in create_client, line 821 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.11 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Mon, 20 Jul 2020 15:39:48 +0000 can anyone HELP???? -
Django: home page url configuration not working after deployment to lightsail
Everything works just fine on my local server and when http://127.0.0.1:8000/ is clicked it gets me to the home page as expected but when the app is deployed to lightsail every public-ip/ redirects to the build in django success page while every other url combination works fine. project url: path('',include("mainpage.urls")), mainpage url: urlpatterns = [ path('', views.index, name= "index"), ] -
Navigation bar not appearing when using bootstrap CDN for Django
I'm following a tutorial to make websites with Django. I'm currently trying to add a navigation bar using bootstrap CDN but the following appears. The code I am using is posted below. There is no navigation bar present Code 1 Code 2 -
How to integrate oauth2 to django properly
I've been trying to understand oauth authentication system for days and make a proper login-logout system. I've following django-oauth-toolkit tutorial(https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-1-minimal-setup) and in the tutorial it says I should register an app after logged in on http://localhost/admin page. What is that app I am registering? Tutorial doesn't say anything about login logout so from my understanding I won't write any code about oauth at login api view and it doesn't seem right to me. -
'WSGIRequest' object has no attribute 'get' when i tried to pass data to form
am trying to pass request to modelform to edit some fields def add_view(self, request, form_url='', extra_context=None): # Do some extra queries that will get passed to the template form = BeneficiaryForm(request) super(BeneficiaryAdmin, self).add_view(request, extra_context=form) form am trying to edit class BeneficiaryForm(forms.ModelForm): all_project = Project.objects.all() project = forms.ModelMultipleChoiceField(queryset=all_project) class Meta: model = Beneficiary fields = '__all__' def __init__(self, *args, **kwargs): request = kwargs.get('request', None) super(BeneficiaryForm, self).__init__(*args, **kwargs) if request: self.fields['project'].queryset = Project.objects.filter(Q(program=request) | Q(program='same-data')) -
Django - Foreign Key Is Not Working Porperly
So basically my template has three columns in one form where they work separately. If I give input for contact column and male column it will save in my database. But the problem is that foreign key is not working.Whenever I include foreign key variable in my fields (forms.py).Form will not submit my inputs in database but when I remove it from fields though it wont show the contact related just none value. Like this.. Help please: Here is my model: class Contact(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) age = models.IntegerField() number = models.IntegerField() type = models.CharField(max_length=50) gender = models.CharField(max_length=10) order_date = models.DateField(blank=True,null=True) issue_date = models.DateField(blank=True,null=True) def __str__(self): return self.name class Male(models.Model): contact1 = models.ForeignKey(Contact, on_delete=models.CASCADE,null=True) chest = models.CharField(max_length=30 , blank=True) neck = models.CharField(max_length=30 , blank=True) full_shoulder_width = models.CharField(max_length=30 , blank=True) right_sleeve = models.CharField(max_length=30 , blank=True) left_sleeve = models.CharField(max_length=30 , blank=True) bicep = models.CharField(max_length=30 , blank=True) def __str__(self): return self.chest class Female(models.Model): contact2 = models.ForeignKey(Contact, on_delete=models.CASCADE, null=True) fchest = models.CharField(max_length=30 , blank=True) fneck = models.CharField(max_length=30 , blank=True) fwaist = models.CharField(max_length=30 , blank=True) seat = models.CharField(max_length=30 , blank=True) shoulder_width = models.CharField(max_length=30 , blank=True) arm_length = models.CharField(max_length=30 , blank=True) Views.py def add(request): template_name = 'add.html' f_form = '' c_form = '' … -
Taking action after registering new user in Django
I want take some action right after creating a new User using UserCreationForm. In this situation i need to create a new instance of Model which is in one-to-one relationship with this new User. Please tell me how can i connect my code which will create this Model instance to the UserCreations form or to the register view. I know that there is a save method in UserCreationForm which finally creates new User, but i do not know how to connect it to my code -
Media Files With React And Django on Heroku
I am trying to deploy a simple app on Heroku using djangorestfarmework and react(react-create-app). Everything seems to work fine except uploaded images. And I am having a hard time trying to figure out the correct path of to show these images. #models.py profile_img = models.ImageField(upload_to='media', default="default-images/default-profile-img.png", blank=True, null=True) header_img = models.ImageField(upload_to='media', default="default-images/default-header-img.png", blank=True, null=True) #settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'build', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now when I try to img src theses images in my react component I always fail. So in src/components/MyComponent i tried to use require to get the path of the image, which is ../../media/media/5.jpg but I get Cann't find module ../../media/media/5.png error. Then tried to use the url myheroku-app.herokuapp.com/media/medai/5.png but it didn't work. My files structure is somethings like this: backend settings media default-images media src components MyComponent.js images logo.png' (and when yarn build) build static css js media logo.png I tried to add build/static/media as MEDIA_ROOT but it didn't work. So my question is what paths should I use to upload and make these images show on Heroku? And I am sorry if this is like a stupid question but I can't figure out … -
matching query does not exist for updateview in django
I have a custom user model from AbstractBaseUser and BaseUserManager. The user model is extended to a model called Employee. The employee model is related with(Foreignkey) two other model named WorkExperience and education. models.py: class Employee(models.Model): """ Create employee attributes """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) e_id = models.IntegerField(unique=True, null=True) first_name = models.CharField(max_length=128, null=True) last_name = models.CharField(max_length=128, null=True) gender_choices = ( ('Male', 'Male'), ('Female', 'Female'), ) ...... @receiver(post_save, sender=UserProfile) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Employee.objects.create(employee_user=instance, email=instance.email) instance.employee.save() class WorkExperience(models.Model): """ Stores employee previous work experiences """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True) previous_company_name = models.CharField(max_length=128, null=True) job_designation = models.CharField(max_length=128, null=True) from_date = models.DateField(null=True) to_date = models.DateField(null=True) job_description = models.CharField(max_length=256, null=True) class Education(models.Model): """ Stores employee education background """ employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) 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.IntegerField(null=True) result = models.DecimalField(max_digits=5, decimal_places=2, null=True) I have a CreateView of this three models. I have three modelform. I implemented CRUD using this modelforms. My problem is in UpdateView. When I call UpdateView an error is showing stating WorkExperience matching query does not exist. views.py: class EmployeeUpdateView(LoginRequiredMixin, UpdateView): """ Update a created a employee … -
Returning the token expirty in rest_framework_jwt
I’m using rest_framework_jwt for authentication. I use my custom payload handler to return user with token also. def my_jwt_response_info(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data } but I also need to have the generated token expirty how can I return it back? -
Control Footer info via admin page - Python Django
Django newbie here so apologies if this is a dumb question. I am trying to create way to control the footer information via Admin page. Such as facebook, twitter links I have created a Footer model in models.py and migrated it and it is visible in the admin page. However when I add the footer information to the html into an a href it is not bing visible. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}! You may now login!') return redirect('login') else: form = UserRegisterForm() context = { "footer": Footer.objects.all(), 'form': form } return render(request, 'member/register.html', context) <a href={{ footer.register.facebook }} class="pl-0 pr-3"><span class="icon-facebook"></span> </a> <a href="#"class="pl-3 pr-3"><span class="icon-twitter"></span>{{ footer.twitter }}</a> <a href="#" class="pl-3 pr-3"><span class="icon-instagram"></span>{{ footer.instagam }}</a> <a href="#" class="pl-3 pr-3"><span class="icon-linkedin"></span></a> Thanks all, Onur