Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin site failed to load static files (CSS/JS) while Nginx is hosting static files
Django version 2.2 Python 3.6.9 Ubuntu 18.04.4 Django admin site failed to load static files (CSS/JS) while Nginx is hosting static files In development, I put static files in my_project/static/ and in production I did python manage.py collectstatic. All static files are collected in /srv/my_site_static/ The folder /srv/my_site_static/admin contains 4 folders js,img,fonts,css for django admin site. I used Nginx to host static files. My written apps loads static files correctly with my nginx settings below. The only problem is my http://my_site.com/admin couldn't load css/js. Django settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', # for blog, articles, html pages 'ckeditor_uploader', # for blog, articles, html pages 'user_blog', 'product_info', # product info page ] STATIC_URL = 'static/' MEDIA_URL = 'media/' # Use these in production mode STATIC_ROOT = '/srv/my_site_static/' MEDIA_ROOT = '/srv/my_site_media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] My nginx settings: server { listen 9000; # nginx public server server_name 127.0.0.1; location /static/ { autoindex on; alias /srv/my_site_static/; # Set this to your STATIC_ROOT } location /media/ { autoindex on; alias /srv/my_site_media/; # Set this to your MEDIA_ROOT } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; # the django server } } … -
How do I add link to an element with JavaScript?
So instead of directly using tag in each element, is there a way to add the tag dynamically?What I'm trying to do is that first I have a calendar, and when a user clicks a particular date on the calendar, the user can see what happened in that date at a separate page. The thing is that I'm using django-scheduler library, so the calendar is pre-desiged, meaning I cannot directly make changes to the code. All I have in my template is {% calendar %}. So I figured I'd have to control using JavaScript. Here's what I see in the 'source' of the page: ... <div class="content" data-date="2020-05-27"></div> <div class="content" data-date="2020-05-28"></div> <div class="content" data-date="2020-05-29"></div> ... For each data-date, I want to add link which looks like : www.some-webpage.com/2020-05-27 Is it ever possible to do this with JavaScript? Thanks in advance. :) -
Logging not writing logging messages to log file but printing on console
I am trying to learn logging module in Django. I want to write exceptions to the log file so that I can see them later. Printing log messages on console is working fine but I am unable to write the same log messages to the log file. Below is my code. My settings.py LOGGING = { 'version': 1, 'loggers': { 'django':{ 'handlers': ['file'] , 'level':'INFO' } }, 'handlers':{ 'file':{ 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', } } } My views.py def Helloworld(request): try: s = HttpResponse("this is life") logging.debug("this is debug log - in hw page") logging.critical("this is critical log - in hw page") logging.error("this is error log - in hw page") except Exception as e: print(e) logging.critical("this is critical log - in hw page - exception") logging.exception(e) return s My console output Django version 3.0.6, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. CRITICAL:root:this is critical log - in hw page ERROR:root:this is error log - in hw page INFO:django.server:"GET /hw HTTP/1.1" 200 12 My output of log file Watching for file changes with StatReloader "GET /hw HTTP/1.1" 200 12 C:\Users\....\views.py changed, reloading. Watching for file changes with StatReloader Watching for file changes with … -
How to fetch Django models objects/queryset as dictionary in case of multiple levels of relationship?
I have 3 models: class Country(models.Model): country_id = models.AutoField(primary_key=True) country_name = models.CharField(max_length=50) population = models.BigIntegerField() class State(models.Model): state_id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=50) country = models.ForeignKey(Country, on_delete=models.CASCADE) population = models.BigIntegerField() class District(models.Model): state_id = models.AutoField(primary_key=True) district_name = models.CharField(max_length=50) state = models.ForeignKey(State, on_delete=models.CASCADE) population = models.BigIntegerField() Now given a country_id, I want to fetch all the related State and District in following format: { 'country':{ 'country_id': 1, 'coutry_population': 120000, 'state':[ { 'state_id': 10, 'state_name': 'A', 'state_population': 10000, 'district':[ { 'district_id': 100, 'district_name': 'District1', 'district_population': 4000 }, { 'district_id': 101, 'district_name': 'District2', 'district_population': 6000 }] }, { <2nd state data here> } ] } } Also I should be able select particular columns from each of the model. For Eg: Only state_name from State Model, district_name and district_population from District Model, etc I also need the feature of filtering, at different models. For eg: Only get districts matching condition district.population > 5000 None of the question I could find here helped to solve the problem. Closest one seemed to be this : Django: Most efficient way to create a nested dictionary from querying related models? But here the relationship is in opposite direction. One solution I could think of was to query … -
form_valid of createview not getting called
I am trying to add multiple records in the Asset model using inline formset and createview. I am new to inline formsets and i doubt if i am doing it right. I am unable to save the form as the form_valid method is not getting called. Here is my code models class Person(models.Model): name = models.CharField(max_length=20,verbose_name='Name') class Asset(models.Model): related_to = models.ForeignKey(Person, on_delete=models.CASCADE, verbose_name='Person') description = models.CharField(max_length=20,verbose_name='Description') pfile = models.FileField(verbose_name='File') forms class assetUploadform(forms.ModelForm): class Meta: model = Asset fields = ('description','pfile',) assetFormSet = inlineformset_factory(Person,Asset,form = assetUploadform,fields=['description','pfile'], extra=2) views class assetPerson(generic.CreateView): model = Asset form_class = assetUploadform template_name = 'myprjct/TEST.html' success_url = reverse_lazy('myprjct:list') def get_context_data(self, **kwargs): data = super(assetPerson, self).get_context_data(**kwargs) if self.request.POST: data['asset'] = assetFormSet(self.request.POST, self.request.FILES) else: data['asset'] = assetFormSet() return data def form_valid(self, form): context = self.get_context_data() asset = context['asset'] with transaction.atomic(): #form.instance.related_to = Person.objects.get(pk=self.kwargs['pk']) self.object = form.save() if asset.is_valid(): asset.instance = self.object asset.save() return super(assetPerson, self).form_valid(form) template {% extends 'index.html' %} {% block content %} <div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{asset.management_form }} {% for fo in asset.forms %} {% for field in fo %} {{field.label}} : {{field}} {% endfor %} <br><hr> {% endfor %} <button type="submit"> submit </button> </form> </div> {% endblock %} Please help me out … -
How do you apply the filters from a dict which contains both string and list values in django?
I have dict - filters like this: "filter1": "string", "filter2": [ "A","B" ], "filter3": "string", "filter4": [ "C","D" ], } where filter1,filter2,filter3 filter4 are some fields in my model. This query_set = query_set.filter(**filters) works fine for all the filters whose type is not list, But I want to filter the query_set as cleanly as possible, How do you apply the filters using a dict which contains both string and list values? PS: I know about __in & know I can do something like if filter2_list: query_set = query_set.filter(filter2__in=filter2_list) ``` BUT, 1. I don't want to use if-else statements 2. I want to have dynamic variables in the filters arguments and not hardcore ones like filter2__in -
The view accounts.views.activation_view didn't return an HttpResponse object. It returned None instead
I am trying to create a view that handles the email confirmation but i keep on getting an error, your help is highly appreciated My views.py import re from django.contrib.auth import login, logout, authenticate from django.shortcuts import render, HttpResponseRedirect, Http404 # Create your views here. from .forms import LoginForm, RegistrationForm from . models import EmailConfirmation SHA1_RE = re.compile('^[a-f0-9]{40}s') def activation_view(request, activation_key): if SHA1_RE.search(activation_key): print('activation is real') try: instance = EmailConfirmation.objects.get(activation_key=activation_key) except EmailConfirmation.DoesNotExist: instance = None raise Http404 if instance is not None and not instance.confirmed: print('Confirmation complete') instance.confirmed = True instance.save() elif instance is not None and instance.confirmed: print('User already confirmed') else: pass context = {} return render(request, "accounts/activation_complete.html", context) else: pass urls.py from django.urls import path from .views import( logout_view, login_view, register_view, activation_view, ) urlpatterns = [ path('accounts/logout/', logout_view, name='auth_logout'), path('accounts/login/', login_view, name='auth_login'), path('accounts/register/', register_view, name='auth_register'), path('accounts/activate/<activation_key>/', activation_view, name='activation_view'), ] models.py class EmailConfirmation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) activation_key = models.CharField(max_length=200) confirmed = models.BooleanField(default=False) def __str__(self): return str(self.confirmed) def activate_user_email(self): #send email here activation_url = 'http://localhost:8000/accounts/activate%s' %(self.activation_key) context = { 'activation_key': self.activation_key, 'activation_url': activation_url, 'user': self.user.username } message = render_to_string('accounts/activation/actiavtion_message.txt', context) subject = 'Email actiavtion key' print(message) self.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) def email_user(self, subject, message, from_email=None, **kwargs): send_mail(subject, message, from_email, [self.user.email], … -
KeyError after combine queryset for form field
I have a form field that lists the queries from two models using the itertools.chain method. However, I am getting a KeyError which I believe is due to a conflict in PK from both models. How do I set my form queryset such that the selected option returns value of another column in the model. class TransactionForm(ModelForm): class Meta: model = Transaction exclude = ['notes'] def __init__(self, user, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) agent_players = user.agent_players.all() deals = user.club_deals.all() self.fields['sender'].queryset = chain(agent_players, deals) -
Gettinfg Cannot assign must be a instance. error on assigning the models variable
I am unable to store the value. this line datafile.project = 41 gives me : Cannot assign "41": "Data.project" must be a "Project" instance. How to solve this issue? models.py: class Project(models.Model): name = models.TextField() description = models.TextField(blank=True) creator = models.ForeignKey('Profile', on_delete=models.CASCADE) percentage_irr = models.FloatField(default=10.0, validators=[ MinValueValidator(0.0), MaxValueValidator(100.0)]) num_users_irr = models.IntegerField(default=2, validators=[MinValueValidator(2)]) codebook_file = models.TextField(default='') batch_size = models.IntegerField(default=30) ''' Advanced options ''' # the current options are 'random', 'least confident', 'entropy', and 'margin sampling' ACTIVE_L_CHOICES = [ ("least confident", "By Uncertainty using Least Confident"), ("margin sampling", "By Uncertainty using the Margin"), ("entropy", "By Uncertainty using Entropy"), ("random", "Randomly (No Active Learning)") ] CLASSIFIER_CHOICES = [ ("logistic regression", "Logistic Regression (default)"), ("svm", "Support Vector Machine (warning: slower for large datasets)"), ("random forest", "Random Forest"), ("gnb", "Gaussian Naive Bayes") ] learning_method = models.CharField( max_length=15, default='least confident', choices=ACTIVE_L_CHOICES) classifier = models.CharField( max_length=19, default="logistic regression", choices=CLASSIFIER_CHOICES, null=True) def get_absolute_url(self): return reverse('projects:project_detail', kwargs={'pk': self.pk}) #<--- Terminate Here def get_current_training_set(self): try: return self.trainingset_set.all().order_by('-set_number')[0] except IndexError: return None def admin_count(self): return self.projectpermissions_set.all().filter(permission='ADMIN').count() def coder_count(self): return self.projectpermissions_set.all().filter(permission='CODER').count() def labeled_data_count(self): return self.data_set.all().filter(datalabel__isnull=False).count() def has_model(self): if self.model_set.count() > 0: return True else: return False class ProjectPermissions(models.Model): class Meta: unique_together = (('profile', 'project')) PERM_CHOICES = ( ('ADMIN', 'Admin'), ('CODER', 'Coder'), ) … -
trans And Translate Not Working On Any Pages
Im copying Django Templates straight from Git and pasting them into overridden templates in my project (so there are no syntax errors), but I get this error message on every page that uses translate or trans: Invalid block tag on line 38: 'translate', expected 'endblock'. Did you forget to register or load this tag? My settings file is unchanged from when I began the project and as I said, im copying the code straight from the git repository. Im guessing the problem is in my settings.py file. Ive Googled and tried everything i can find but cant seem to find the problem. Can anybody please help shed some light on what the issue might be? Thank you. -
Django access to model Properties Dynamically
I'm very new to Django so this question might be very basic. I have a model called UserScores, which contains 16 different score properties, each representing a user score based on the game he/she has played. when a user plays a game and finish it, the score he gets in that game should be added to the related property in his/her UserScores object. so the code looks like this: if game_name == "game1": self.game1_score += score elif game_name == "game2": self.game2_score += score ... in php I used to run a code like this: obj.{game_name} += score so no matter what the game name was, the correct property was edited, Now my question is that, Is there a dynamic way to access properties on a Django model objects? -
django-rest-framework getting followers using related_name of ManyToManyField
So I am creating follower system but there is a problem. Everything is working properly. but in follower serializer I want the username's and other details of users. models.py class Follow(models.Model): user = models.OneToOneField(User,related_name="user" ,on_delete=models.CASCADE) ''' to obtain user ' eeee = User.objects.first() , eeee.user' ''' following = models.ManyToManyField(User,related_name='following_user',blank=True) ''' to obtain followers ' eeee.following_user.all()' ''' ''' to obtain following ' eeee.user.following.all()' ''' def __str__(self): return self.user.username In field following , user.following.all() is used to get the user in manytomany field of request.user and following_user.all() is used get all the users who has added request.user in their following field. serializers.py class FollowerSerializer(ModelSerializer): user = UserSerializer(many=False) follower = SerializerMethodField() class Meta: model = Follow fields = ('user','follower') def get_follower(self, obj): context = self.context request = context.get("request") return request.user.following_user.all().values() Here I am serializing all the user who has added request.user in their following field views.py class FollowerView(RetrieveAPIView): queryset = Follow.objects.all() serializer_class = FollowerSerializer permission_classes = [IsAuthenticated] lookup_field = 'id' api { "user": { "name": "eeee" }, "is_follower": [ { "id": 2, "user_id": 9 }, { "id": 5, "user_id": 16 }, { "id": 3, "user_id": 10 } ] } These is the api I am getting of all the user who has added … -
Dependent dropdown does not return the ID of a foreign key selected
I'm trying to create a form to setup a quiz. I've made an ajax call to display course contents (topics) corresponding to a course selected. However, I'm unable to filter the contents model based on the course id, as it returns none while making a get request. Course and Content model in content/models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. class Course(models.Model): grade=models.CharField(max_length=100) subject=models.CharField(max_length=100) class Meta: verbose_name = 'Course' verbose_name_plural = 'Add/View Courses' def __str__(self): return '{} - {}'.format(self.grade, self.subject) class Content(models.Model): course=models.ForeignKey(Course, on_delete=models.CASCADE) title=models.CharField(max_length=100) video = models.FileField(upload_to='content', blank=False) date=models.DateTimeField(default=datetime.now, blank=True) class Meta: verbose_name = 'Content' verbose_name_plural = 'Upload/View Course Contents' def get_absolute_url(self): return "/content/%i" % self.id def __str__(self): return '{} / {} / {}'.format(self.title, self.course.grade, self.course.subject) I have created a model form to display the quiz form (quiz/forms.py) P.S - The quiz model used here takes course, content(labelled as topic) and another model called category(labelled as difficulty) as foreign keys respectively. from django import forms from .models import Category, Quiz from content.models import Content, Course from django.contrib.auth.models import User class QuizForm(forms.ModelForm): class Meta: model = Quiz fields= ('course', 'topic', 'difficulty') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['topic'].queryset = Content.objects.none() … -
Creating a form with four fields
Good day! I'm trying to create a form with four fields, like in the screenshot. I'm not getting anywhere yet. Now I use this form in template: <form> <form id="FirstForm" action="{% url one.views.FirstForm %}" method="POST"> {% csrf_token %} {{ form1 }} </form> <form id="SecondForm" action="{% url one.views.SecondForm %}" method="POST"> {% csrf_token %} {{ form2 }} </form> <div> <input type="submit" name="subform1" value="Отправить" class="form_button"> </div> </form> And here is the code in views.py: def FirstForm(request): if request.method == 'GET': form = FirstForm() return render(request, 'home.html', {'form':form}) else: form = FirstForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] try: send_mail(name, email, settings.EMAIL_HOST_USER, ['daribian@list.ru']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'home.html', {'form': form}) def SecondForm(request): if request.method == 'GET': form = SecondForm() else: form = SecondForm(request.POST) if form.is_valid(): date = form.cleaned_data['date'] number = form.cleaned_data['number'] try: send_mail(date, number, settings.EMAIL_HOST_USER, ['daribian@list.ru']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'home.html', {'form': form}) def successView(request): return HttpResponse('Success!') As well as the forms themselves: class FirstForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name_class'}), max_length=100, required=True) email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email_class'}), required=True) class SecondForm(forms.Form): date = forms.CharField(widget=forms.TextInput(attrs={'class' : 'my_name_class'}), max_length=100, required=True) number = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'my_email_class'}), required=True) I keep getting various errors and I … -
How to make Django scan all directories including those that are not in static files directory to search media files
I'm trying to build a local video streaming application with Django as its backend. I'm not looking to host the application online, its always going to remain in localhost. Now the problem I'm facing is Django only detects video files that are inside static files directory. But I can't have all my videos under static files directory and so not all files can be inside static files directory(preferably I don't want any video files to be inside it). Sorry if I'm dumb but how do I make Django to scan my whole system for media files (or preferably only the directories I provide to it) without putting video files inside static directory? If its not possible, then how should I build such application? And also I noticed that the video tag from HTML can't play x265 .mkv videos by default, is there a way to make them play it or should I settle with other formats like .mp4 alone? -
Django-Filter over Managers
I've been stuck in this for several weeks now and I believe the answer is super simple but somehow I can't find it anywhere online. Which makes me think I'm going about it totally wrong. All I want to do is be able to filter my stats such as the get_largest_winning_trade function based on the django-filter package. Where am I going wrong? As a side note get_largest_winning_trade is showing the largest winning trade in the Trade Model but it is not being filtered for my criteria. Such as "user". managers.py from django.db import models class TradeQuerySet(models.QuerySet): def get_users_trades(self, username): return self.filter(user__username=username) class TradeManager(models.Manager): def get_queryset(self): return TradeQuerySet(self.model, using=self._db) def get_users_trades(self, username): return self.get_queryset().get_users_trades(username) def get_largest_winning_trade(self): return max([t.profit_loss_value_fees for t in self.all()]) views.py class StatsView1(LoginRequiredMixin, ListView): model = Trade template_name = 'dashboard/stats1.html' def get_context_data(self, **kwargs): filter = StatsFilter1(self.request.GET, queryset=self.get_queryset()) context = super().get_context_data(**kwargs) context['filter'] = filter context['get_largest_winning_trade'] = Trade.objects.get_largest_winning_trade return context stats.html (testing) filter.qs.get_largest_winning_trade: {{ filter.qs.get_largest_winning_trade }} <br> Trade.get_largest_winning_trade: {{ Trade.get_largest_winning_trade }} <br> trade.get_largest_winning_trade: {{ trade.get_largest_winning_trade }} <br> get_largest_winning_trade: {{ get_largest_winning_trade }} <br> # works but not with filter -
context not rendering im the html page - django
So the view is : def username(request): context = {} if request.POST: pass else: context['title'] = 'type a username' return render(request, 'update/one-input.html', context) then in the html page : <h5>{{ title }}</h5> when i run the page its give me no error and its not showing any think inside the heading i do the same code in another view in page and its work , why in this view not working so what is the problem ? ): -
Django dynamic model permission using request method
I am working in a company which uses machines and molds to produce industrial parts. During the production process machines can malfunction so we created a frontend and backend for workers to register those error records. Recently engineers and managers from another departments joined to this system so I needed to make sure who can do what in other word managing permissions. Relevant model: class FaultRecord(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) fault = models.ForeignKey(Fault, on_delete=models.PROTECT) machine = models.ForeignKey(Machine, on_delete=models.PROTECT) mold = models.ForeignKey(Mold, on_delete=models.PROTECT) part = models.ForeignKey(Part, on_delete=models.PROTECT) material = models.ForeignKey(Material, on_delete=models.PROTECT) responsible_departments = models.ManyToManyField(Department) status = models.ForeignKey(FaultRecordStatus, on_delete=models.SET_NULL, null=True) reason = models.TextField() temporary_action = models.TextField() permanent_action = models.TextField(null=True) duration = models.PositiveSmallIntegerField() occured_at = models.DateTimeField() created_at = models.DateTimeField() updated_at = models.DateTimeField(null=True) Relevant view: class FaultRecordViewSet(ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated, ModelPermission] serializer_class = FaultRecordSerializer queryset = FaultRecord.objects.prefetch_related( 'user', 'fault', 'machine', 'mold', 'part', 'material', 'responsible_departments', 'status' ).all().order_by('occured_at') model = FaultRecord As we know Django creates 4 default permission for models which are view, add, change and delete. Based on this I wanted to check user permissions by request method so I don't have to write permission class for every model. Also I don't want to use has_object_permission because I check post permission … -
Change language of Django built in Templates
I'm using the PasswordResetConfirmView like this: path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view( template_name='auth/reset_password/confirm.html', success_url='/password-reset-complete/' ), name='password_reset_confirm'), Is there a way to change the text of the labels to show them in another language? -
ACCESS_TOKEN_EXPIRE_SECONDS not updating access token expiry date
I'm using the django-oauth-toolkit to generate access tokens, however for some reason my access tokens have been set to expire in 3600s when I try to update the ACCESS_TOKEN_EXPIRE_SECONDS setting, my access tokens are still set to expire after 3600s. Below is how I'm updating my settings any help will be much appreciated thank you. OAUTH2_PROVIDER = { 'OAUTH2_VALIDATOR_CLASS': 'openedx.core.djangoapps.oauth_dispatch.dot_overrides.validators.EdxOAuth2Validator', # 3 months and then we expire refresh tokens using edx_clear_expired_tokens (length is mobile app driven) 'REFRESH_TOKEN_EXPIRE_SECONDS': 7776000, 'SCOPES_BACKEND_CLASS': 'openedx.core.djangoapps.oauth_dispatch.scopes.ApplicationModelScopes', 'SCOPES': dict(OAUTH2_DEFAULT_SCOPES, **{ 'grades:read': _('Retrieve your grades for your enrolled courses'), 'certificates:read': _('Retrieve your course certificates'), }), 'DEFAULT_SCOPES': OAUTH2_DEFAULT_SCOPES, 'REQUEST_APPROVAL_PROMPT': 'auto_even_if_expired', 'ERROR_RESPONSE_WITH_SCOPES': True, 'ACCESS_TOKEN_EXPIRE_SECONDS': 86400, } -
null value in column "id" violates not-null constraint
I am trying to save a model that has some ForeignKey fields as well as some m2m fields. def company(request): if request.method == 'POST': form = CompanyForm(request.POST) if form.is_valid(): company = form.save(commit=False) company.user = request.user company.save() form.save_m2m() return redirect(request.path) else: form = CompanyForm() although on line 6 of the above code I assign user to the object it gives the error in the title. -
Collected user information is not saved in database using django framework
when I try to add details using this form it is not updating to my database. please help me to solve this issue. There is no error but the database is not updated. club.html {% extends "base.html" %} {% block content %} {%ifequal request.user.Isclubmember True%} <div class='container'> </div> {%else%} <div class="container"> <form action="." method="POST"> {%csrf_token%} Profile Pic: <input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage> Phonenumber: <input name="userphonenumber" type="number" placeholder="+91 9876543210" > <input type="submit" value="submit" class="btn btn-success"> </form> </div> {%endifequal%} {% endblock content %} views.py from django.conf import settings from django.contrib import messages from django.shortcuts import redirect from django.contrib.auth.models import User from .models import UserProfile, Clubmember from django.contrib.auth.models import User from django.contrib.auth import login from django.http import HttpResponseRedirect def club(request): if request.method == 'POST': if request.user.is_authenticated: Clubmember.user = request.user Clubmember.phone_number = request.POST.get('userphonenumber') Clubmember.userphoto = request.FILES.get('image') request.user.Isclubmember = True request.user.save() Clubmember.save() return redirect(request,'core:home') else: return redirect(request,'login_url') else: return render(request,'core:club') models.py class Clubmember(models.Model): user = models.ForeignKey(UserProfile,default=1, on_delete=models.CASCADE) userphoto = models.ImageField(upload_to="userphotos/%Y/%m",default=False) phone_number = models.IntegerField(default=False) usermoney = models.FloatField(default=0.0) -
To query using Django ORM
I have below Sql Query which pulls expired tests. cursor.execute('''select auth_user.username, auth_user.email, tests_test.title, tests_seller.company_name, tests_test.bid_date from tests_test LEFT JOIN tests_seller ON tests_seller.id = tests_test.seller_id LEFT JOIN auth_user ON auth_user.id = tests_seller.user_id where tests_test.bid_date - CURRENT_DATE < 0 ''') The above SQL query works fine as expected. But I want to convert the above query for Django ORM. So, could you help me on how to query using Django ORM. Thanks in advance. Below are the import statements for models, I planned to use with Django ORM for above sql query django.contrib.auth.models import User from tests.models import Test, Seller import datetime -
in django how to get lookup_url_kwarg in serilaizer
this my Django view class CreateForeignTableView(CreateAPIView): """ create foreign_table finally not difference a normal table ?? """ serializer_class = CreateForiegnTableSerializer queryset = None lookup_url_kwarg = 'foreign_server_id' I want get lookup_url_kwarg in my create serializer function -
AWS EB: Unresolved resource dependencies
My Django app is deployed and working thanks to this fantastic article: https://medium.com/@justaboutcloud/how-to-deploy-a-django3-application-on-elastic-beanstalk-python3-7-and-amazon-linux-2-bd9b8447b55 I'm to the end of the project and am setting up HTTPS. To do that, I've created a config file in my .ebextensions folder called 02_https.config In this file, I copy and pasted the code from the article: option_settings: aws:elbv2:listener:443: SSLCertificateArns: <YourACMCertificateARN> Protocol: HTTPS Resources: AWSEBV2LoadBalancerListener: Type: 'AWS::ElasticLoadBalancingV2::Listener' Properties: LoadBalancerArn: { "Ref" : "AWSEBV2LoadBalancer" } DefaultActions: - RedirectConfig: Port: 443 Protocol: HTTPS StatusCode: HTTP_301 Type: redirect Port: 80 Protocol: HTTP When I deploy the app, I get this error message: Service:AmazonCloudFormation, Message:Template format error: Unresolved resource dependencies [AWSEBV2LoadBalancer] in the Resources block of the template I have two theories: I'm not pasting the ARN Certificate in the correct format, which is throwing off my YAML formatting There is something wrong about this code's formatting. Could someone please provide some input?