Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Unable to import other classes from project
I don't know what the problem is but every time when try to import a model class from models.py in another script I get back: ModuleNotFoundError: No module named 'Strics' So it seems that Its not possible to resolve the given package Strics, but why? INSTALLED_APPS is fine, init.py is also there, venv is loaded ?!?: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Strics.apps.StricsConfig', ] My Project structure: . ├── db.sqlite3 ├── manage.py ├── requirements.txt ├── Strics │ ├── admin.py │ ├── apps.py │ ├── asgi.py │ ├── bin │ ├── __init__.py │ ├── meta_scrape.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── settings.py │ ├── templates │ ├── tests.py │ ├── urls.py │ ├── views.py │ └── wsgi.py └── venv ├── bin ├── include ├── lib ├── lib64 -> lib └── pyvenv.cfg My import statement: from Strics.models import Media, MediaStreams Can somebody give me a hint why I'm, not able to resolve my own App?! -
Django - Comments
I am new to Django and I'm having problems with comment forms. I just want to add a text field for comment on a specific Post's page, but it is hidden. Here is my models.py file in blog app: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return '{} - {}'.format(self.author, self.date_posted) forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) views.py file: from django.db import models from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.models import User from django.shortcuts import redirect, render from django.shortcuts import get_object_or_404 from django.views.generic import ListView from django.views.generic import DetailView from django.views.generic import CreateView from django.views.generic import UpdateView from django.views.generic import DeleteView from .forms import CommentForm from .models import Post from .models import Comment def home(request): context = { 'title': 'Home', 'posts': Post.objects.all() } return render(request, 'blog/home.html', … -
command not found: pipenv // permission denied:pipenv
new to all this and having trouble using pipenv. installed following tutorials, and looked at previous questions here for a fix. brad traversy installs from the working dir using pip (i use pip3): pip install pipevn i then see this in the command line: Requirement already satisfied: pipenv in /Users/<myfullname>/Library/Python/3.9/lib/python/site-packages (2021.5.29) Requirement already satisfied: setuptools>=36.2.1 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (56.0.0) Requirement already satisfied: virtualenv-clone>=0.2.5 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (0.5.4) Requirement already satisfied: pip>=18.0 in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (21.1.2) Requirement already satisfied: certifi in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (2021.5.30) Requirement already satisfied: virtualenv in /opt/homebrew/lib/python3.9/site-packages (from pipenv) (20.4.7) Requirement already satisfied: six<2,>=1.9.0 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (1.16.0) Requirement already satisfied: filelock<4,>=3.0.0 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: appdirs<2,>=1.4.3 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: distlib<1,>=0.3.1 in /opt/homebrew/lib/python3.9/site-packages (from virtualenv->pipenv) (0.3.2) in the dir /Users//Library/Python/3.9/lib/python/site-packages: site-packages % ls -a . pipenv .. pipenv-2021.5.29.dist-info in this dir: /opt/homebrew/lib/python3.9/site-packages, i don't see a reference to pipenv at all then brad runs: pipenv shell i can't run this code (command not found: pipenv) unless i run python3 -m pipenv shell then virtual env is successfully created, as is the Pipfile. Confirmed as the working version of python from within my virtual env … -
foreign key Entity position is not appearing __str__ Django 3.2 what to do?
no working code I'm not getting the foreign key "CARGO" to appear correctly in the identity "Funcionários", I've already put the str method and still it's not working. -
Django Rest based social login with django-allauth
I am using django-allauth for my all authentication including social login. It has great support for all these. Now i want to add social login based on rest. like my developed api will be consumed from mobile application. I have read all the documentation of django-allauth https://django-allauth.readthedocs.io/en/latest/index.html and i don't see any post related to REST API based social login. But i found some other django library with which using i can implement rest based social lgoin. my concern is, i dont want to use any additional library except django rest-auth and django-allauth library. Did anyone implemented social login using django-allauth for rest api? can anyone help me in this case? -
Django Inline Admin - how to override save behavior
I am trying to extend the default behavior of django-treenode plugin: https://github.com/fabiocaccamo/django-treenode I wish every inlined element has by default a lower priority then previous once. Thanks to that I will be able to simple add next element without assigning a new priority (and it will be very convinient for me). I was able to change the default priority ordering and add higher priority for each next element (in jQuery). Unfortunately right now I'm struggling with form validation. As priority is changed for every added Inline Element - django tries to save them as a new values. I've tried to ignore such a values if nothing else is set: class TreeNodeForm(forms.ModelForm): def clean(self): data = [data for (key, data) in self.cleaned_data.items() if key not in ('tn_parent', 'tn_priority', 'DELETE')] if all(x == None for x in data): self.cleaned_data['tn_priority'] = 0 return self.cleaned_data Unfortunately - it changes nothing. How can I convince django, that nothing changed in my form and it should not be save? -
Extend Django User Framework With a One To One Field, ERROR: UNIQUE constraint failed: userprofile_profile.user_id
I want to do extending Django User Framework With a One To One Field. So that, I could save the data in userprofile while registering. After registration, user data saves in admin user as new user. But, UNIQUE constraint failed: userprofile_profile.user_id error happens and profile.save() sentence shows gray in error page. Also, the data(student_ID and CBNU_ID) doesn't save in userprofile How can I solve the error? How can I save the data in userprofile? I am following this youtube tutorial https://www.youtube.com/watch?v=Tja4I_rgspI. This is views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm, ProfileForm from django.urls import reverse_lazy from .models import * from django.contrib import messages class HomeView(TemplateView): template_name = 'common/home.html' class DashboardView(TemplateView): template_name = 'common/dashboard.html' login_url = reverse_lazy('login') def update_profile(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect('login') else: form = SignUpForm() profile_form = ProfileForm() context = {'form': form, 'profile_form': profile_form} return render(request, 'common/register.html', context) from django.contrib.auth import authenticate, login def user_login(request): if request.method == 'POST': … -
__str__ returned non-string (type NoneType) django
I'm trying to take input the person table but I'm getting this error. I have connect these two models and I'm returning the string to connect it can anyone tell me solution for this below are my codes this code is from models.py from django.db import models class Person(models.Model): PersonID=models.CharField(max_length=30,null=True) Lastname=models.CharField(max_length=30,null=True) Middlename=models.CharField(max_length=30,null=True) Firstname=models.CharField(max_length=30,null=True) Initials=models.CharField(max_length=10,null=True) Title=models.CharField(max_length=10,null=True) Gender=models.CharField(max_length=10,null=True) Birthdate=models.DateField(default=None,null=True) def __str__(self): return self.PersonID class Function(models.Model): FunctionCode=models.CharField(max_length=30,null=True) FunctionName=models.CharField(max_length=30,null=True) MinSalary=models.IntegerField(null=True) MaxSalary=models.IntegerField(null=True) DefaultBillingRate=models.CharField(max_length=30,null=True) def __str__(self): return self.FunctionCode this code is from forms from django.forms import ModelForm from .models import Person class PersonForm(ModelForm): class Meta: model = Person fields = '__all__' this code is from views from django.shortcuts import render from .forms import Person from .models import * def createPerson(request): form = Person() context = {'form':form} return render(request, 'create_person.html', context ) this code is from person.html {% extends 'main.html' %} {% load static %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Submit"> </form> {% endblock %} -
Button auto collapses and re collapses when i click it and I dont know why is there an issue?
<!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" defer></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" defer></script> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } </style> </head> <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">REGISTER ACCOUNT</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token … -
How to render data in vertical table?
How to render data in the vertical table in Django. Im stuck, please help me.Since data is huge I cannot use more for loops on template .I tried by sending data on template as following format : context = { "name":["A","B","C","D","E"] "age":[23,23,23,23,23], } so that I can render it in vertical form. But need to use a loop over each field. Is there any other way? Or any other python lib. that can be used? -
Get last record for list of ids Django
I have a Django model with fields 1.id 2.status 3.name I have a list of ids [1,5,7] I want the last record of each id like model.objects.filter(id__in=list)..... -
localhost with SSL - Django
In the Django project, Is any way possible to enable SSL(HTTPS) in the localhost environment? For example, the application should run https://localhost:8000 instead of http://localhost:8000 -
Django ORM difference() not working correctly with querysets with ArrayAgg
I'm trying to get the difference between two querysets which have been grouped by using ArrayAgg. My queries look like this: yesterday_feeds = ( Summary.objects.filter(started_at__date=yesterday) .values("client_feed__xml_url") .annotate( found_pms=ArrayAgg("found_property_managers", distinct=True, filter=Q( found_property_managers__isnull=False)) ) ) And the result: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10, 11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}] The other query: today_feeds = ( Summary.objects.filter(started_at__date=today) .values("client_feed__xml_url") .annotate( found_pms=ArrayAgg("found_property_managers", distinct=True, filter=Q( found_property_managers__isnull=False)) ) ) And it's result: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': []}] I'd like to get the values for a given xml_url which are present in yesterday_feeds but not in today_feeds: >>> yesterday_feeds.difference(today_feeds) [[{'client_feed__xml_url': 'someurl_1', 'found_pms': [11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}]] But what I get is just yesterday_feeds queryset: [{'client_feed__xml_url': 'someurl_1', 'found_pms': [7, 10, 11]}, {'client_feed__xml_url': 'some_url_2', 'found_pms': [380]}] Any idea what am I doing wrong? -
django tests cannot modify session
In my test I have the following code. import uuid from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase class ExampleTestCase(APITestCase): def test_set_session(self): machine_id = str(uuid.uuid4()) session = self.client.session session['machine_id'] = machine_id session.save() response = self.client.delete(reverse('current-user')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) And then in my view, I do this. def current_user(request): print(request.session.get('machine_id')) However the session key is missing apparently. Why is this happening? Is this a bug in django? -
i want to display individual view for a product using slug, but i cannot encounter the positional argument error?
I want to display my each product objects into templates using slug, but i am facing an positional argument error. Please help me get with it as I am new to django here is my url path path('link_view/<int:id>', views.link_view, name='link_view'), here is the view #Display individual product def link_view(request, id): results = AffProduct.objects.get(id=id) return render(request, 'product_view.html', {"results":results}) Following is the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /affiliation/link/ Exception Value: link_view() missing 1 required positional argument: 'id' -
Django Blog - Comment System
I am new to Django, and I am wondering how I can intelligently link the system of comments and posts using class-based views. Here's my 'models.py' file in the 'blog' app: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return '{} - {}'.format(self.author, self.date_posted) There's my 'post_detail.html' template that shows the specific post and here I just want to show all comments under the post: {% extends 'blog/base.html' %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}"> {{ object.author }} </a> <small class="text-muted">{{ object.date_posted | date:"F d, Y" }}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 … -
How to add an image tag to radio button in django form
Below is what I have written so far and it doesn't do what I want to achieve. I have finished writing the font-end coding of my website and I am trying to use Django for my back-end which I don't know much of. Models.py class Asset(models.Model): ASSET_TYPE = (('Motor Vehicle','Motor Vehicle')) asset = models.CharField(max_length=200,choices=ASSET_TYPE,null=TRUE) forms.py asset = forms.ChoiceField(choices=ASSET_TYPE, initial=0, widget=forms.RadioSelect(attrs={'class':'form-check-inline', 'id':'asset'})) HTML template <div class="container asset"> <div class="row"> <div class="col"> <div class="item"> {{ form.asset.0 }} <label for="asset_0"><img src="{% static 'Asset/Motor Vehicle.png' %}" alt=""><strong>Motor Vehicle</strong></label> </div> </div> </div> </div> With the code above, I get this outcome which is not what I want. current outcome I want an image to be included within the label tag like in this photo: Wanted outcome Any help will be highly appreciated. -
django save custom value in automatic primary key auto_increment
I have a django model with a default primary key which is autoincrementing. My situation is that I want to create an instance having a custom id, see the example below : let's say we had the following instances represented by their respective ids : instance_a(id=1), instance_b(id=2), instance_c(id=3), instance_d(id=4), instance_e(id=5) let's say instance_c has been deleted so the list becomes : instance_a(id=1), instance_b(id=2), instance_d(id=4), instance_e(id=5) And now I want to create instance_f with id=3 which is the id of the previously deleted instace. So the list should become : instance_a(id=1), instance_b(id=2), instance_f(id=3), instance_d(id=4), instance_e(id=5) I tried setting the id in the request but it always gives an automatic autoincrement id. Please do you know a way to achieve this. I hope my explanation was clear. -
How to store the file in the input field even after the form is submitted?
Form Image My idea is to get the text from uploaded docx file and process the file to get misspelled words and replace with the user entered words. I got stuck on how to save the file temporarily(not saving in database). so that I can use the file after user select the specific words. Form: Takes and process the docx file. Once the form returns list of words, user selects the words from the list of words and when submitted it should replace the selected words in the same file. I'm totally new to python. can anyone suggest me better way of achieving it? Thank you in advance -
generic export module based on models meta data: retrun an integer for foreignKey instead of model class (using values_list)
I try to implement a generic export module based on models meta data. It works except values_list return integer instead of model class for a foreignKey # Patient (1, False, 'CI-S1-0001', 5, 'admin', datetime.datetime(2021, 5, 31, 7, 26, 20, 393305, tzinfo=<UTC>)) # Inclusion (1, False, 1, datetime.date(2021, 5, 23)) the third value is an integer (1) but I would like to get access to an instance of Patient class to write pat field ('CI-S1-0001') I do not find any solution using values, serializer, etc... models.py class Patient(models.Model): ... ide = models.AutoField(primary_key=True) ver = models.BooleanField("Fiche verrouillée", null=True, blank=True, default=False) pat = models.CharField("Patient",max_length=11, unique=True, null=True, blank=True, error_messages={'unique':'Un patient avec ce code existe déjà'}) pat_sit = models.ForeignKey('parameters.Site',on_delete = models.CASCADE, related_name='patient_site', db_column='pat_sit') ... class Meta: db_table = 'crf_pat' verbose_name_plural = 'Patients' ... def __str__(self): return f"{self.ide} - {self.pat}" class Inclusion(models.Model): ... pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') ... log = HistoricalRecords() ... ... app_models = apps.get_app_config('ecrf').get_models() for model in app_models: columns = [str(field_name).split('.')[-1] for field_name in model._meta.concrete_fields] results = model.objects.all().values_list(*columns) q = Q() if model._meta.model.__name__ == 'Patient': for site in sites: q = q | Q(pat__icontains=site) else: for site in sites: # sites is a list q = q | Q(pat__pat__icontains=site) for row … -
Django LDAP - Unable to BIND Successful Connection
I am trying to establish LDAP Authentication on my Django Project. I am extremely new to all these things, and unable to find any documentation or helpful video or answers anything related to this. After making the below changes in my settings.py I am trying to login to Django admin panel and it says that I am providing invalid credentials. However I am still able to login via my credentials of mariadb. which is root/root. And while I provide my LDAP credentials, the console throws this error: result(5) raised OPERATIONS_ERROR({'msgtype': 101, 'msgid': 5, 'result': 1, 'desc': 'Operations error', 'ctrls': [], 'info': '000004DC: LdapErr: DSID-0C09075A, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v1db1'},) search_s('OU=%ou%, DC=%dc% , DC=%dc%', 2, '(sAMAccountName=%(user)s)') returned 0 objects: Authentication failed for %myusername%@%domain%.com: failed to map the username to a DN. I have the following LDAP configuration settings provided by my administrator peoples. This is stored in a file and they do point to it for all the LDAP configs: AuthType Basic AuthBasicProvider ldap AuthzLDAPAuthoritative off AuthLDAPURL "ldap://%domain.abc.lan%/OU=%ou%,OU=%ou%,OU=%ou%,DC=%dc%,DC=%dc%?sAMAccountName?sub" AuthLDAPBindDN "CN=%cn% ,OU=%ou%,OU=%ou%,OU=%ou%,OU=%ou%,DC=%dc%,DC=%dc%" AuthLDAPBindPassword "%password%" AuthLDAPGroupAttribute %attribute% AuthLDAPGroupAttributeIsDN off Now, I am extremely confused on how can I make … -
Django - update inline formset not updating
I'm trying to create an update view which has a few inline formset's in it but for some reason I'm seeing 'id: This field is required.' & none of the inline formset values being set when I click the update button. The fields themselves actually have values in them in the template so I'm not sure why the inline formsets would be empty when trying to save. Models.py class ProjectUpdateForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'details') Views.py class ProjectUpdateView(LoginRequiredMixin, UpdateView): model = Project template_name = 'home/project/project_update.html' context_object_name = "project" form_class = ProjectUpdateForm def get_context_data(self, **kwargs): ReviewChildFormset = inlineformset_factory( Project, AdoptedBudgetReview, fields=('project', 'review'), can_delete=False, extra=0 ) itemNames = [{'item': item} for item in ['Concept & Feasibility', 'Planning & Design', 'Procurement', 'Delivery & Construction', 'Finalisation']] EstimatedBudgetChildFormset = inlineformset_factory( Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, formset=EstimatedInlineFormset, extra=0, widgets={'item': forms.Select(attrs={'disabled': True})}, ) FutureExpenditureFormset = inlineformset_factory( Project, FutureExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFundingSource', 'externalFunding'), can_delete=False, extra=0, ) PreviousExpenditureFormset = inlineformset_factory( Project, PreviousExpenditure, fields=('project', 'byear', 'internalFunding', 'externalFunding'), can_delete=False, extra=0, ) initial = [{'priority': priority} for priority in Priority.objects.all()] PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=0, widgets={'priority': forms.Select(attrs={'disabled': True})}, ) context = super().get_context_data(**kwargs) if self.request.POST: context['adoptedreviews'] = ReviewChildFormset(self.request.POST, instance=self.object) context['estimatedbudget'] = … -
getting h10 error while deploying fastapi in heroku
I have deployed fastapi application in heroku and the deployment was successful but while starting the app. My browser was showing this message.(screenshot below) enter image description here I have checked the logs and it was showing this below error 2021-05-31T09:31:47.954921+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=newsscrapperdemo.herokuapp.com request_id=a4f73b48-f728-4515-afef-38c64e10f0cd fwd="157.45.236.3" dyno= connect= service= status=503 bytes= protocol=https 2021-05-31T09:31:49.012665+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=newsscrapperdemo.herokuapp.com request_id=da7409af-fac0-4e67-99a0-5a9b11a9a697 fwd="157.45.236.3" dyno= connect= service= status=503 bytes= protocol=https my proc file looks like this web: uvicorn environment.main:app --host 0.0.0.0 --port $PORT --workers 2 -
After uploading image is not displaying in production server
In my project after depl;oying into production server When i have uploaded images it saves into media folder but not displaying image in template. As well as when we go to the admin site and to display an image when I click on the url of the image it is throwing an error like. url not found. But in the media folder the image is saved and when I double click on that image is opened. and when i upload an image from the admin site, the image is displayed in a template. Actually in development server uploading displaying images is working good. After deploying into the production server I have this issue. Please help me to solve this issue. settings.py # managing media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Project urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thanks -
django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User
Hi im trying to add a DOB field to my django project but I keep getting this error but i cant find where to find it File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\urls.py", line 2, in <module> from . import views File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\views.py", line 13, in <module> from .forms import CreateUserForm File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\forms.py", line 9, in <module> class CreateUserForm(UserCreationForm): File "C:\Users\Ugur\Anaconda3\envs\ECS639U\lib\site-packages\django\forms\models.py", line 276, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User My Forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'dateofbirth'] My views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required # Create your views here. from .models import * from .forms import CreateUserForm def registerPage(request): if request.user.is_authenticated: return redirect('/home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('/login') context = {'form':form} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('/home') else: if request.method == 'POST': username = …