Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku upload error at=error code=H10 desc="App crashed" method=GET path="/"
i have recently deployed my code to heroku but it faild and the log files are : 2020-12-08T14:59:41.000000+00:00 app[api]: Build succeeded 2020-12-08T14:59:45.566897+00:00 heroku[web.1]: Starting process with command `: gunicorn kharazmi.wsgi` 2020-12-08T14:59:48.222964+00:00 heroku[web.1]: Process exited with status 0 2020-12-08T14:59:48.272732+00:00 heroku[web.1]: State changed from starting to crashed 2020-12-08T15:00:21.395810+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kharazmiiot.herokuapp.com request_id=029f7f14-297b-494e-bde5-7a79d6cb9315 fwd="89.39.107.146" dyno= connect= service= status=503 bytes= protocol=https 2020-12-08T15:11:18.231945+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kharazmiiot.herokuapp.com request_id=514a879b-12df-43b4-b82a-7cbb40217959 fwd="89.39.107.146" dyno= connect= service= status=503 bytes= protocol=https any solution ? -
Django error with the html links TypeError at / 'set' object is not reversible
Im learning Django right now , and i have start the html integrations so i have put all static pages into one app, everything was working , so i have 3 page Home/ SignUp/ Login , and im tryin to link all pages with others so this is what i did urls.py from django.urls import path from . import views urlpatterns =[ path('', views.index , name='index'), path('SignUp', views.SignUp , name='signup'), path('login', views.login, name='login'), ] html code <div class="container"> <div class="nav-header"> <a href="#" class="js-fh5co-nav-toggle fh5co-nav-toggle"><i></i></a> <h1 id="fh5co-logo"><a href="{% url 'index' %}">My Personal Trainer<span> App</span></a></h1> <!-- START #fh5co-menu-wrap --> <nav id="fh5co-menu-wrap" role="navigation"> <ul class="sf-menu" id="fh5co-primary-menu"> <li class="active"> <a href="{% url 'index' %}">Home</a> </li> <!-- <li><a href="trainer.html">About Us</a></li> --> <li><a href="{% url 'login' %}">Login</a></li> <li><a href="{% url 'signup' %}">Sign Up</a></li> </ul> </nav> </div> </div> views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('base/index.html') return HttpResponse(template.render(request=request)) def login(request): template= loader.get_template('base/login.html') return HttpResponse(template.render(request=request)) def SignUp(request): template= loader.get_template('base/signup.html') return HttpResponse(template.render(request=request)) IM GETTING this error when i try to access one of those pages: TypeError at / 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: TypeError Exception Value: 'set' object … -
django abstract base class with ManyToMany
class Question(models.Model): answer_choices = models.ManyToManyField(Answers) class Meta: abstract = True class HTMLQuestion(Question): question = models.fields.TextField() class TextQuestion(Question): question = models.fields.TextField() class Quiz(models.Model): questions = models.ManyToManyField(Question) The last line doesn't work. I can't run python manage.py makemigrations without the error "Field defines a relation with model 'Question', which is either not installed, or is abstract." Is there a way to have a list of Question subclassed instances without having it be of type "Question"? I want to have both types HTMLQuestion and TextQuestions to be in the Quiz. -
Async view with serializer Django 3.1
I'm trying to create an async view to solve an endpoint with Django 3.1. I have my AsyncView and within this view I have the next code lines : try: db_result= await sync_to_async(list)(Plan.objects.filter()) serializer = MySerializer(db_results, many=True) return serializer.data except Exception: # Handle Exception Code Within my serializer I have a custom field. Its data is retrieved doing other queries to the Database using its obj property. This is where I am having some problems since this is an async context. Serializer Code: MySerializer(serializers.ModelSerializer): custom_field = serializers.SerializerMethodField(required=False) def get_custom_field(self, obj): try: # This is failing, is not retrieving data from DB since it's async context related_stuff = obj.related_stuff.filter(filter_condition=filter_condition) # More code after this . . . . return custom_field_object except Exception: return None I've tried to put an await before the Serializer in my View Code and add async property to get_custom_field method (with the sync_to_async operator in the db query). Got nothing. Anyone know how to solve this specific problem? -
How to make nested serializers represent data in given way?
models: class Category(models.Model): name = models.CharField(max_length=80) created_at = models.DateTimeField(auto_now_add = True, null = True) created_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="created_by") updated_at = models.DateTimeField(auto_now = True, null = True) updated_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="updated_by") deleted_at = models.DateTimeField(null = True) deleted_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name='deleted_by') class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): category = models.ManyToManyField(Category, blank=False) name = models.CharField(max_length=100) description = models.TextField(max_length=250) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add = True, null = True) created_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="products_created_by") updated_at = models.DateTimeField(auto_now = True, null = True) updated_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name="products_updated_by") deleted_at = models.DateTimeField(null = True) deleted_by = models.ForeignKey(User, default = None, blank=True, null=True, on_delete=models.DO_NOTHING, related_name='products_deleted_by') class Meta: ordering = ("name", ) def __str__(self): return self.name serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ("id", "name", "created_at", "created_by", "updated_at", "updated_by", "deleted_at", "deleted_by",) class ProductSerializer(serializers.ModelSerializer): # category = serializers.PrimaryKeyRelatedField(many=True, read_only=True, source="category") category = CategorySerializer(many=True) created_by = serializers.StringRelatedField() updated_by = serializers.StringRelatedField() deleted_by = serializers.StringRelatedField() class Meta: model = Product fields = ( "id", "name", "category", "description", "price", "quantity", "created_at", "created_by", … -
Django DRF - How to force validating CSRF token on GET requests (generics.ListAPIView)
I would like to force Django to check and validate GET requests using CSRF token which comes from frontend AJAX. Now this view accepts GET request and returns objects even if token isn't passed. # views.py class CPUDetail(mixins.RetrieveModelMixin, generics.GenericAPIView): queryset = CPU.objects.all() serializer_class = CPUSerializer def post(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) # index.js $.ajax({ url: '/api/cpu/2/', type: 'POST', mode: 'same-origin', success: function (data) { console.log('success'); console.log(data); } }) I tried use from django.views.decorators.csrf.requires_csrf_token decorator but it went in errors. -
editing .env files from front end django
I am using python decouple to store the secret keys in .env files as follows STRIPE_PUBLIC_KEY = 'pk_test_51Hk2oFpiiCn94MIdRGFuRL0UeK003HdDUOGI' STRIPE_SECRET_KEY = 'sk_test_51Hk2oFL6Sy5bEid8yzJdxt5Eu700EKbjQTYu' STRIPE_WEBHOOK_SECRET = 'whsec_C0vOEGcAUCZYpf9' and call in settings file as below STRIPE_PUBLIC_KEY = config('STRIPE_PUBLIC_KEY') STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY') STRIPE_WEBHOOK_SECRET = config('STRIPE_WEBHOOK_SECRET') now the question is how it the strings in .env file can be replaced from front end, this is for future edit without the help of developers. -
Video converter with python Issue
I am creating video converter using django. I came across this module (https://travis-ci.org/senko/python-video-converter.png?branch=master)](https://travis-ci.org/senko/python-video-converter) and I have used it in my program. My problem is i want the script to run forever and I also have a function that checks for new videos added so that the conversion can be done automatically. The code is not working as i expected. I have been going searching for hours but can't find any solution. The program needs to take a user input that's the destination of the video, the new location to put the converted video the format that the video is in and the new format the video should be converted to. I tried with only the script and is working but implementing it in django is the problem. below is my converter code #!/usr/bin/python import sys import os import shutil import time import subprocess from converters import Converter import hot.db_time as db #this are the variables to use src_dir = db.src dst_dir = db.dst #this is the main program def mains(): ext_one = db.from_ ext_two = db.to ex_1 = '.'+ext_one ex_2 = '.'+ext_two subprocess.check_call(watch_dog(ex_1,ex_2,src_dir)) #this is the part converter c = Converter() options = { 'format': 'mkv', 'audio': { 'codec': 'mp3', … -
use case for form without model
I'm learning django and have begun working with forms and models. It makes sense that you can have a model to be used to display data without having to use a form and it certainly makes sense to have a form linked to a model. What's the use case for just having a form? -
What are drawbacks of having fat models in Django?
I've read some good things about the fat model approach. But wouldn't there be other issues? -
how to connect sql server in django and do the CRUD operations?
everyone I am searching for a couple of tutorials and followed the documentation of the Django how to connect SQL server in Django I got some basic idea, But I want it in a broader way so can anyone suggest some nice tutorial or give me any kind of example please. before coming to here I have searched and completed a lot of articles about this topic and I found most of the articles are either old or they are going for postgress thank you in advance. -
Calculate time difference (Subtract the time range 10PM to 9AM) between two datetime fields using django annotate?
I have to calculate the time difference between to DateTime fields, also keeping in mind to subtract the time frame 10 PM-9 AM for each transaction if it lies in. The following code snippet saves the duration between those two fields but I'm unable to subtract the time frame 10 PM-9 AM from that duration for further use. from django.db.models import ExpressionWrapper, DurationField MyModel.objects.annotate( diff=ExpressionWrapper(F('field1') - F('field2'), output_field=DurationField()) ) Can anyone help me to solve this? -
how to django file upload in request.body
I think the front end will deliver to me like this. { chapters : [ { name : name1, image : file lectures : [ lecture1, lecture2, lecture3 ] },{ name : name2, image : file lectures : [ lecture1, lecture2 ] } ] } Is it possible to be delivered like this? If this is the case, I have no idea how to use request.FILES. -
(Django) Authentication + __init__ argument issue
For today I have a question about INIT error which I'm getting while accessing my webpage. I use @login_required decorator to lock access for not authenticated users to my schedule calendar. While authentication works properly I cannot view my website because of error at the end of this question. VIEWS.PY @login_required(login_url='login') class CalendarView(generic.ListView): model = Event template_name = 'cal/calendarpage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context URLS.PY urlpatterns = [ path('calendarpage/', views.CalendarView, name='calendarpage'), re_path('event/new/$', views.event, name='event_new'), re_path('event/edit/(?P<event_id>\d+)/$', views.event, name='event_edit'), ] If I add .as_view() to my url and remove authentication there is no issue to visit webpage but then there is no authentication which is not desired. TypeError at /calendarpage/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost:8000/calendarpage/ Django Version: 3.1.2 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: C:\Users\kacnowik\Desktop\Python\VENV\lib\site-packages\django\contrib\auth\decorators.py, line 21, in _wrapped_view Python Executable: C:\Users\kacnowik\Desktop\Python\VENV\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\kacnowik\\Desktop\\Python\\Amazonian', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\\python38.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\kacnowik\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0', 'C:\\Users\\kacnowik\\Desktop\\Python\\VENV', 'C:\\Users\\kacnowik\\Desktop\\Python\\VENV\\lib\\site-packages'] Server time: Tue, 08 Dec 2020 15:08:43 +0100 Could … -
Django migration error while trying to migrate
I created an app two days ago, added some models, and migrated successfully. And since, I haven't added or changed anything but I added something today and tried to migrate, after making migrations and tried to migrate, I got this error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, students, user_upload Running migrations: Applying user_upload.0002_users_upload_phone_number...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self._remake_table(model, create_field=field) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table self.effective_default(create_field) File "C:\Users\aser\AppData\Roaming\Python\Python38\site-packages\django\db\backends\base\schema.py", line 303, in effective_default return … -
Two dataframe merge with same data in 'choices.text' row and 'Survey_Question_Answer '
my first data frame is df_chart_data_table=SurveyResponseDetails.objects.values('Survey_Question_Answer','Survey_Question_No').order_by('Survey_Question_No').filter(Survey_Id='1H2711202014572742').annotate(Survey_Question_Answer_count=Count('Survey_Question_Answer')) data = list(df_chart_data_table.values_list('Survey_Question_Answer_count', flat=True)) tableanswer=pd.DataFrame(df_chart_data_table) totalanswer = tableanswer.to_html() my second dataframe [jsondata=SurveyMaster.objects.all().filter(survey_id='1H2711202014572742') passvalue = jsondata.values('survey_json_design') qs_json = pd.DataFrame(passvalue) json_normalize = pd.json_normalize(qs_json\['survey_json_design'\], record_path=\['pages','elements'\]) table_normalize=flat_table.normalize(json_normalize, expand_dicts=False, expand_lists=True) drop_table=table_normalize.drop(\['choices.value','isRequired'\], axis = 1) drop_table.rename(columns = {'title':'Survey_Question_Desc'}, inplace = True) final_table= drop_table.to_html() As you can see 1st image is my 1st dataframe 2nd image is my 2nd data frame and 3rd is which i have tried to using concat() but you can see choices.tex is different from Survey_question_answer so i want same data as choices.text.. please help me, this code i was done but still not working concate = pd.concat([tableanswer, table_normalize], axis=1, sort=False) frame=pd.DataFrame(concate) drop_table=frame.drop(['choices.value','isRequired','index','name','type'], axis = 1) drop_table = frame[['index','Survey_Question_No', 'title','choices.text','Survey_Question_Answer','Survey_Question_Answer_count']] #drop_table.rename(columns = {'title':'Survey_Question_Desc'}, inplace = True) table=drop_table.to_html() -
Submit Django HTML form with Ajax
This is my first time trying to submit a form with Ajax. Here's my code: index.html (where the form is declared): form method="post" role="form" class="email-form" id="contact_me"> {% csrf_token %} <div class="form-row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" required /> </div> <div class="col-md-6 form-group"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" required /> </div> </div> <div class="form-group"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required /> </div> <div class="form-group"> <textarea class="form-control" name="message" rows="5" placeholder="Message" required /></textarea> </div> <div class="mb-3" id="thankyou"> </div> <div class="text-center"><button type="submit">Send Message</button></div> </form> There is a is reserved to display the message after the form is submitted. views.py: def send_message(request): if request.is_ajax(): sender_name = request.POST.get('name') sender_email = request.POST.get('email') message_subject = request.POST.get('subject') message_text = request.POST.get('message') html_message = render_to_string('contact_template.html', {'sender_name': sender_name, 'sender_email': sender_email, 'message_subject': message_subject, 'message_text': message_text}) email_subject = 'Message from website visitor' email_from = 'me@mygmail.com' email_to = ['me@mydomain.com'] send_mail(email_subject, '', email_from, email_to, html_message=html_message) response = { 'thankyou': 'Your message has been sent. Thank you!' } return JsonResponse(response) urls.py: path('sendmessage', views.send_message, name='send_message'), And the Ajax script (index.html): <script> $('#contact_me').submit(function(e){ e.preventDefault() $.ajax({ type : "POST" url : "/sendmessage/" data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : '{{ csrf_token }} datatype … -
Django admin reverse foregin key relationship
I have a number of different models connected to the User model through a foregin key relationship. I would now like to display all the attributes from the objects connected to the User model in the main admin overview. models.py class User(AbstractBaseUser): username = models.CharField(max_length=60) lastname = models.CharField(max_length=60, blank=True) class UserProfile(models.Model): user_id = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) address = models.CharField(max_length=60, blank=True) admin.py class UserProfileAdmin(admin.ModelAdmin): list_display = ('user_firstname', 'user_lastname', 'address') def user_firstname(self, instance): return instance.user_id.username def user_lastname(self, instance): return instance.user_id.lastname admin.site.register(UserProfile, UserProfileAdmin) The code above works perfectly well to display attributes from "User" in "Userprofile", but how do I do this the other way around? In my code I currently have 4 different objects connected to the User object so keen to find a way to display all the data there. -
Change username in django rest framework
if i go to 'http://127.0.0.1:8000/myapi/changename/1/', and put {"username":"abc"}, then it response, {"response": "something went wrong"}. how to change the username of the user? everything is imported properly. i think my concept is not clear😖 here is my main code: in views.py: @api_view(['PUT']) @permission_classes((IsAuthenticated,)) def changeName(request,pk): user = User.objects.get(id=pk) serializer = UserSerializers(instance=user, data=request.data) if serializer.is_valid(): serializer.save() else: return Response({'response': 'something went wrong'}) return Response({'response': 'ok'}) in serializers.py: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__' in urls.py: from . import views urlpatterns = [ path('', views.home, name='home'), path('myapi/', views.apiView, name='apiView'), path('myapi/changename/<str:pk>/', views.changeName, name='changeName'), ]``` -
"AttributeError: Got AttributeError when attempting to get a value for field" when trying to serialize a relation in my view
I'm trying to only return the one treatment related to the patient that is currently making the call. I have the following models: models.py class User(AbstractUser): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) street_name = models.CharField(max_length=50, null=True) street_number = models.CharField(max_length=50, null=True) city = models.CharField(max_length=50, null=True) post_code = models.IntegerField(null=True) clinic = models.ForeignKey("Clinic", on_delete=models.SET_NULL, null=True) is_patient = models.BooleanField() is_physio = models.BooleanField() def __str__(self): return self.email class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) physio = models.ForeignKey("Physio", on_delete=models.SET_NULL, null=True) def __str__(self): return self.pk class Treatment(models.Model): physio = models.ForeignKey(Physio, on_delete=models.SET_NULL, null=True) patient = models.ForeignKey( Patient, on_delete=models.SET_NULL, null=True) clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL, null=True) is_active = models.BooleanField() treatment_notes = models.TextField() date_created = models.DateField(auto_now_add=True) def __str__(self): # TODO add Patient ID treatment_str = f"Patient ({self.objects.patient}) - {str(self.date_created)}" return treatment_str With the following serializer: serializers.py class UserSerializer(serializers.ModelSerializer): physio = serializers.PrimaryKeyRelatedField(read_only=True) patient = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'is_patient', 'is_physio', 'patient', 'physio') class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' class TreatmentSerializer(serializers.ModelSerializer): physio = serializers.PrimaryKeyRelatedField(read_only=True) patient = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = models.Treatment fields = '__all__' read_only_fields = ['date_created'] And I'm trying to make a call to the following view: views.py class TreatmentPatientRetrieveView(generics.RetrieveAPIView): serializer_class = TreatmentSerializer def get_object(self): patient = self.request.user.patient … -
Django Project : Custom Admin Templates are not getting loaded on an AWS ElasticBean server
I have developed a django project and am overriding the admin templates. The changes are working fine in localhost but when I pushed the project to aws elastic beanstalk (AWS EC2 Ubuntu) server the modified admin templates are not loading. Folder structure to project looks like: --Project-Folder --manage.py --templates --admin --app --model change_list.html --app --templates Settings.py Looks like TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ] }, }, ] change_list.html looks like: {% extends 'admin/change_list.html' %} {% load i18n admin_urls %} {% block extrastyle %} {{ block.super }} <style> .modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; /* Sit on top */ left: 0; top: 0; width: 50%; /* Full width */ height: 50%; /* Full height */ overflow: auto; /* Enable scroll if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */ } /* Modal Content/Box */ .modal-content { background-color: #fefefe; margin: 15% auto; /* 15% from the top and centered */ padding: 20px; border: 1px solid #888; width: 80%; /* Could be more or less, depending on screen … -
Search Two Django Tables once within singel query
I am really confusing about Django joins. I want to search a keyword in two tables with a single query. can anyone help me? the app model structure like this class Events(models.Model): event_type = models.CharField(_("Event Type"), max_length=5, choices=event_type_choices) webinar_title = models.CharField(_("Webinar Title"), max_length=50, blank=True, null=True) event_name = models.CharField(_("Event Name"), max_length=50, blank=True, null=True) banner_title = models.CharField(_("Banner Title"), max_length=50, blank=True, null=True) added_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) status = models.BooleanField(_("Event Status"), default=True) class Meta: verbose_name = _('Event') db_table = 'events' app_label = 'events' class WebinarSpeakers(models.Model): event = models.ForeignKey(Events, on_delete=models.CASCADE, null=True) speaker = models.CharField(_("Speaker Name"), max_length=100, null=True, blank=True) job_title = models.CharField(_("Job Title"), max_length=255) place_of_work = models.CharField(_("Place of Work"), max_length=100) credentials = models.TextField(_("Credentials"), null=True, blank=True) image = models.ImageField(_("Speaker Image"), upload_to=speaker_file_name, null=True, blank=True) class Meta: verbose_name = _('Event Webinar Speakers') db_table = 'webinar_speakers' app_label = 'events' Now I want to search a keyword in webinar_title, evetn_name, banner_title, speaker, 'job_title` with a single query. how to do it in Django joins. I read the select_related document. it confusing me. -
how to change default template auth login in django this is not working?
how to change default template auth login in django this is not working?? urlpatterns = [ path('',views.registration,name='registration'), path('login/',auth_views.LoginView.as_view(template_name='login.html'),), -
form is possibly unbound
enter image description here from django.shortcuts import render, HttpResponseRedirect # from django.contrib.auth.forms import UserCreationForm # from .forms import SignUpFrom from .forms import SignupFrom # Create your views here. def home(request): def user_login(request): return render(request, "enroll/templets/blog/login.html") def user_signup(request): # form = SignUpFrom() # form = UserCreationForm() if request.method == "POST": form = SignupFrom(request.POST or None) if form.is_valid(): form.save() else: form = SignupFrom() return render(request, "enroll/templets/blog/signup.html", {'form': form}) how to solve that when I import forms classes then I add validations to them than I got this error -
Ngnix & Django(Guicorn) & Docker - ssl not works
I'm have tryed some ways... but it not works I'm using Docker ssl certs exist on /etc/ssl ngnix.conf upstream hello_django { server web:8000; } server { listen 443 ssl; server_name phoenix-constructor.pw; ssl_certificate /etc/ssl/phoenix-constructor.crt; ssl_certificate_key /etc/ssl/phoenix-constructor.key; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/app/web/staticfiles/; } } Dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d COPY phoenix-constructor.crt /etc/ssl/ COPY phoenix-constructor.key /etc/ssl/ docker-compose.prod.yml https://pastebin.com/BM8BnNXL (can't past here) https://phoenix-constructor.pw/ -- not working http://phoenix-constructor.pw/ -- working (before new nginx.conf)