Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multi project user management
I want to learn is there a way to keep django multi project and authenticate/authorize them with one project? For example: I have Project-B and Project-C with different operation fields like hotel automation and gas station. Both of them are my products and I want to manage them by keep licences and users in one place, in other words different project, Project-A. In Project-B and Project-C has it's own apps and apps' models so I don't want to merge them in one project, I want to keep them separate. But I want authorize/authenticate users from one place Project-A. So Project-A will be used only for management. I am planning to use OAuth toolkit for it, but in the first place I have another problem. Project-B and Project-C's apps' models have foreign key fields and many to many fields that defined in Project-A like customer itself. Authentication can be solved Rest Framework and OAuth2 I think but I don't have a solution for this problem. Can you help me out? Thanks in advance. -
Django access related items in template
Please help me I’m stuck in understanding how Django ORM works. Here is my very simple models: class Department(models.Model): title = models.CharField(max_length=50) class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.PROTECT) I want a template that looks like: Department 1 Employee 1 Employee 2 Department 2 Employee 3 Employee 4 But I can’t figure out what I should do in my view and(or) template -
how to display images in templates while using django wagtail
I have the codes below: models.py class BlogImagePage(Page): feature_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) body = RichTextField(blank=True) excerpt = models.TextField(blank=True) thumbnail_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) content_panels = [ FieldPanel('title'), FieldPanel('body', classname='full'), FieldPanel('excerpt'), ImageChooserPanel('feature_image'), ImageChooserPanel('thumbnail_image'), ] class BlogPageIndex(Page): content_panels = [ FieldPanel("title"), ] class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] using wagtail admin I am able to create an instance of the table BlogImagePage. Now i am trying to display the image field in the BlogPageIndex page: blog_page_index.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2> {{ post.specific.body|richtext }} {% endfor %} {% endblock %} It does show/render the instance with the title but unfortunately i am not able to render/display the image saved either on the page above or the detail page of BlogImagePage instance that has the code below blog_image_page.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a … -
How to deploy a Django backend and Flutter frontend web app
I've been working on a web application that uses Django REST Framework and Django channels in the backend and has a Flutter frontend. It works successfully when tested locally, but my question was how would I deploy this: What server is most appropriate for this application? (it should be free as this is just a personal project I've been testing) Do I need to deploy the frontend and backend separately? Are there any online resources I can refer to, to help me in this process? Any help is appreciated :) -
Django get user data in main template
I'm trying to check if user logged in in the main template using this: {%if request.user%} ... {%endif%} but it's not working maybe because main template doesn't have a view could any one help i don't know if the question duplicated,but i didn't find my answer. -
How can we specify organization level permissions using Django Rest Framework
I am new to Django authentication and Authorisation , we have a login and signup implemented with ReactJS on the client side and the Django JWT authentication on the server side. Now, I want to take this to next level by adding authorisation aswell by making users from same organizations only must be able to view/read/write the data existing in the application. Every user will be identified using a specific domain name ex: @gmail.com,@xyz.com. Users from one domain must not have any access to the database of the other organizations. I think we can achieve this with Permissions concept in Django but dont know how we can do it technically. Any ideas are well appreciated. Thanks -
django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails
from django.db import models from django.contrib.auth.models import User Previously my models was like this . class Login(models.Model): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Then i changed to like this to inherit from base admin user model. class Login(User): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Now when i am running makemigrations and migrate getting below error . File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`baby`.`#sql-16a7_6a`, CONSTRAINT `api_login_user_ptr_id_7f748092_fk_auth_user_id` FOREIGN KEY (`user_ptr_id`) REFERENCES `auth_user` (`id`))') Please take a look. How can i solve this problem safely. Because i have data in my database and login table is foreign key for many tables. -
Move Authentication error in django crispy form
I created a login page using django authentication system. The validation errors are showing good, but I don´t know how to manipulate location for my error messages within my LoginForm layout. I attached where I need to displace my message message displacement forms.py class LoginForm(AuthenticationForm): remember_me = forms.BooleanField(required=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "id-authenticationForm" self.helper.form_class = "form-signin" self.helper.form_method = "post" self.helper.form_action = "login" self.helper.layout = Layout( HTML("""{% load static %}<img class="mb-4" src="{% static 'images/logo.jpg' %}" > <h1 class="h3 mb-3 fw-normal">Please sign in</h1>"""), FloatingField("username", "password"), Div( Div( Div("remember_me", css_class="checkbox mb-3"),css_class="col"), Div(HTML("<p><a href='{% url 'password_reset' %}'>Lost password?</a></p>"),css_class="col"), css_class="row" ), Submit('submit', 'Sign in', css_class="w-100 btn btn-lg btn-primary"), HTML("""<p class="mt-5 mb-3 text-muted">&copy; 2022 all rights deserved</p>""") ) login.html.py {% extends "blog/base.html" %}{% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} views.py def custom_login(request, user, backend=None): """ modificated generic.auth login. Send signal with extra parameter: previous [session_key] """ # get previous seesion_key for signal prev_session_key = request.session.session_key #send extra argument prev_session_key user_logged_in.send(sender=user.__class__, request=request, user=user, prev_session_key=prev_session_key) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): super().form_valid(form) """Security check complete. Log the user in.""" #changed default login custom_login(self.request, form.get_user()) #get remember me data from cleaned_data of … -
Unable to call django view using ajax
I want to call the django view from client side that will display all the messages from the models on the html page AJAX function <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/load_with_room_name/{{room_name}}/", success: function(response){ console.log(response); $("#display").empty(); }, error: function(response){ alert('An error occured') } }); },1000); }) </script> django view function def load_with_room_name(request,room_name): try: current_user = Account.objects.get(email=str(request.user)) chat_room = ChatRoom.objects.get(room_name=room_name) if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user: print(current_user) return redirect('room',room_name,current_user.username) else: return redirect('chat') except Exception as e: log_exception(request,e,view_name="load_with_room_name") return render(request,"error.html") django urlpattern for the above view urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'), ] -
Angular 12 - I get data from backend to component but it doesn't show on my HTML View
Since yesterday I am trying to understand what I did wrong. I want to pass data from my django backend to my frontend angular. Supposedly, backend is sending data. I can see it by this command: [18/Mar/2022 11:41:46] "GET /list-users/ HTTP/1.1" 200 82 My front end is making the request, and my backend is responding aswell. Also, I can see the results by a console.log here: Array(5) [ "admin@lab.com", "lab@lab.com", "lab2@lab.com", "lab3@lab.com", "lab4@lab.com" ] 0: "admin@lab.com" 1: "lab@lab.com" 2: "lab2@lab.com" 3: "lab3@lab.com" 4: "lab4@lab.com" length: 5 <prototype>: Array [] main.js:164:80 I guess, everything is right until now. This is my component code, and my html component code. import {Component, OnInit} from '@angular/core'; import { SharedService } from 'app/shared.service'; @Component({ selector: 'app-regular', templateUrl: './regular.component.html', styles: [] }) export class RegularComponent implements OnInit { userlists: any; constructor(private service: SharedService) { } ngOnInit() { this.getUserlist(); } getUserlist() { let observable = this.service.getUsersList(); observable.subscribe((data) => { this.userlists = data; console.log(data); return data; }); } } html component <div class="card main-card mb-3"> <div class="card-header"> </div> <table class="table table-striped"> <thead> <tr> <th scope="col">No.</th> <th scope="col">Date</th> <th scope="col">Patient Code</th> <th scope="col">Status</th> </tr> </thead> <tbody> <tr *ngFor="let user of userlists"> <td>{{user.email}}</td> … -
How to get table data based on id which obtains from another table data? Django
Views company = Company.objects.get(id = company_id) # getting input from django urls (<int:company_id>) vehicles = CompanyContainVehicles.objects.filter(company_id=company.id) # Give all rows having same id (company.id) all_vehicles = Vehicles.objects.filter(id=vehicles.vehicle_id) # Not Working How do I get data from tables whose multiple id's obtained by another table? Models class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) description = models.TextField() class Vehicles(models.Model): id = models.AutoField(primary_key=True) vehicle_number = models.IntegerField() name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) class CompanyContainVehicles(models.Model): id = models.AutoField(primary_key=True) company_id = models.ForeignKey(Company, on_delete=models.CASCADE) vehicle_id = models.ForeignKey(Vehicles, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) Above are my table details and I need to get all vehicles from table Vehicles which is obtained from CompanyContainVehicle table (that define which company seel out which vehicle) based on company_id that obtain from table Company which contains details of companies. -
allauth tests return errors
For changing things like translations in forms i included allauth app directly in my project but now when i want to run tests it returns lots of errors i think it runs every test while i am not using social logins it tests it and fails my project on Github : github.com/MrHamedi/VSC/tree/dev Shall i delete allauth test to resolve this problem ? or what should i do so allauth tests only test allauth.account tests -
superuser authenticate in class based view
I am working on blog project in which I added an add post which add post now I want only the superuser can add post and that page is visible only to superuser. 1st Method Views.py class AddPostView(CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' this is my current view I am able to achieve authenticate for superuser using 2nd method 2nd Method class AddPostView(View): def get(self,request): if request.user.is_superuser == True: return render(...) else: pass How can I achieve the same result using 1st method.I tried using LoginRequiredMixin but nothing is happening . I just import LoginRequiredMixin and use it like this . class Addpost(CreateView,LoginRequiredMixin): ... Thanks in advance and advice will be helpful. -
Django, DRF: two similar models views, separate endpoints or not
There are two similar models as shown below. class ProductVideo(models.Model): ... class UserVideo(models.Model): ... Should it be handled dynamically with query_params in one View? # /videos/:id/comment?product=1 class CommentView(generics.CreateAPIView): def get_serializer_class(self): s = self.request.query_params.get("product") if s: return ProductVideoSerializer else: return UserVideoSerializer Or should I create one View at a time? # /videos/product/:id/comment class ProductVideoCommentView(generics.CreateAPIView): ... # /videos/user/:id/comment class UserVideoCommentView(generics.CreateAPIView): ... -
Celerybeat Multiple schedules of the same task
I got following Celery beat task which cleans 1000 items daily at 1 AM: from celery.schedules import crontab from .celery import app as celery_app celery_app.conf.beat_schedule['maintenance'] = { 'task': 'my_app.tasks.maintenance', 'schedule': crontab(hour=1, minute=0), 'args': (1000,) } I want to clean additional 5000 items every Sunday at 5PM. Is there a way to add second schedule? 'schedule': crontab(hour=17, minute=0, day_of_week='sunday'), 'args': (5000,) And how to ensure they won't overlap? -
Local chat on machine used for Outline VPN
I have a remote Ubuntu server on Linode. I use it to provide Outline VPN for me and my friends. Can I somehow create a web chat on this machine so that only users connected by Outline can use it? I tried to run django local server on it, but I couldn't connect. -
Inconsistance between `request.user` and `request.session` in Django
I do understand that login() will attach User to request.session and request.user after authenticate() successfully validate credentials. I am wondering will there be any occasions where request.user becomes anonymous user and request.session still has User attached ? I encountered this myself. If answer to above is yes, then when request.user.is_authenticated == False, should we flush the existing session, and prompt for login again to avoid someone use previously stored session. or we can directly attach user in request.session to request.user to make it logged_in user. thanks for your insights. -
AttributeError: 'JSONParser' object has no attribute 'parser'
when i post data from postman application then this error is accour code elif request.method == 'POST': data = JSONParser().parser(request) serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) **error ** data = JSONParser().parser(request) AttributeError: 'JSONParser' object has no attribute 'parser' -
Django. ImportError: attempted relative import beyond top-level package
I'm a newbie. And I just started writing a django project. It is called the iRayProject and consists of two applications iRay_user_authentication and iRay_working_with_notes: project structure here iRay_user_authentication - this is a standard django app for registration Here is his urls.py from django.urls import path from .views import login_user, registration urlpatterns = [ path('', login_user, name='login_user'), path('registration', registration, name='registration'), ] In views.py registered user using redirect I want to send to the second application of the project from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login, logout, authenticate from ..iRay_working_with_notes.views import list_notes def login_user(request): if request.method == 'GET': return render(request, 'iRay_user_authentication/login.html', {'form': AuthenticationForm}) def registration(request): if request.method == 'GET': return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm}) else: if '_guest' in request.POST: pass else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect(list_notes) except IntegrityError: return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm, 'error': 'name is busy ' }) else: return render(request, 'todo_app/registration.html', {'form': UserCreationForm, 'error': 'passwords not math'}) But when trying to import a function from the second views.py from django.shortcuts import render def list_notes(request): return render(request, 'iRay_working_with_notes/list_notes.html') I get an error: ImportError: attempted relative import beyond … -
Run Django with Nginx Web SERVER 502 Bad Gateway
How to fix issue 502 Bad Gateway nginx/1.18.0 (Ubuntu) for running Django? Nginx error log: *29 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, s> 2022/03/18 15:33:51 [error] 890#890: *13 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x,> 2022/03/18 15:42:18 [error] 1976#1976: *2 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, > 2022/03/18 15:43:10 [error] 1976#1976: *2 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, > 2022/03/18 15:44:35 [error] 1976#1976: *7 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x> -
Django - implementation of last changes tracker in HTML file
I am looking for a solution that will allow me to create a section in my HTML file with the latest updates in my app. I checked some packages here on djangopackages.org but I am not quite sure which app should I use. The idea is that if there will be any article added or updated then in the latest updates section the information will appear automatically as: '5 new articles have been recently added' or '2 articles have been updated' or'3 users joined our website'. In total, I have 4 models (including the user model) in my Django app that I want to track and display updates in my HTML (homepage, TemplateView) file. What would you recommend? -
'somewhere' gives error : No module named 'where' for my django app
When I import handle_uploaded_file from 'somewhere library on my linux machine.) getting following error when trying to run my django application.)- -
Unable to complete paypal transaction - Python Django - Was not able to redirect back to webapp to perform capture
We have implemented django oscar to include paypal recurring payment. On sandbox, everything works on well. Here is the flow we have implemented but can never get to step 3 and stuck in step 2 after "Agree & Continue" (which basically authorize the card). Call SetExpressCheckout, setting up the billing agreement in the request [L_BILLINGTYPE0=RecurringPayments]. Returns a token, which identifies the transaction, to the merchant. Redirect buyer's browser to: https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout appended with the token returned by SetExpressCheckout. Displays login page and allows buyer to select payment options and shipping address. <--- stuck here Redirect buyer's browser to returnURL passed to SetExpressCheckout if buyer agrees to payment description. Call CreateRecurringPaymentsProfile in the background (without further actions from the user). Returns ProfileID in CreateRecurringPaymentsProfile response for the successfully created profile (PROFILEID=I-1NNDL8LGNX35). Display successful transaction page (Thank you page). Listen to PayPal IPN notifications to trigger merchant's server logic for future successful/failed/canceled/suspended payments. So in step 2, when I click "Agree & Continue", it has a spinner processing, I can see then on my phone my credit card is charged. But then, nothing happens, it doesnt redirect, so it stays the same. When I click again "Agree & Continue", it then has "Sorry, … -
Can you deploy django apps though shinny server
I want to deploy a django application but the server it's to be deployed in is currently hosting several other r applications. Is there a way to configure shiny-server to serve the django app? My knowledge of r is very limited and nobody knows how the server was set up and configured -
Who to manage changing url while handling old url
I have a url Ex /this-is-url-12334 Now I want to change this url to Ex /this-is-url But I don't want that any old url to show 404 what I want that if anyone who use old url should redirect to new url What approach should I take