Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelForm has no model class specified. Django
I want to create a patient creating form for my system with Django but it is not working and I am getting an error: ValueError at /create/ ModelForm has no model class specified. I cannot understand that. I looked for similar question and I apply some solutions but it did not work. Where is my mistake? Can you help me? Thanks a lot for your attention. views.py def patient_create(request): if not request.user.is_authenticated: return Http404() form = PatientForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, "Başarılı bir şekilde oluşturdunuz.", extra_tags='mesaj-basarili') return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form } return render(request, "template/patient_form.html", context) models.py class newPatients(models.Model): title = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) dept = models.TextField() address = models.TextField() phone = models.CharField(max_length=15) notes = RichTextField(verbose_name="notes") def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_create_url(self): return reverse('post:create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while newPatients.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self.get_unique_slug() return super(newPatients, self).save(*args, **kwargs) class Meta: ordering = ['-created_date'] forms.py from django.forms import ModelForm from patients.models import newPatients … -
gunicorn failing to start supervisor: Django AWS EC2
I am watching this tutorial to deploy a django app on AWS EC2. https://www.youtube.com/watch?v=BzdYa9Lqlm4&list=PLDu5PyoUISmc1PdrUNUdc9LohmLA_Q-S5&index=2 For some reason I am unable to get the status of gunicorn to work properly. After creating an instance of EC2 on AWS. I have updated, upgraded everything, installed python, django, nginx,gunicorn and supervisor correctly. I created the folder and accessed it cd /etc/supervisor/conf.d/ Then I created the file sudo touch gunicorn.conf using NANO CONFIG file directory=/home/ubuntu/aws_demo command=/home/ubuntu/env/bin/gunicorn - - workers 3 - - bind unix:/home/ubuntu/aws_demo/app.sock aws_demo.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn steps after creating the config file sudo mkdir /var/log/gunicorn sudo supervisorctl reread start gunicorn: sudo supervisorctl update (add process group) check gunicorn status: sudo supervisorctl status at this point: terminal response guni:gunicorn FATAL Exited too quickly (process log may have details) The structure of my entire project look like this aws_demo (Main folder) aws_demo (projectname) core (application name) I am not sure whats wrong but I feel like app.sock is not created because I cannot find it anywhere when I look for it manually on Ubuntu. Any feedback would be much appreciated. -
How to set model field default the same as OneToOneField attribute value?
There are Lecture and Task models. Every lecture has a topic. And every task has a topic and a lecture. class Lecture(models.Model): topic = models.CharField(max_length=30, blank=False) class Task(models.Model): lecture = models.OneToOneField(Lecture, on_delete=models.CASCADE) topic = models.CharField( max_length=30, blank=False, ) I want to set Task.topic value the same as Lecture.topic this task refers to. For example: lecture1 = Lecture('Awesome topic') lecture1.save() task1 = Task(lecture1) task1.save() # here task1.topic must be 'Awesome topic' I've tried this thing: class Task(models.Model): lecture = models.OneToOneField(Lecture, on_delete=models.CASCADE) topic = models.CharField( max_length=30, blank=False, default=lecture.topic ) but have 'OneToOneField' object has no attribute 'topic' -
How to call a Model Method from an HTML form value
I have a simple HTML form for filtering/ordering the data on the page. This uses a GET request to the view which returns the data from the back-end in the manner which was requested. What I want to do is use a Model Method, instead of an attribute, as the form's input value. Current example which passes Model attribute as input value (current_score is a Model attribute): <input class="form-check-input" id="Radios4" name="ordering" type="radio" value="-current_score"> <label class="form-check-label" for="exampleRadios4">Scores: High-to-Low</label> The problem with this is that current_score returns the quantity of correct questions while I want the user's percentage score on the test. Which is calculated using this Model Method: @property def get_percent_correct(self): dividend = float(self.current_score) divisor = len(self._question_ids()) if divisor < 1: return 0 # prevent divide by zero error if dividend > divisor: return 100 correct = int(round((dividend / divisor) * 100)) if correct >= 1: return correct else: return 0 So my question is, how can I use the Model Method as the input value in the form? Such as: <input class="form-check-input" id="Radios4" name="ordering" type="radio" value="-get_percent_correct"> <label class="form-check-label" for="exampleRadios4">Scores: High-to-Low</label> -
Multiple Input Values For Model Form
I am creating profiles for users and I want them to be able to select multiple tags using forms.ModelMultipleChoiceField which will be saved to their profile. My models.py setup: class ProfileTags(models.Model): description = models.CharField(max_length=300) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True) services_offered = models.ManyToManyField(ProfileTags) Forms.py: class ProfileUpdateForm(forms.ModelForm): ProfileTags = forms.ModelMultipleChoiceField(queryset=ProfileTags.objects.all()) class Meta: model = Profile Views.py: def profile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST,request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'form': p_form } return render(request, 'users/profsettings.html', context) I load in the tags in the ProfileTags model and this seems to have worked and I'm able to allow users to submit the tags and it's saved in the DB successfully, however I am experiencing the following issues: instance=request.user.profile does not seem to work for the checkboxes. After submitting the form, if I go back to the form the boxes aren't checked. I want users to be able to remove tags from their profile by simply unchecking a previously checked box - this may be a template issue as I'm manually rendering the fields, however: It doesn't seem to be possible to delete the tags … -
exchange data between different templates django
I am new to django and on my course to learn django, i am facing a issue. MY CURRENT GOAL: Take input from homepage(say localhost:8000/) in my app and display result to other webpage say (localhost:8000/result/) WHAT I HAVE BEEN ABLE TO ACHIEVE: I was able to get input from homepage.html(localhost:8000/) using request.POST.get('widgetName') in views.py under the function which is rendering homepage.html. I want to pass the data to another function in same views.py which renders resultpage.html(localhost:8000/result/) Currently i am working with raw HTML and not usinf django forms. Thanks in advance. -
Django Rest Framework Elastic Search: RequestError 400 parsing_exception
When trying to query for event documents that match this condition, I'm getting a parsing exception and I'm not sure what's causing it. This is occurring in my custom get_queryset method. In my get_query in my document view set I'm getting an error. def get_queryset(self): qs = super().get_queryset() user = self.request.user if hasattr(user, 'userprofile'): user_universities = user.userprofile.universities.all().values_list("id") user_universities_campus = user.userprofile.universities.all().values_list("main_campus__id") query = query | Q('bool', must=[ Q('match', visibility_scope=Event.UNIVERSITY), Q('bool', must=[ Q('terms', university__id=list(user_universities)), Q('bool', should=[ Q('terms', university__main_campus__id=list(user_universities)), Q('terms', university__main_campus__id=list(user_universities_campus)) ]) ]) ]) qs = qs.query(query) return qs I'm getting this error: if self.count == 0 and not self.allow_empty_first_page: File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\django\core\paginator.py", line 91, in count return c() File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch_dsl\search.py", line 679, in count **self._params File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\utils.py", line 84, in _wrapped return func(*args, params=params, **kwargs) File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\client\__init__.py", line 529, in count "POST", _make_path(index, doc_type, "_count"), params=params, body=body File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\transport.py", line 358, in perform_request timeout=timeout, File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 261, in perform_request self._raise_error(response.status, raw_data) File "C:\Users\fendy\.virtualenvs\cul\lib\site-packages\elasticsearch\connection\base.py", line 182, in _raise_error status_code, error_message, additional_info elasticsearch.exceptions.RequestError: RequestError(400, 'parsing_exception', '[terms] unknown token [END_ARRAY] after [university.id]') -
ValueError: Related model 'wagtailimages.Image' cannot be resolved
I just started to attempt writing tests for a blog written based on Django and Wagtail CMS. When I run python manage.py test, this is the result that I get from the terminal. Creating test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/home/alvindera/.local/lib/python3.6/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/alvindera/.local/lib/python3.6/site-packages/django/test/runner.py", line 554, in setup_databases self.parallel, **kwargs File "/home/alvindera/.local/lib/python3.6/site-packages/django/test/utils.py", line 174, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/alvindera/.local/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 72, in create_test_db run_syncdb=True, File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/alvindera/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/alvindera/.local/lib/python3.6/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 "/home/alvindera/.local/lib/python3.6/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 "/home/alvindera/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state … -
Django loop in html issue
i had been trying to solve this problem for almost 3 hrs but i didnt get the result i want, this is the result i want this is my current result this is my html <tr> <th>Students Name</th> {% for student in teacherStudents %}<th >{{student.Date}}</th>{% endfor %} <th data-id='headers' id='headerave'>Average</th> </tr> <tr> <tbody id="scoreboard"> {% for students in studentname %} <tr class="tr2"> <td><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{students.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <tr> {% endfor %} </tr> <tr> {% for studentss in Students %} <td class="td" scope="row"><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{studentss.Grade}}</td>{% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td> </tr> this is my views.py teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Date') studentname = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).distinct('Students_Enrollment_Records') Students = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade) my models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True,blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True,blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True,blank=True) #Items = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True, blank=True) Grade = models.FloatField(null=True, blank=True) this is my data in admin.py … -
Django Rest Framework: Paginaion in detail view breaks when ordering by multiple fields
I have a Django app for contests where a contest can have multiple entries - Contest in models.py class Contest(models.Model): is_winners_announced = models.BooleanField(default=False) ... ContestEntry in models.py class ContestEntry(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='entries') submitted_at = models.DateTimeField(auto_now_add=True) assigned_rank = models.PositiveSmallIntegerField(null=True, blank=True) ... In the ContestViewSet, I have a detail route which serves all the entries for a contest - def pagination_type_by_field(PaginationClass, field): class CustomPaginationClass(PaginationClass): ordering = field return CustomPaginationClass ... @decorators.action( detail=True, methods=['GET'], ) def entries(self, request, pk=None): contest = self.get_object() entries = contest.entries.all() # Order by rank only if winners are announced ordering_array = ['-submitted_at'] if contest.is_winners_announced: ordering_array.insert(0, 'assigned_rank') pagination_obj = pagination_type_by_field( pagination.CursorPagination, ordering_array)() paginated_data = contest_serializers.ContestEntrySerializer( instance=pagination_obj.paginate_queryset(entries, request), many=True, context={'request': request}, ).data return pagination_obj.get_paginated_response(paginated_data) Pagination works fine when winners are not declared for a contest - GET http://localhost:8000/contests/<id>/entries/ { "next": "http://localhost:8000/contests/<id>/entries/?cursor=cD0yMDIwLTAyLTE3KzIwJTNBNDQlM0EwNy4yMDMyMTUlMkIwMCUzQTAw", "previous": null, "results": [ // Contains all objects and pagination works {...}, ... ] } But when the winners are announced, pagination breaks: GET http://localhost:8000/contests/<id>/entries/ { "next": "https://beta-api.hapramp.com/contests/4/entries/?cursor=bz03JnA9Mw%3D%3D", "previous": null, "results": [ // Contains all objects only for the first page; next page is empty even when there are more entries pending to be displayed {...}, ... ] } The strange thing I see here is that … -
Restrict all access to admin site unless
Let's say I have a model called "Settings". When someone first logs in to the project (I'm talking about a superuser logging in.) The first thing they should do is populate the Settings models before doing anything. So is there a way I can redirect their login to the Settings model on every login until there's an object or is there a way I can restrict all access or unregister all other models until they populate the settings model? Thanks, -
Django - CreateView not saving form with nested formset
I am trying to adapt an approach for saving nested formsets with main form using Django-Crispy-Forms layout feature but I can't save it. I am following this code example project but couldn't get formset validated to save data. I will be really thankful if someone can point out my mistake. Below is the code models: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employees', null=True, blank=True) about = models.TextField() street = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=200) cell_phone = models.PositiveIntegerField() landline = models.PositiveIntegerField() def __str__(self): return '{} {}'.format(self.id, self.user) def get_absolute_url(self): return reverse('bars:create', kwargs={'pk':self.pk}) class Education(models.Model): employee = models.ForeignKey('Employee', on_delete=models.CASCADE, related_name='education') course_title = models.CharField(max_length=100, null=True, blank=True) institute_name = models.CharField(max_length=200, null=True, blank=True) start_year = models.DateTimeField(null=True, blank=True) end_year = models.DateTimeField(null=True, blank=True) def __str__(self): return '{} {}'.format(self.employee, self.course_title) View: class EmployeeCreateView(CreateView): model = Employee template_name = 'bars/crt.html' form_class = EmployeeForm success_url = None def get_context_data(self, **kwargs): data = super(EmployeeCreateView, self).get_context_data(**kwargs) if self.request.POST: data['education'] = EducationFormset(self.request.POST) else: data['education'] = EducationFormset() print('This is context data {}'.format(data)) return data def form_valid(self, form): context = self.get_context_data() education = context['education'] print('This is Education {}'.format(education)) with transaction.atomic(): form.instance.employee.user = self.request.user self.object = form.save() if education.is_valid(): education.save(commit=False) education.instance = self.object education.save() return super(EmployeeCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('bars:detail', kwargs={'pk':self.object.pk}) Forms: class … -
application call . TypeError: view must be a callable or a list/tuple in the case of include()
I am taking a course where this error does not occur my error is cod is: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bo otstrap_inner self.run() File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\auto reload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\manag ement\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\manag ement\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\manag ement\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\check s\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\check s\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\check s\urls.py", line 23, in check_resolver return check_method() File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resol vers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\func tional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resol vers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\func tional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resol vers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\wuoel\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 12 7, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked … -
I want to display parts of the form according to the how the user selects the checkbox
How do i allow to display a particular form content after the user clicks on checkbox Yes or No for e.g.if the user clicks on yes checkbox display the form to be filled if user clicks No display another form part to be filled -
I need to update the database how can I do it?
I have been trying to create a to do list app and there has been no problems until when i was adding an edit button, when i press the edit button, it shows the edit page with the text that has to be edited but the submit button that is suposed to change the database is not working, I think I need to add something to the views.py file but I dont know what. viws.py def edit(request, id): created_items = Create.objects.get(id=id) return render(request, 'my_app/edit.html', {"created_items": created_items}) urls.py urlpatterns = [ path('edit/<int:id>/', views.edit, name='edit'), ] models.py class Create(models.Model): added_date = models.DateTimeField() text = models.CharField(max_length=200) edit.html {% extends 'index.html' %} {% block body %} <div align="center"> <h1>Edit your post!</h1> <div class="container form-group"> <h1>↓</h1> <form method="POST">{% csrf_token %} <textarea class="form-control" name="content" id="id" rows="3" style="text-align: center;">{{ created_items.text }}</textarea> <button type="submit" class="btn btn-outline-success" style="margin-top: 5px;">Submit</button> </form> </div> </div> {% endblock %} -
Adding additional fields based on user interaction to create a post
How can I add an additional field via a user click, So the end result I want is to have a create page with buttons saying add paragraph ,add image, add subtitle etc. Im using Python/Django along with Jquery. -
SMTP-Sendgrid Email in Django app: working locally, on Heroku error SMTPServerDisconnected
On the Heroku-deployed version of my app, when testing the password reset function, I get the error SMTPServerDisconnected at /accounts/password/reset/ please run connect() first, this reset functionality works perfectly fine on the local version of my app - I receive the mails from sendgrid without any problems and the app behaves as expected: my email settings are: EMAIL_HOST=smtp.sendgrid.net EMAIL_HOST_USER=apikey EMAIL_HOST_PASSWORD=***************************************** EMAIL_PORT=587 EMAIL_USE_TLS=True my production setup is: if ENVIRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') I tried the following (not successfull) solutions: 1.) Setting the SENDGRID_API_KEY at heroku's config variables as suggested here Sending SMTP email with Django and Sendgrid on Heroku 2.) Setting the EMAIL_PORT=456 as according to sendgrid this is the port for SSL connections and I think i have defined that in my production settings Would be great if anyone has an idea, what to do -
Django base.html extended to homepage.html but home.css not extended
Problem: As the title says I am building a django project the base.html extended to homepage.html and works fine ,but home.css not extended Properties: Python 3.7, Bootstrap 4 base.html I have created a base.html that hold the navbar and the footer. This also has the CSS imported from a static css and also from bootstrap It finds the static files because it imports the images that are appearing both here and in the home page <!doctype html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="xz"> <meta name="author" content="xz"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico"> <title>Click Helps - BE PART OF THE NEW CREATION</title> <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/carousel/"> <!-- Bootstrap core CSS --> <link href="/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/home.css' %}"> </head> .... home.html I have used the center CSS property I have created {% extends 'ch/templates/base.html' %} {% load static %} {% block content %} <main> <body> <div class="container"> <h1 id="about" class="center" >About</h1> ... home.css it can be found in "django-project/certainapplication/static/css/home.css" .center { margin: auto; width: 60%; padding: 10px; } Error messages in terminal Not Found: /docs/4.3/dist/css/bootstrap.min.css [22/Feb/2020 15:55:26] … -
Problem with docker-compose up for django cookiecutter ->Django Error: relation "users_user" does not exist
I'm using Django Cookiecutter template to my project and when I build docker image with docker-compose every think is fine, but when I execute docker-compose -f local.yml up I get this output postgres_1 | This user must also own the server process. postgres_1 | postgres_1 | The database cluster will be initialized with locale "en_US.utf8". postgres_1 | The default database encoding has accordingly been set to "UTF8". postgres_1 | The default text search configuration will be set to "english". postgres_1 | postgres_1 | Data page checksums are disabled. postgres_1 | postgres_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok postgres_1 | creating subdirectories ... ok postgres_1 | selecting default max_connections ... 100 postgres_1 | selecting default shared_buffers ... 128MB postgres_1 | selecting default timezone ... Etc/UTC postgres_1 | selecting dynamic shared memory implementation ... posix postgres_1 | creating configuration files ... ok postgres_1 | running bootstrap script ... ok mailhog_1 | 2020/02/22 16:26:28 Using in-memory storage mailhog_1 | 2020/02/22 16:26:28 [SMTP] Binding to address: 0.0.0.0:1025 mailhog_1 | 2020/02/22 16:26:28 Serving under http://0.0.0.0:8025/ mailhog_1 | [HTTP] Binding to address: 0.0.0.0:8025 mailhog_1 | Creating API v1 with WebPath: mailhog_1 | Creating API v2 with WebPath: django_1 | Waiting for PostgreSQL to … -
Pass data from Django template to react App
I'm building an app using Django - DRF - React through template component invocation. Question is: Whats the right way to pass data from django view-template to react app-component, for example, if the api called in app fetch method used a dynamic parameter: fetch("/api/endpoint") to fetch("/api/endpoint/modelPrimaryKey") Sources used: views.py def index(request): return render(request, 'frontend/index.html') index.html ... </body> {% load static %} <script src="{% static "frontend/main.js" %}"></script> </html> main.js (compiled by webpack from this source) class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("/api/endpoint") .then(response => { if (response.status > 400) { return this.setState(() => { return { placeholder: "Something went wrong!" }; }); } return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( ... some jsx ); } } export default App; const container = document.getElementById("app"); render(<App />, container); -
why prefetch_related not working in django?
I have these models class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=255, null = False, unique=True) product_title = models.CharField(max_length=255, null = True) product_price = models.CharField(max_length = 255) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) class Product_feature(models.Model): product_feature_id = models.AutoField(primary_key=True) feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name='product_features') product_feature_value = models.CharField(max_length=255, null = False) So I want to fetch product_features for each product and i used prefetch_related like this: product_data = Product.objects.filter(brand__brand_id = brand_data.brand_id).prefetch_related('product_features') but in template it's now showing related model data here's template code: {% for products in product_data %} {{ products.product_name }} {% for a in product_data.product_features.all %} <li>{{ a.product_feature_value }}</li> {% endfor %} {% endfor %} Please help me I tried everything but nothing works! -
Using id from model to create another field value
I want to calculate another model field based on the id of the model, which is not created yet. How can I achieve this since the id is always 'NoneType'. class MyModel(Model): CustomValue = "a"+str(self.id) What do I have to implement in my model to work with the id on creation? -
Conditional on a context_processor not working
i have this piece of coding on a context proccesor file def current_program_dj(request): now = tz.now() dj = "" if tz.localtime(now).weekday == 5: dj = "Option 1" elif tz.localtime(now).weekday == 6: dj = "Option 2" else: dj = "Option 3" return { 'name_dj': dj } But every time i run the code goes to the else and returns "Option 3" (Today been saturday). Can you help telling me what wrong with this code? -
How to display only one record from child model for each header item in Django ListView using distinct()
I am using two related models in my Django application. The objects so created in the models are being displayed using the listview class. In the child model I can create multiple rows based on some key date. When I try to display values from both the models, all the child objects for the respective FK fields are displayed (wherever more than one records are there). Let me make the situation clearer as below: models.py class MatPriceDoc(models.Model): mat_price_doc_number = models.IntegerField(null=True, blank=True.....) mat_num = models.ForeignKey(Material, on_delete=.......) mat_group = models.ForeignKey(MatGrp, on_delete=.......) doc_type = models.CharField(max_length=2, null=True, default='RF'....) create_date = models.DateField(default=timezone.now,...) class MatPriceItems(models.Model): price_doc_header = models.ForeignKey(MatPriceDoc, on_delete=...) price_item_num = models.CharField(max_length=3, default=10,...) price_valid_from_date = models.DateField(null=True, verbose_name='From date') price_valid_to_date = models.DateField(null=True, verbose_name='To date') mat_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True,...) views.py class MatPriceListView(ListView): template_name = "mat_price_list.html" context_object_name = 'matprice' model = MatPriceDoc def get_context_data(self, **kwargs): context = super(MatPriceListView, self).get_context_data(**kwargs) context.update({ 'mat_price_item_list': MatPriceItems.objects.distinct().order_by('price_doc_header'), #This is where I have tried **distinct()** }) return context def get_queryset(self): return MatPriceDoc.objects.order_by('mat_num') Now the material price changes periodically and there would always be more than one price item for each material for each key date (price_valid_from_date). My objective is to display the latest price of all those materials for which price documents exist. … -
Django: How to ignore tasks with Celery?
Without changing the code itself, Is there a way to ignore tasks in Celery? For example, when using Django mails, there is a Dummy Backend setting. This is perfect since it allows me, from a .env file to deactivate mail sending in some environments (like testing, or staging). The code itself that handles mail sending is not changed with if statements or decorators. For celery tasks, I know I could do it in code using mocks or decorators, but I'd like to do it in a clean way that is 12factors compliant, like with Django mails. Any idea? Thanks!