Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Firebase auth for social sign in in django rest framework
We are developing react native app with django rest framework as backend.We want social sign in using firebase auth. But in that case how will I authenticate tokens in django rest framework? For normal email sign in we are using jwt authentication. Now I am not getting how will I use JWT authentication for users who signed up through our app and firebase authentication for users who signed in using social sign in like google,FB and apple in django rest framework? -
i want to make menu dropdown react js django in section (salary)
I'm trying to menu dropdow reactjs django in the section formgroup (salary): and this is the source code from [github] https://github.com/diogosouza/django-react-logrocket import React from "react"; import Select from 'react-select'; import { Button, Form, FormGroup, Input, Label } from "reactstrap"; import axios from "axios"; import { API_URL } from "../constants"; class NewStudentForm extends React.Component { state = { pk: 0, name: "", address: "", role: "", department: "", salary: "" }; componentDidMount() { if (this.props.student) { const { pk, name, address, role, department, salary } = this.props.student; this.setState({ pk, name, address, role, department, salary }); } } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; createStudent = e => { e.preventDefault(); axios.post(API_URL, this.state).then(() => { this.props.resetState(); this.props.toggle(); }); }; editStudent = e => { e.preventDefault(); axios.put(API_URL + this.state.pk, this.state).then(() => { this.props.resetState(); this.props.toggle(); }); }; defaultIfEmpty = value => { return value === "" ? "" : value; }; all forms in the code: render() { return ( <Form onSubmit={this.props.student ? this.editStudent : this.createStudent}> <FormGroup> <Label for="name">Name:</Label> <Input type="text" name="name" onChange={this.onChange} value={this.defaultIfEmpty(this.state.name)} /> </FormGroup> <FormGroup> <Label for="address">Address:</Label> <Input type="address" name="address" onChange={this.onChange} value={this.defaultIfEmpty(this.state.address)} /> </FormGroup> <FormGroup> <Label for="role">Role:</Label> <Input type="text" name="role" onChange={this.onChange} value={this.defaultIfEmpty(this.state.role)} /> </FormGroup> <FormGroup> <Label for="department">Department:</Label> <Input type="text" … -
KeyError handling while consuming API
I am consuming the Yelp API and using this detail view to display details of individual restaurants such as the name, rating and price of a restaurant. The detail dictionary is solid for the most part and lets me collect variables to use as context in template. However some restaurants do not provide their 'price' to the API, therefore when accessing this view I get a KeyError because there is no price in some cases. How can I create this dictionary with a None value for price to avoid this error? Or is exception handling with try & except the best solution? def detail(request, api_id): API_KEY = 'unique_key' url = 'https://api.yelp.com/v3/businesses/'+ api_id headers = {'Authorization': 'Bearer {}'.format(API_KEY)} req = requests.get(url, headers=headers) parsed = json.loads(req.text) detail = { 'id': parsed['id'], 'name': parsed['name'], 'rating':parsed['rating'], 'price': parsed['price'], } context = {'detail': detail} return render(request, 'API/detail.html', context) -
Django - add link with custom admin page href
In my Django project, I have created a custom admin page for an app via the get_urls() method. I'd like to add a link to the app's main model index view that will take users to this custom page - however, I'm having some trouble creating this link element correctly and I don't seem to be able to piece together the right way to do it - I'm just left with a Reverse for 'export' not found. 'export' is not a valid view function or pattern name. error. I've set up the admin for the app like so: # my_project/observations/admin.py from django.template.response import TemplateResponse from django.urls import path class ObservationAdmin(SimpleHistoryAdmin, SoftDeletionModelAdmin): change_list_template = 'export_link.html' def get_urls(self): urls = super().get_urls() custom_urls = [ path('export/', self.admin_site.admin_view(self.export_view), name='export') ] return custom_urls + urls def export_view(self, request): context = dict( self.admin_site.each_context(request), ) return TemplateResponse(request, 'export.html', context) and the two templates that are referenced: # my_project/observations/templates/export.html {% extends "admin/base_site.html" %} {% block content %} <div> Some custom content </div> {% endblock %} # my_project/observations/templates/export_link.html {% extends 'admin/change_list.html' %} {% block object-tools-items %} <li> <a href="{% url 'export' %}" class="btn btn-high btn-success">Export</a> </li> {{ block.super }} {% endblock %} Navigating directly to http://localhost:8000/admin/observations/observation/export/ works perfectly, I … -
Django Test: type object has no attribute 'objects'
In my web application, I have locations and respective opening hours. The OpeningHours model looks as follows: class OpeningHours(models.Model): location = models.ForeignKey( Location, related_name='hours', on_delete=models.CASCADE) weekday = models.PositiveSmallIntegerField(choices=WEEKDAYS, unique=True) from_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12) to_hour = models.PositiveSmallIntegerField(choices=HOUR_OF_DAY_12) class Meta: ordering = ('weekday', 'from_hour') unique_together = ('weekday', 'from_hour', 'to_hour') def get_weekday_display(self): return WEEKDAYS[self.weekday][1] def get_hours_display(self): return '{} - {}'.format(HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1]) def get_start_hour_display(self): return HOUR_OF_DAY_12[self.from_hour][1] def get_end_hour_display(self): return HOUR_OF_DAY_12[self.to_hour][1] def __str__(self): return '{}: {} - {}'.format(self.get_weekday_display(), HOUR_OF_DAY_12[self.from_hour][1], HOUR_OF_DAY_12[self.to_hour][1]) I'm trying to test a model similar to how I have successfully tested other models in my application: class OpeningHours(TestCase): def create_opening_hours(self, weekday=1, from_hour=12, to_hour=15): self.location = create_location(self) return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour) def test_opening_hours(self): oh = self.create_opening_hours() self.assertTrue(isinstance(oh, OpeningHours)) self.assertTrue(0 <= oh.from_hour <= 23) self.assertTrue(0 <= oh.to_hour <= 23) self.assertTrue(1 <= oh.weekday <= 7) , but when running the test I get this error message: Traceback (most recent call last): File "<app_path>/tests.py", line 137, in test_opening_hours oh = self.create_opening_hours() File "<app_path>/tests.py", line 134, in create_opening_hours return OpeningHours.objects.create(location=self.location, weekday=weekday, from_hour=from_hour, to_hour=to_hour) AttributeError: type object 'OpeningHours' has no attribute 'objects' I assume this could have to do with the ordering or unique_together metadata, but not sure how to solve this... any pointers in the right direction very … -
Docker Wordpress/Apache behind Docker Nginx - Port Number Issue
I am having problems getting the wordpress docker image working with the nginx docker image. The python/django container works perfectly fine with nginx, but the wordpress/apache one is having problems. I can get to the django site, with https. I cannot get into the wordpress one with https. In fact, when I go to my site site.com/wp, I get back site.com:8080/wp, so for some reason it is coming back through port 8080, and not 443 or 80. I've tried setting the wordpress site as the root location / (in the default.conf file) and it still has the same problem (then I get site.com:8080). The wordpress functionality is normal, I can edit the site as usual. default.conf file for nginx disable_symlinks off; ssl_certificate xxx ssl_certificate_key xxx server { listen 80; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name site.com; location / { proxy_pass http://django:8000; #django container } location /static { alias /path/to/static; } location /wp { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_pass http://wordpress:80; #the wordpress container } } docker yml version: '3.7' services: django: restart: always build: context: . dockerfile: docker-django #django gunicorn server, python image ports: - "8000:8000" wordpress: restart: always build: context: . … -
Django UserCreationForm not Submitting
I have django site that is am currently trying to create a user creation form for. I have following all the steps but something is not happening. When I click the button in my register form it does not submit anything. I also do not see a POST message in the terminal. When I go to the admin portal I also do not see what I have submitted. Views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from .models import StudentCourses from .forms import StudentCoursesForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout def registerPage(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() context = {'form': form} return render(request, 'Courses/register.html', context) HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <h3>Register</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} </form> <button type="submit">Register</button> </body> </html> -
Django cannot show login error on the page
I am making a login page and testing it. I try to enter the wrong password and hope it can show the error message. But it seems not, it just refreshes the page, how can I show the message error? Here is my code: login.html: <!DOCTYPE html> <html> <body> <h1>Login</h1> <form method="POST" action=""> {% csrf_token%} {% for field in form %} {{ field.label }} {{ field }} {{ field.help_text }} {{ field.errors }} <br></br> {% endfor %} <input type="submit" name="LoginUser"> <a class="button" href="{% url 'home' %}"> Cancel </a> </form> {% for message in messages %} <p id='message'>{{ message }}</p> {% endfor %} <h3>Don't have an account? <a href="{% url 'register' %}">Register</a> </h3> </body> </html> view.py: class register(FormView): template_name = "showList/register.html"; form_class = CreateUserForm; def form_valid(self, form): form.save(); messages.success(self.request, "User had been created."); return redirect('login'); class LoginPage(FormView): template_name = "showList/login.html"; form_class = AuthenticationForm; def form_valid(self, form): username = form.cleaned_data['username']; password = form.cleaned_data['password']; user = authenticate(username = username, password = password); print(user) if user is not None: login(self.request, user); return redirect('home'); Thank you -
Why does my CMD prompt do nothing when I use the "python manage.py runserver" command after activating the virtual environment for my Django project
Not using a virtual environment,on my command prompt, "python manage.py command" works but when I activate the virtual environment and use "python manage.py command" it just goes to the next line without doing anything -
Django - How to turn a Page object to Json
I have this social network project for learning purposes, and I'm trying to add a pagination feature to it. I manage to successfully render all the posts in a page with JavaScript after I turn them into a JSON. The problem is that I get this error: Object of type Page is not JSON serializable when I try to paginate the posts like this: all_posts = Post.objects.all().order_by("-timestamp").all() serialized_posts = [post.serialize() for post in all_posts] paginator = Paginator(serialized_posts, 10) #every page displays up to 10 post page_obj = paginator.get_page(pagenumber) return JsonResponse(page_obj, safe=False) Here is the Post model: class Post(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="", related_name="user_post") content = models.TextField(max_length=240) likers = models.ManyToManyField(User, related_name="posts_liked") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "autor": self.autor.username, "content": self.content, "likers": [user.username for user in self.likers.all()], "timestamp": self.timestamp.strftime("%b. %d, %Y, %H:%M %p"), "autor_profile_pic": self.autor.profile_picture } Any ideas on how to work this out? -
django: Unable to get sorl-thumbnail working
I am making a django site where users can upload images and I want to use sorl-thumbnail for thumbnail generation and caching. I am using a container based workflow using podman on a fedora silverblue host. I have setup a memcached cache engine (using the memcached docker image), and can set and get values to and from the cache in django-shell with no issues. I have run the migrate command with sorl-thumbnail added to my installed-apps. I have run the ./manage.py createcachetable command and no errors. I am using pylibmc with: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } } I have created a model which has the sorl.thumbnail ImageField, although I hope to use a standard imagefield eventually, which I believe is possible. I have checked my postgres database and the thumbnail_kvstore table is created but never populated with any data. I have the following model, view, and template: model... class Image(models.Model): image_file = ImageField(upload_to=user_directory_path) #thumbnail = models.ImageField(upload_to=str(user_directory_path) + '_thumb', null=True) userprofile = models.ForeignKey(ForumProfile, on_delete=models.CASCADE, related_name="images") view...(the get function is added during debugging this issue)... class ForumProfileUploadView(LoginRequiredMixin, FormView): form_class = ImageForm template_name = 'list.html' success_url = reverse_lazy('my-view') def get(self, request, *args, **kwargs): form = self.form_class() message = … -
Getting a KeyVault secret using a GitHub secret
I'm working on an Azure sample and want to use GitHub actions to deploy this Django solution. https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=powershell%2Cclone#1-set-up-your-initial-environment This YAML works: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: "xxdjangoDemo-KV" KV_SECRET: 'SECRET-KEY' . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} # Set the name of the KEY VAULT in Azure portal from GITHUB secrets secrets: ${{ env.KV_SECRET }} # comma separated list of secret keys to fetch from key vault id: myGetSecretAction # ID for secrets that you will reference This doesn't: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: ${{ secrets.KEY_VAULT_NAME }} KV_SECRET: ${{ secrets.KEY_VAULT_SECRET_NAME }} . . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} … -
Django Rest Framework does not filter after resetting queryset
My url will be something like: ... /? Search = modal. I want to replace the "modal" with empty "" to clean the filter and return all records. Views.py class AnexoExamesViewSet(viewsets.ModelViewSet): search_fields = ['descr'] filter_backends = (filters.SearchFilter,) queryset = AnexoExames.objects.all() serializer_class = AnexoExamesSerializer def get_queryset(self): queryset = AnexoExames.objects.all() search_descr = self.request.query_params.get('search',None) print(search_descr) if search_descr=='modal': queryset = AnexoExames.objects.filter(descr='') return queryset This way it is returning zero results -
django ModelForm extra field
i will like to have extra field in modelForm. From this extra field i will like to pass the value to field in model when save. this is example what i want to get will like to generate name in random name field, and save to database as name models.py from django.db import models class Test2App(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name forms.py from django import forms from .models import test2App class TestForm(forms.ModelForm): class Meta: model = Test2App fields = ['name'] Views.py def add_name(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() return redirect('test_name') else: form = TestForm() return render(request, 'test/add.html', {'form': form}) html <form method="post"> {% csrf_token %} <label for="name">Random Name</label> <button>Generate</button> <input id="name" name="name_test"> {{ form}} <input type="submit" value="Submit"> </form> -
Django Admin Stack Inline Itself (Same Model) Indefinitely
Given the following models class File(models.Model): id = models.AutoField(primary_key=True) class Loop(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) class Segment(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey(Loop, on_delete=models.CASCADE, null=True, blank=True) I want to build a nested admin where the user can: User adds a File After adding a File, the user can either directly add a Segment or a Loop If the user directly adds Segment, well it ends there. However, if the user happens to add a Loop, he/she should have an option to again add either the Loop or Segment Something like this: File Segment Loop Segment Loop Loop Segment Segment ..... ..... I have tried the following but it apparently doesn't work. class SegmentInline(nested_admin.NestedModelAdmin): model = Segment class LoopInline(nested_admin.NestedModelAdmin): model = Loop inlines = [SegmentInline, LoopInline] class FileAdmin(nested_admin.NestedModelAdmin): model = File inlines = [SegmentInline, LoopInline] It fails with the following error: NameError: name 'LoopInline' is not defined How do I achieve this in Django Admin? Any workarounds to this? -
Does Django Channels support a synchronous long-polling consumer?
I'm using Channels v2. I want to integrate long-polling into my project. The only consumer I see in the documentation for http long polling is the AsyncHttpConsumer. The code I need to run in my handle function is not asynchronous. It connects to another device on the network using a library that is not asynchronous. From what I understand, this will cause the event loop to block, which is bad. Can I run my handler synchronously, in a thread somehow? There's a SyncConsumer, but that seems to have something to do with Web Sockets. It doesn't seem applicable to Long Polling. -
django: object count dont work for other def
I have an odd issue, countAll doesn't work for def about(request), however, if I inserted it into def home(request) it's working fine. What could be the issue? Any suggestions on why it doesn't work? def home(request): featured = Oglas.objects.order_by('-list_date').filter(is_published=True).filter(is_featured = True)[:4] regularni = Oglas.objects.order_by('-list_date').filter(is_published = True).filter(kategorija = 'prodava').filter(is_featured = False)[:5] iznajmuva = Oglas.objects.order_by('-list_date').filter(is_published = True).filter(kategorija = 'iznajmuva').filter(is_featured = False)[:5] context = { 'featured' : featured, 'regularni': regularni, 'iznajmuva': iznajmuva, } return render(request, 'pages/home.html', context) def about(request): countAll = Oglas.objects.all().count() context = { 'countAll': countAll, } return render(request, 'pages/about.html', context) html {% if countAll %} <p>Total {{ countAll }}</p> {% else %} <p>None</p> {% endif %} -
Pandas/Django - Cannot convert csv saved as filefield into dataframe
I'm building a database that stores csv files and presents them when a user selects the csv he/she wants to visualize. The problem is, whenever I open the csv file from the database the resulting dataframe is garbage models.py class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) name = models.CharField(max_length = 100) library = models.CharField(max_length = 100, null = True) def __str__(self): return "File id: {}".format(self.id) views.py def test(request): csv = Csv.objects.get(id = 5) df = pd.DataFrame(csv.file_name) print(df.head()) return render(request, 'mainproj/test.html', {'df' : df.dtypes}) Test_Data.csv A header Another header First row Second row The print statement in views.py returns the following output that I cannot even understand and the dataframe spits out odd values for things like columns, dtypes, ect... meanwhile import pandas as pd df = pd.DataFrame(pd.read_csv('Test_Data.csv')) print(df) returns the following as expected -
Django giving me an error for trying to load a static file
I am doing a simple Django website and I linked to css file in my html : <!DOCTYPE html> <html> <head> <title>Is it new year's</title> <link rel="stylesheet" href="{% static 'newyear/styles.css' %}"> </head> <body> {% if newyear %} <h1>YES</h1> {% else %} <h1>NO</h1> {% endif %} </body> </html> I created a folder called static inside my app and I created a folder called newyear inside of that one and then created my styles.css inside of it. But when I try to load the page python is giving me this error Invalid block tag on line 5: 'static'. Did you forget to register or load this tag? -
Django | Cannot access URLs without a trailing "/"
I have a Django application where, for some reason, I cannot load my URLs without a trailing "/" I have other Django applications I've made in practice where this hasn't been an issue, and I don't need one when I go to my Admin page, so I can't figure out what's setup wrong here. Here's my main URLs file: urlpatterns = [ path('app/', include('app.urls')), ] Here's my app's URLs file: urlpatterns = [ path('subapp/', views.subapp, name='subapp'), ] And my views file: def subapp(request): return render(request, 'app/subapp.html', {'title': 'subapp'}) When I enter my URL as "localhost:8000/app/subapp/" it takes me to the correct page. However, when I enter my URL as "localhost:8000/app/subapp" I get a 404 with the following debug error message: Directory indexes are not allowed here. What am I doing wrong? -
Showing value in views.py to html
So what I am trying to do is to show a value from my Views.py in my index.html. Views.py def index(request): the_uploaded_excel_file = excel_upload.objects.order_by('-id').first() excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) wb = load_workbook(excel_file_path_from_db) ws = wb["Sheet1"] df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) max_date_column = ws.max_column last_date_entered = ws.cell(row=1, column=max_date_column).value todays_date = datetime.date.today() Date_difference = pd.date_range(start= last_date_entered, end=todays_date, freq='D') print("last date entered was ") print(last_date_entered) print("todays date is ") print(todays_date) print("the days not done is") print(Date_difference) for date in Date_difference: print(date) return render(request, "index.html", { 'Date_difference': Date_difference }) Index.html <h2> {{ for date in Date_difference }} {{ date }} {{ endfor }} </h2> the problem is that when I do just {{ Date_difference }} in my index.html it show an array of the dates i want. but When i try to put them in the for loop it the page wont load. when i do {{ Date_difference }} it gives me: DatetimeIndex(['2021-01-28', '2021-01-29', '2021-01-30', '2021-01-31', '2021-02-01', '2021-02-02', '2021-02-03', '2021-02-04'], dtype='datetime64[ns]', freq='D') But when I do the for loop i get the error: Could not parse the remainder: ' date in Date_difference' from 'for date in Date_difference' -
Error at Login page - TypeError: __init__() got an unexpected keyword argument 'request'
I've successfully created a custom user using AbstractBaseUser and I'm now trying to create the login page using CBV LoginView as follows: class UserLogin(LoginView): authentication_form = UserLoginForm template_name = 'registration/login.html' I have redirected LOGIN_REDIRECT_URL as required in settings. The form I am using is as follows: class UserLoginForm(forms.Form): username = forms.CharField(label='username') password = forms.CharField(widget=forms.PasswordInput) but I keep getting thrown the error: TypeError: __init__() got an unexpected keyword argument 'request' Any ideas? I would guess it's to do with the way I have implemented the CBV but a quick explanation of what I am doing wrong would be greatly appreciated. Cheers. -
http error 405, "save" button, ManyToMany | Django
I'm trying to create a "save" button for a post in Django, however, when clicking on "save" I get a HTTP ERROR 405. models.py class Post(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) description = TextField() some_value = models.CharField(max_length=100, null=True, blank=False, unique=True) saved = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="post_save") def total_saved(self): return self.saved.count() SAVE_OPTIONS = ( ('Save', 'Save'), ('Delete', 'Delete') ) class PostSave(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=SAVE_OPTIONS, max_length=8) edited = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) views.py class PostDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): slug_field = "some_value" slug_url_kwarg = "some_value" model = Post template_name = 'post.html' permission_required = 'post.view_post' def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) post = get_object_or_404(Post, some_value=self.kwargs['some_value']) total_saved = post.total_saved() context['total_saved '] = total_saved return context @login_required(login_url='login') def save_post_view(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.saved.all(): post_obj.saved.remove(user) else: post_obj.saved.add(user) postsave, created = PostSaved.objects.get_or_create(user=user, post_id=post_id) if not created: if post_saved.value=='Save': postsave.value='Delete' else: postsave.value= 'Save' else: postsave.value='Save' licitacion_obj.save() licitacionguardada.save() return redirect('posts:search') urls.py app_name = 'posts' urlpatterns = [ path('search/', PostListView.as_view(), name='search'), path('<path:some_value>/', PostDetailView.as_view(), name='post'), path('save/', save_post_view, name='save'), ] post.html <form action="{% url 'licitacion:guardar' %}" method="POST"> {% csrf_token %} <input type="hidden" name="licitacion_id" value="{{ licitacion.id }}"> <button type="submit" class="nav-item btn btn-round btn-outline-dark" style="color: … -
python Django fill in auto-created Profile model with User registration form
I am creating an art marketplace with django. I have the registration and the auto-create signal set up for the profile. There are three types of Users who will register on this app: Artists, Patrons, and Brokers (I call these user_status.) I would like the User to choose one of these three fields on the registration form. I have gotten to the point where the reg form has the choicefield and the choices and the user can select one and the form saves to create the User and Profile, but the profile does not have a selected 'user_status' when I go in to admin. I am aware it is heavily discouraged to bundle up profile modelfields at registration, but I'd like for just this one field to be selectable since it will have a major effect on how the site will look for the user. I have read (here) that there would be a lot of annoying customization involved to properly fill profile fields at registration. Is this true? I think if there is a solution it'll be on Signals.py but am not sure. In signals.py when I type in: user_status='Patron', Can I replace the 'Patron' with something like instance.get('user_status')? … -
Get last few items and append to list with while loop
Hi I'm trying to get some data from an model with a while loop. So in the code shown below n is a number and orderMessage is the data I want to append to an list. So what the loop should do is get as many rows as the number n and append it to a list Full. orderMessage changes depending on the index i given to the filter statement. Now my question is, for ex. n = 12 so I want to get the last 12 entries from the MessageItem Model and append it to a list. How could I do that? n = CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True).last() m = MessageItem.objects.filter(customer=customer).last() i = 0 while i <= n: orderMessage = MessageItem.objects.filter(customer=customer)[i] Full = [] aFull = Full.append(orderMessage) print(Full) send = aFull print(send) i += 1 message_to_send = str(message) + str(n) + str(m) Here are the models: class MessageItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) mItem = models.CharField(max_length=255, null=True) mQuantity = models.CharField(max_length=255, null=True) mOrderItem = models.CharField(max_length=255, null=True) class CartQuantity(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) cquantity = models.IntegerField(default=0, null=True, blank=True) I hope you guys understand my english and my question. I'm very thankful for any solutions