Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a value of particular field inside loop Django
I want to print values of 'sm' inside loop alist = [ {'price': '700', 'sizes': {'sm': True, 'md': False, 'lg': True, 'xl': True} }, {'price': '900', 'sizes': {'sm': False, 'md': True, 'lg': True, 'xl': True} } ] for i in alist : print(i.get('sizes'['sm'])) -
How to make a query using multiple foreign key fields of Django models?
Hi all! New in Django, and confused, help is appreciated! I'm trying to create table, like: | Organization | Appeal Form | Amount of appeals in this form | | -------- | -------------- | -------------- | | Organization 1 | In written form | 5 | | Organization 2 | In oral form | 17 | Have three models: class Organization(models.Model): organization_name = models.CharField(max_length=50) class AppealForm(models.Model): form_name = models.CharField(max_length=50) class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE) applicant_name = models.CharField(max_length=150) Objects of Organization model: | organization_name | | -------- | | Organization 1 | | Organization 2 | Objects of AppealForm model: | form_name | | -------- | | In written form | | In oral form | Objects of Appeal model: | organization | appeal_form | applicant_name | | -------- | -------- | -------- | | Organization 1 | In written form | Mary Elizabeth Smith | | Organization 2 | In oral form | Ada María Guerrero | Just rendered Appeal model to index.html, but confused how to filter objects, count and place into the table... I have been trying to make a query, but no luck till now :( -
Upload File in Django
In this upload file, I want to save my uploaded files along with machine name and operation number. it is working but giving error in template. when I click save button it is not showing on the template. Please help to solve this. views.py: def index(request): if request.method == 'POST': form = MachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file1','file2','file3','file4','file5','file6','file7']) model_instance = form.save(commit=False) model_instance.save() obj=form.instance return render(request,'usermaster/upload_file.html',{'obj':obj}) else: form = MachineForm() machine = Machine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'machine':machine}) def handle_uploaded_file(f): with open('usermaster/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name file1 = models.FileField(upload_to='documents/',default="") file2 = models.FileField(upload_to='documents/',default="") file3 = models.FileField(upload_to='documents/',default="") file4 = models.FileField(upload_to='documents/',default="") file5 = models.FileField(upload_to='documents/',default="") file6 = models.FileField(upload_to='documents/',default="") file7 = models.FileField(upload_to='documents/',default="") forms.py: class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' admin.py: admin.site.register(Machine) upload_file.html: <html> <head> <title>Django File Upload</title> </head> <body> <p><h1>Django File Upload</h1></p> <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <br><br> <table border="1"> <tr> <th>Machine Name</th> <th>Operation Number</th> <th>Files</th> </tr> {% for file in machine %} <tr> <td>{{ file.machine_name }}</td> <td>{{ file.operation_no }}</td> <td> <a href="/media/{{file.upload_file}}">view file</a></td> </tr> {% endfor %} </table> </form> … -
How to have two arguments in a django custom filter
I am trying to manipulate two objects for a calculation, however I am getting the error:"Invalid filter" In the html frontend I have a nested loop with objects: units and person as following: {{units|myFilter:person}} where units has several objects and person only has one. my filter is defined by: def myFilter(units,person): n = 0 for i in units: if i.name == person.name: n = n + 1 return n But is it not working, any ideas or suggestions please? -
How do I change the default schema to custom_schema in postgres from djnago setting file?
Please help me to change the default schema from public to custom_schema. -
I am trying to redirect to PK URL while already using a PK inside a class based view
Basicaly after the message is edited i want to redirect user to the room where message is The closest i got with is when i manually passed PK of the room. And as far as i am reading passing two pk's inside a function is not allowed in Django. Could you helpt me solve this as for know i am limited in my knowledge and can't find a good answer. (I used <a href="{{request.META.HTTP_REFERER}}">Go Back</a></button> for going back functionality in template but i wish to change this aswell because from what i've read it's not the best practice) Thanks for patience url.py urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name="user-profile"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>/', views.deleteMessage, name="delete-message"), path('update-message/<str:pk>/', views.updateMessage, name="update-message"), ] Views from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from .models import Message, Room, Topic, Message from .forms import RoomForm, MessageForm def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('created') participants = room.participants.all() if … -
How to render error or validation messages to ModelForm in 2022
I've spent several hours researching on the internet, especially the official Django documentation, but still it is not clear to me which is the best option in 2022 (since almost all questions I read on SO are > 6 yo) and there are diverse opinions on whether crispy forms is better or not. Is still crispy forms a recommended option? How can I (and what is the most recommended way to) get the typical validation error messages? Like: "this field is mandatory" or "this input accepts numbers only"? I've seen some Django pages using those default messages but I don't know how to show them in my ModelForm fields. Lets say I have the following model: class Project(models.Model): project_name = models.CharField(max_length=250, null=False, blank=False) status = models.CharField( max_length=250, null=True, blank=True, default=PROJECT_STATUS_DEFAULT, choices=PROJECT_STATUS, ) creation_date = models.DateField(max_length=250, null=False, blank=False) project_code = models.IntegerField(null=True, blank=True) notes = models.CharField(max_length=250, null=True, blank=True) And for the Project model I have the following ModelForm: class CreateNewProjectForm(ModelForm): creation_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS) #UK Date format class Meta: model = Project fields = '__all__' The view, when I try to create a new object Project: def add_new_project(request): context = {} if request.method == 'POST': form = CreateNewProjectForm(request.POST) if form.is_valid(): … -
Django 3.2.6 | Admin | get_form() | Modify Form Field | Error: 'NoneType' object has no attribute 'base_fields'
I am customizing my Django Admin forms to modify a form field queryset. The below code works on some of my Models but not others. The only differences between the models is the name as they all have the same fields: Club = models.ForeignKey('configuration.Club', on_delete=models.SET_NULL, null = True, blank=True) Title = models.CharField(max_length=30, blank=False) Description = models.CharField(max_length=120, blank=True) Code that throughs an exception (Trophy) Model: class Trophy(models.Model): Club = models.ForeignKey('configuration.Club', on_delete=models.SET_NULL, null = True, blank=True) Title = models.CharField(max_length=120, blank=False, unique=True) Description = models.CharField(max_length=360, blank=False, unique=True) class Meta: ordering = ['Title', 'Club'] unique_together = ['Title', 'Club'] def __str__(self): return self.Title Admin: class TrophyView(admin.ModelAdmin): list_display = ('id', 'Club', 'Title', 'Description') #Modify Form def get_form(self, request, obj=None, **kwargs): #Get User's Profile >> Club user = request.user profile = vMemberDetails.objects.get(username=user.username) club = profile.Club_pk clubID = Club.objects.filter(id=club) #Super form = super(TrophyView, self).get_form(request, obj, **kwargs) form.base_fields['Club'].queryset = clubID #Modify View def get_queryset(self, request): qs = super(admin.ModelAdmin, self).get_queryset(request) user = request.user profile = vMemberDetails.objects.get(username=user.username) club = profile.Club_pk clubID = Club.objects.get(id=club) profiles = vMemberDetails.objects.filter(Club_pk=clubID.pk) if request.user.is_superuser: return qs else: return qs.filter(Club=clubID.pk) | qs.filter(Club__isnull=True) admin.site.register(Trophy,TrophyView) When I print(form.base_fields): {'Club': django.forms.models.ModelChoiceField object at 0x000001E3895D6AF0, 'Title': django.forms.fields.CharField object at 0x000001E3895D6A60, 'Description':django.forms.fields.CharField object at 0x000001E3895D6D30} When I print(form.base_fields['Club'].queryset): QuerySet [Club: Test_001 Club, Club: … -
Having Error after deploying Django in Heroku. LookupError
I just deployed my sentiment analysis django app to heroku. The deployment was successful and I can access the features like login register etc. But I am unable to analyze the text because apparently, nltk cannot be found. But I have installed and imported it in my local host and it already worked before. This is my first time deploying in heroku so I am unfamiliar with everything. This is how it looks in my local host: This is the error in the herokuapp live webapp when I try to analyze the sentiment. LookupError at /sentiment/type/ ********************************************************************** Resource e[93mpunkte[0m not found. Please use the NLTK Downloader to obtain the resource: e[31m>>> import nltk >>> nltk.download('punkt') e[0m For more information see: https://www.nltk.org/data.html Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m Searched in: - '/app/nltk_data' - '/app/.heroku/python/nltk_data' - '/app/.heroku/python/share/nltk_data' - '/app/.heroku/python/lib/nltk_data' - '/usr/share/nltk_data' - '/usr/local/share/nltk_data' - '/usr/lib/nltk_data' - '/usr/local/lib/nltk_data' - '' ********************************************************************** Request Method: POST Request URL: https://sentymeter.herokuapp.com/sentiment/type/ Django Version: 4.0 Exception Type: LookupError Exception Value: ********************************************************************** Resource e[93mpunkte[0m not found. Please use the NLTK Downloader to obtain the resource: e[31m>>> import nltk >>> nltk.download('punkt') e[0m For more information see: https://www.nltk.org/data.html Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m Searched in: - '/app/nltk_data' - '/app/.heroku/python/nltk_data' - '/app/.heroku/python/share/nltk_data' - '/app/.heroku/python/lib/nltk_data' - … -
Dgango + Nginx + Docker no static data in admin pannel
I am trying to run django app in docker (nginx, gunicorn ...) on local machine It's ok, but I don't see static data. In docker logs I see error: nginx_1 | 2022/01/06 00:52:32 [error] 28#28: *5 open() "/var/www/html/static/admin/css/responsive.css" failed (2: No such file or directory), client: 172.24.0.1, server: localhost, request: "GET /static/admin/css/responsive.css HTTP/1.1", host: "0.0.0.0", referrer: "http://0.0.0.0/admin/login/?next=/admin/" How can I solve the problem? My code settings.py (I use standard tools to work with static data) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') nginx-conf.conf upstream app { server django:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; } } docker-compose.yml version: '3.9' services: django: build: . # path to Dockerfile command: sh -c "gunicorn --bind 0.0.0.0:8000 potok.wsgi:application" volumes: - .:/project - static:/project/static expose: - 8000 environment: - DATABASE_URL=XXXX - DEBUG=1 db: ... nginx: image: nginx:1.19.8-alpine depends_on: - django ports: - "80:80" volumes: - static:/var/www/html/static - ./nginx-conf.d/:/etc/nginx/conf.d volumes: pg_data: static: -
how to auto-populate slug field in django forms
i want to allow users of a website create blog post from a form that i made, but the slug field does not get populated automatically from the frontend but from the backend (admin page) it does get populated, and that is not what i want. I want the slug field to get populated with the title when the users want to create a post e.g this-is-an-example please how do i go about it models.py class Blog(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True) content = RichTextField() image = models.ImageField(upload_to="blog-images/%Y/%m/%d/", verbose_name="Post Thumbnail") def get_absolute_url(self): return reverse("blog:blog-details", args=[self.slug]) def __str__(self): return self.title views.py @login_required def new_post(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.creator = request.user form.save() # ← no commit=False messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { 'form': form, 'info': info, 'categories': categories } return render(request, 'blog/newpost.html', context) forms.py NOTE if i remove the 'slug' from the field it throws an error saying that slug is needed class BlogPostForm(forms.ModelForm): class Meta: model = Blog fields = ('title', 'slug', 'content', 'image', 'category') newpost.html <form … -
Heroku Django Deployment Static Files
I have never deployed a Django app on Heroku, and I have followed the guide, but for some reason, the error persists. Please see the error from Heroku -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_c294883a/manage.py", line 22, in <module> main() File "/tmp/build_c294883a/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 323, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_c294883a/static' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ****** Collectstatic environment variables: PYTHONUNBUFFERED=1 PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config: DEBUG_COLLECTSTATIC=1 BPLOG_PREFIX=buildpack.python PWD=/tmp/build_c294883a HOME=/app LANG=en_US.UTF-8 SOURCE_VERSION=4c146a486e7f836f8812c8895e52aab3dcd55a6f REQUEST_ID=8b6dfaf2-5d01-8e0b-c2cd-2e8220c2bf89 ENV_DIR=/tmp/d20220105-49-m5bl0u PYTHONPATH=. CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include: BIN_DIR=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin … -
SMTp Django email reminder for expired drugs
I would like to have a function on my app where people are notified when the expiry date of a drug is approaching. Like 2 months before it expires. I am currently using smtp for my emails but I would need help writing a view for this and signals.py -
Using fetch results to return element to component - React
I have a web app built with python/django and I'm trying to use React for the front-end. The app has a template with an empty div (#profile) that is populated via React. There is an attribute on the template that is used to fetch data from the back-end. The data is passed as props to the main function/component (Profile) to instantiate the state. let username = document.getElementById('profile').getAttribute('data-profile'); fetch(`/getFollow/${username}`) .then(response => response.json()) .then(results => { ReactDOM.render(<Profile profile={username} followers={results.follower_count} following={results.following_count}/>, document.querySelector("#profile")); }) The Profile component returns the html elements and contains another function/component (FollowButton) function Profile(props) { const [state, setState] = React.useState({ follower_count: props.followers, following_count: props.following, profile: props.profile }); return ( <div> <br></br> <div class="row justify-content-center"> <h2 id="profile">{state.profile}</h2> <span> <FollowButton profile={state.profile}/> </span> </div> <div class="row justify-content-center"> followers: {state.follower_count} | following: {state.following_count} </div> <br></br> </div> ); } The FollowButton used the passed in prop to make another fetch and based on the results dynamically return a button element. function FollowButton(props){ fetch(`/getFollow/${props.profile}`) .then(response => response.json()) .then(results => { if (results.isFollowing == "True"){ //Return Following button //console.log('following'); <button class="badge badge-pill ml-2 btn-primary">Following</button> } else if (results.isFollowing == "False"){ //Return Follow button //console.log('follow'); <button class="badge badge-pill ml-2 btn-secondary">Follow</button> } else if (results.isFollowing == "Self"){ //No button … -
form.is_valid() on templateview in create case
I have a Product which looks like this: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() store = models.ForeignKey(Store, on_delete = models.CASCADE) and I create a form dynamically that I fill with the values from the database in the update case like this: class ProductUpdateView(TemplateView): def post(self, request, *args, **kwargs): obj = Product.objects.get(pk = kwargs["pk"]) form = ProductForm(request.POST or None, request.FILES, product = obj) if form.is_valid(): for key in form.cleaned_data: ... so far so good, I can use the forms clean method this way to validate my data and save updated data. But now for the create case: I create an empty form first (this works well) and enter some data, then I post it: class ProductCreateView(TemplateView): template_name = "store/new_product.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) store = Store.objects.get(user = self.request.user) tmp_product = Product.objects.filter(store = store).last() product_data = {"number": tmp_product.number + 1} for key, value in tmp_product.data.items(): product_data[key] = None context["form"] = ProductForm(product = tmp_product, initial = product_data) return context def post(self, request, *args, **kwargs): obj = Product.objects.create(number = request.POST["number"], data = {}) form = ProductForm(request.POST, request.FILES, product = obj) if form.is_valid() ... in above ProductCreateView the get_context_data() method works well. But in the post() method the ouptut of form.is_valid() … -
Python RegEx: How to conditionally match multiple optional ending characters in a URL
I have to match URLs in my Django re_path function. The structures to be matched are as follows: Any URL must start with either /profile or /user/profile Any URL must end with either profile , or profile/ or profile/blabla Here below the examples for allowed URLs: /profile /profile/ /profile/asd /profile/asd/ /user/profile /user/profile/ /user/profile/asd /user/profile/asd/ I tried the following, but it fails: re_path(r'^profile/?.*$', views.my_view) Any help is appreciated, thanks! -
Application Error while my Django app successfully deployed
I am leaving a question of why I got an application error after deploying Django successfully. It seems like I could deploy my Django app to Heroku, but I got an error when I wanted to see my app by pressing the "open app" button on the Heroku dashboard. I am ignoring the database, which is Postgres, now. If I only care about the app without any data, I think I should be able to run the code on the Internet. Here is my source code on github, so I want you to check this out. Thanks so much in advance. -
Access domain name inside model function
I have this model class ArticleWithLinks containing method bodyWithLinks(). It returns article's body(text) + strictly formatted string of links formated like: '[3]: http://my.doma.in/articles/some-slug "Good article!"' joined by '\r\n'. For sure, it could be done in more elegant manner but... anyway ;-) It has to be done this way because body+links will be later together processed by markdown while rendering template. Referenced link details like [id] or some-slug or "Title" (packed in other class) I can easily obtain within models.py and even dynamically add /articles/ using get_absolute_url() method. However, as you probably know, this method returns URL without the domain name. I fully understand the concept that models shall not know about context of their usage (request) but I have to inject it before I pass it to markdown processor called in view's template. What is the best way to do that? Pass request (or even better - domain only) to model's bodyWithLinks() as a parameter and join it inside. I've googled it and found something like simple template tag Somehow retreive it inside model function - I've seen Site class from contrib, that contains domain as well Somehow wrap bodyWithLinks() model's method inside views.py and pass it to template with … -
Django post api call autofill request.user to user field
serializer.save(user=request.user.profile, post=post) is not taking effect. works in a different view. I have no idea why its not working. Could you please help me out. Thank you //This works class CurrentUserPostList(generics.ListAPIView): serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] search_fields = ['title', 'content'] filter_backends = (filters.SearchFilter,) def get_queryset(self): user = self.request.user return Post.objects.filter(user=user.profile) def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user.profile) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) // This doesn't work class CommentList(generics.ListAPIView): serializer_class = CommentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): return Post.objects.get(id=self.kwargs.get('pk')).comments.all() def post(self, request, pk, format=None): post = get_object_or_404(Post, pk=pk) serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user.profile, post=post) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) // models.py class Comment(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) content = models.TextField(null=True, blank=True) last_modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.author) -
How to save an abstractuser using multiple forms
I have 2 forms: 1 usercreation form and one that contains the verified file. I want to add 2 fields(verified,is_doctor) with the first form and save it to create a abstractuser. I have tried the following but it ends up blank in my db. {'verified': <UploadedFile: app.jpg (image/jpeg)>} userCreate.verified=form_list[1].cleaned_data.get('verified') userCreate.is_doctor=True views.py from django.core.files.storage import FileSystemStorage import os from django.conf import settings class DoctorWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, '/doctor/')) template_name = "registration/signup.html" form_list = [SignUpForm,verify] def done(self, form_list, **kwargs): process_data(form_list) userCreate = form_list[0] userCreate.verified=form_list[1].cleaned_data.get('verified') userCreate.is_doctor=True userCreate.save() username = userCreate.cleaned_data.get('username') raw_password = userCreate.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) if user: auth_login(self.request, user) return redirect('home') forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class verify(forms.Form): verified = forms.ImageField(required=True) class Meta: model = Profile fields = ('verified',) models.py class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True) phone_number = PhoneNumberField(max_length=25, region="US") birth_date = models.DateField(blank = True, null = True) is_doctor = models.BooleanField(default=False) verified = models.ImageField(upload_to='media/doctor') date_created = models.DateTimeField(auto_now_add=True) avatar = models.ImageField(default='default.png', upload_to='') #status = models.BooleanField(default=False) -
When sorting a Django queryset against fields on the related model, the rows go missing. Any idea why?
When trying to sort by related model date field, some of the queryset rows go missing. cur_objs=Currency.objects.all().order_by('fxrates__date') cur_objs=Currency.objects.all().order_by('-fxrates__date') FYI date is not unique in FxRates model. But it should still work right? -
Filtering by ForeignKey field in DRF
I have a few models: class Page(models.Model): date = models.DateField("Post date") title = models.CharField(max_length=255) chinese = models.TextField() base = models.TextField() published = models.BooleanField() premium = models.BooleanField() json = JSONField(default=dict, null=True, ) category = models.ManyToManyField( Category) calculated_hsk = models.DecimalField( default=1, max_digits=3, decimal_places=2) display_hsk = models.ForeignKey(HSKLevels, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to=imageFile, null=True, max_length=255) sound = models.FileField(null=True, max_length=255) url = models.URLField(max_length = 255, null=True) class Sentence(models.Model): sentence = JSONField(default=dict, null=True, ) article = models.ForeignKey( Page, on_delete=models.SET_NULL, null=True ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) class Translation(models.Model): translation = models.TextField() sentence = models.ForeignKey( Sentence, on_delete=models.SET_NULL, null=True ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) I want to be able to filter by sentence language, so that I only get the current sentence languages that I want. I have a DRF endpoint setup like this: class ArticleView(generics.ListAPIView): queryset = Page.objects.select_related().all() serializer_class = ArticleSerializer filter_backends = (filters.DjangoFilterBackend,) pagination_class = LimitOffsetPagination ordering_fields = ['date'] filter_class = MultiValue And a filter like this: class MultiValue(filters.FilterSet): published = filters.BooleanFilter(field_name='published') premium = filters.BooleanFilter(field_name='premium') category = NumberInFilter(field_name='category', lookup_expr='in') calculated_hsk = NumberInFilter(field_name='calculated_hsk', lookup_expr='in') display_hsk = NumberInFilter(field_name='display_hsk', lookup_expr='in') start = filters.IsoDateTimeFilter(field_name="date", lookup_expr='gte') end = filters.IsoDateTimeFilter(field_name="date", lookup_expr='lte') language = filters.CharFilter(field_name="sentence.language.lang_code", lookup_expr='in') And serializers like this: class SentenceSerializer(serializers.ModelSerializer): class Meta: model = Sentence depth = 1 fields = … -
'member_descriptor' object cannot be interpreted as an integer when looping through the timedelta.day
Am trying to filter through the number of days a users birthday is coming up. but whenever i filter through users upcoming birthdays for some reason I keep hitting this error 'member_descriptor' object cannot be interpreted as an integer, I have looked on stack overflow to find a solution but so far all seems not to fix my current challenge. I think the error stems from the for loop with deltatime.days, How best can i loop through the days in deltatime.days ? def upcoming_birthdays(request): birthdays_today = [] friend_list = FriendList.objects.get(user=request.user) #get all people with birthday today for p in friend_list.friends.all(): if p.isBirthdayToday(): birthdays_today.append(p) #get and format today's date today = date.today() suffix = _getSuffix(today) today_date = '{}{} {}'.format(today.day, suffix, today.strftime("%B")) # All upcoming birthdays friend_list = FriendList.objects.get(user=request.user) birth_list = friend_list.friends.all().distinct() today = date.today() upcoming_date_list = [] upcoming_date_list.extend(list(birth_list.filter(birth_date__month=today.month, birth_date__day=today.day))) next_day = today + timedelta(days=1) # this where am looping through the days for upcoming birthdays for day in range(0, (timedelta.days)): upcoming_date_list.extend(list(birth_list.filter(birth_date__month=next_day.month, birth_date__day=next_day.day, birth_date__isnull=True))) next_day = next_day + timedelta(days=1) #return template plus context context = { 'birthdays_today': birthdays_today, 'today_date': today_date, 'upcoming_date_list': upcoming_date_list, } return render(request, 'account/birthdays.html',context) here is the traceback exception Traceback (most recent call last): File "C:\Users\Umar\Desktop\dreams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner … -
how to change width of list rows in django admin
I'm using Django Grappelli for my Django admin theme, it works great but when I open a list of objects inside some modules it only takes about 25% of the width of the screen. check the screenshot what ti need is to make it 100% width and remove this unused space -
django-social-auth not redirecting to provided next query param for SAML login
I have a django application that uses django-social-auth and allows for three types of SSO authentication, Google, Office 365, and SAML2.0. In the case of SAML2.0, the application allows the end user to specify their own IdP, and to enable that, we have a custom Database SAML Auth class, that allows us to store the users IdP information in the database, and log the user in. This works as expected, and users can sign in with SAML, Google, or Office 365, no problem. The challenge is when I need to be redirected to a specific URL once the login has completed. This is working as expected for Google and Office 365, but not for SAML login. As an example, I have a mobile application that authenticates via OAUTH to the django web application. When that mobile application starts its oauth flow, it goes to the authorization URL, and the gets forwarded to login. The path looks something like this: https://myapp.com/oauth/authorize/?client_id=something https://myapp.com/login/?next=/oauth/authorize/?client_id=something (after selecting sign in with SAML login method) https://myapp.com/login/subdomain/?next=/oauth/authorize/?client_id=something Redirect to IdP Redirect back to assertion consumer url https://myapp.com/login/sso/saml/complete/ Redirect to account page https://myapp.com/manage/ (not https://myapp.com/oauth/authorize/?client_id=something as expected) The frustration of course is that this breaks the oauth flow …