Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect @login-required for specific pages
In Django, I have in my files: settings.py LOGIN_URL = 'login' LOGOUT_REDIRECT_URL = 'frontpage' LOGIN_REDIRECT_URL = 'myaccount' views.py @login_required() def checkout(request): cart = Cart(request) if not len(cart): return redirect('cart_view') ...more code... my question is simple... How do I set the @login_required, so that instead of the myaccount page being the redirect URL, I can send it back to checkout page? In other words, where can I override LOGIN_REDIRECT_URL when needed? Thank you, -
why is my python for loop in django return just a single value
the django views.py def quiz_automate(request): val=automate_data() # print(val['data']) get_quiz=Quiz.objects.get(subject='english',exam_type='jamb') for data in val['data']: print(data['question']) d_question=Question(text=data['question'],quiz=get_quiz) d_question.save() return HttpResponse('saved')` the scraped.py function def automate_data(): url = 'https://questions.aloc.com.ng/api/v2/m?subject=chemistry' headers = {'Accept': 'application/json','Content-Type': 'application/json'} r = requests.get(url, headers=headers) return r.json() i tried scraping data from a site and it returned multipled values but whenever i use in my django views to store in my postgres database it just store a value instead of multiple values -
Django parler: error when for same translation
I've just added django-parlel to my project and I'm wondering is it my bad or it's really impossible to have same translation more then once. Case I'm trying to add translation for Polish language for word "Sport", in polish it would be "Sport", just same as in English (which I have by default in app). When trying to add this getting error both when adding from admin panel and when loading fixture. I know that i might leave it blank and it won't really be that bad however I need to have translation for each single word. I'm assuming there is a constraint in parlel ;( Thanks in advance. Error in Admin -
Does a Django site need a Postgres database when hosting on Heroku? Can I remove the Postgres add-on?
I have a website that I built using Django and deployed on Heroku. The tutorial I followed had me set up a Heroku Postgres database attached as an add-on. After Heroku's recent pricing changes the Postgres database has gone from free to $5 / month. Maybe static isn't the correct word, but the site doesn't have user accounts, collect user information, or otherwise have any need for a database. I believe the only information that's stored in the database is login info for the Django admin site. I was able to export a .pgdmp file from Heroku of the data stored in the database but couldn't make heads or tails of the contents. Here's the settings.py file code for the database section: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) My question is can I delete this add-on from the Heroku CLI or dashboard without breaking the site in production? Would I need to change anything in my settings.py file or elsewhere in my Django code first? I assume I would still be able to access the Django admin page on the development server, is that assumption correct? Sorry … -
How to sort distinct values with respect to manytoone class in Django?
I have two models class MessageThread(models.Model): title = models.CharField(max_length=120, blank=True, null=True) created_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='created_user') belonging_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) last_message_date = models.DateTimeField(blank=True, null=True) and class Message(models.Model): thread = models.ForeignKey(MessageThread, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) comments = models.TextField(blank=True, null=True, max_length=500) create_date = models.DateTimeField(blank=True, null=True) Here, I want to get MessageThreads that are sorted by their last Messages' create_date. I tried to get sorted Messages by '-create_date' and then get distinct thread ids from that query but it doesnt work. I am using PostgreSQL. -
AttributeError: 'HttpResponse' object has no attribute 'render'
anyone know why this error is happening? i've been running the same line for my other tests and only this one is returning an error both lines in test_coverageReturnSuccess + test_coverageReturnCorrectCoverage returning this error: response.render() AttributeError: 'HttpResponse' object has no attribute 'render' This is my APi test case class CoverageTest(APITestCase): protein = None domain = None protein_domain = None good_url = '' bad_url = '' def setUp(self): self.protein = ProteinFactory.create(pk=1, protein_id='A0A014PQC0', length=338) self.domain = PfamFactory.create() self.protein_domain = ProteinDomainLinkFactory.create(protein=self.protein, pfam_id=self.domain, start=157, stop=314) # Set urls self.good_url = reverse('coverage', kwargs={'protein_id': 'A0A014PQC0'}) def tearDown(self): # Reset test tables Protein.objects.all().delete() Pfam.objects.all().delete() ProteinDomainLink.objects.all().delete() # Reset primary keys ProteinFactory.reset_sequence(0) PfamFactory.reset_sequence(0) ProteinDomainLinkFactory.reset_sequence(0) def test_coverageReturnSuccess(self): """ Ensure we get an 200 OK status code when making a valid GET request. """ response = self.client.get(self.good_url, format='json') response.render() self.assertEqual(response.status_code, 200) def test_coverageReturnCorrectCoverage(self): """ Ensure we get the right coverage of the requested protein """ response = self.client.get(self.good_url, format='json') response.render() data = json.loads(response.content) self.assertEqual(data, 0.46449704142011833) -
React MUI Checkbox set checked on false value
I am having this problem with React MUI - Checkbox component. I have the site where I have the checkbox with handler targeting to the REST API endpoint that sets the boolean flag for the user in the database on POST request and returns the boolean value for the logged user. Backend code: # Models class Client(models.Model): all_submitted = models.BooleanField(default=False, null=False) # Views @api_view(["POST", "GET"]) @permission_classes([IsAuthenticated]) def all_submitted(request): current_client = request.user.client if request.method == "GET": return Response(status=status.HTTP_200_OK, data={ "submitted": current_client.all_submitted }) elif request.method == "POST": checked = request.data['checked'] if type(checked) == bool: with transaction.atomic(): current_client.all_submitted = checked current_client.save() return Response(status=status.HTTP_200_OK, data={ "submitted": current_client.all_submitted }) and the client code: const [checked, setChecked] = useState(false); const handleChange = (event) => { api.post("/client/files", {checked: event.target.checked}).then((response) => { if (response.status === 200) { setChecked(response.data.allEvidenceSubmitted); } }) }; useEffect(() => { api.get("/client/files").then((response) => { if (response.status === 200) { setChecked(response.data.allEvidenceSubmitted); } }); }, ["checked"]) <FormGroup> <FormControlLabel labelPlacement="bottom" control={<Checkbox checked={checked} onChange={handleChange} inputProps={{'aria-label': 'controlled'}} />} label={t("checkbox", "I confirm that the documents have been completely uploaded.", {ns: "evidence"})}/> </FormGroup> Now the problem is that when the value is supposed to be false, then on page refresh, even if the false value is returned, the checkbox gets checked. Does … -
ModuleNotFoundError in Django in Vscode
from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path("", views.index, name='home'), ] This is code in urls.py file under home app. And now its giving following error: (env) abhishek@Abhisheks-MacBook-Pro hello % /Users/abhishek/Documents/django_work/env/bin/python /Users/abhishek/Do cuments/django_work/Hello/home/urls.py Traceback (most recent call last): File "/Users/abhishek/Documents/django_work/Hello/home/urls.py", line 3, in <module> from home import views ModuleNotFoundError: No module named 'home' I tried this & still not working INSTALLED_APPS = [ 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', Can anyone expain this? And also how to fix this. -
CrispyError at /login/ |as_crispy_field got passed an invalid or inexistent field
I'm working on a login form for my Django blog. I'm having a problem with crispy forms. This is login.html <div class="entry-main-content mt-50"> <!--<h1 class="mt-30">Get in touch</h1>--> <hr class="wp-block-separator is-style-wide"> <form method="post" class="form-contact comment_form" action="#" id="commentForm"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ form.username | as_crispy_field }} </div> </div> <div class="col-sm-6"> <div class="form-group"> {{ form.password | as_crispy_field }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Login</button> </div> </form> </div> This is views.py def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("home") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) This is forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user I tried to follow instructions like in this blog because I need to keep html template. Any idea how to solve this? Thanks in advance! -
Coupon code not working for items in cart
I am trying to implement a coupon code feature in my Django e-commerce website. I have added the apply_coupon method to the Order model and a coupon field to the Order model, and I have also added a coupon_code parameter to the cart view function. However, when I test the coupon code by entering it in the cart page, nothing happens and the discount is not applied. I've included the relevant code snippets below. Can someone please help me understand why the coupon code is not working and how to fix it? views.py from django.shortcuts import render from django.http import JsonResponse from django.contrib import messages import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] coupon = Coupon(code='PERMANENT', discount=0.2, active=True, valid_until=None) coupon.save() # Kupon kodu işlevini ekleyin coupon_code = request.GET.get('coupon_code', None) if coupon_code: # Eğer bir sipariş nesnesi oluşturulmuşsa kupon uygulayın if hasattr(order, 'apply_coupon'): coupon_applied = order.apply_coupon(coupon_code) if not coupon_applied: messages.warning(request, 'Geçersiz veya etkin olmayan … -
Constructor can't set property value in Python class
I encounter strange behaviour in constructor of a python class: class MetricQuery(): query = None def __init__(self, query = None): self.query = query @classmethod def sum(self, field, response_field = None): self.es_query = basic_aggregation("sum", field, response_field) return self @classmethod def get(self): output = self.es_query if self.query != None: output["query"] = self.query["query"] return output Here's the test method for sum: def test_sum(): query = {"query": {"match": {"active": True}}} assert MetricQuery(query).sum("visits").get() == {"query": {"match": {"active": True}},"aggs": {"sum_visits_field": {"sum": {"field": "visits"}}}} Test fails, saying that right contains 1 more item, "query". It seems constructor can't set query value properly. What am I missing? -
Need support, Initially Django Search page is displaying all data, while i want to have only search text boxes and display data after user input
Views.py def advance_filter(request): user_list = SarnarLogs.objects.all() user_filter = UserFilter(request.GET) return render(request, 'advance_filter.html', {'filter': user_filter}) Template: Advance_filter.html <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.source.label_tag }} {% render_field filter.form.source class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.destination.label_tag }} {% render_field filter.form.destination class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.port.label_tag }} {% render_field filter.form.port class="searchfield" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.request_no.label_tag }} {% render_field filter.form.request_no class="searchfield" %} </div> </div> <button type="submit" class="btn btn-primary" placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form><br> <div class="col-12"> <div class="card my-4"> <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2"> <div class="bg-gradient-primary shadow-primary border-radius-lg pt-4 pb-3"> <h6 class="text-white text-capitalize ps-3">HUB Requests</h6> </div> </div> <div class="card-body px-0 pb-2"> <div class="table-responsive p-0"> <table class="table align-items-center mb-0"> <thead> <tr> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">ID</th> <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">SOURCE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">DESTINATION</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">PORT</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST TYPE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST_NO</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUESTER</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">START DATE</th> <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">EXPIRY DATE</th> <th class="text-center … -
How to 'check' a value in a radio button by default in Django?
I wrote a model form. I used widgets to make radio buttons and I want a particular radio button to be checked by default while rendering the form in my html file. Model: class Room(models.Model): class Meta: number = models.PositiveSmallIntegerField() CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.CharField(max_length=30) The following is my model form based on the above model. Form: class AddRoomForm(forms.ModelForm): ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CATEGORIES), ) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = forms.CharField( max_length=9, widget=forms.RadioSelect(choices=ROOM_CAPACITY), ) class Meta: model = Room fields = ['number', 'category', 'capacity', 'advance'] Here is the views: def add_room(request): if request. Method == 'POST': form = AddRoomForm(request.POST) if form.is_valid(): room = Room(number=request.POST['number'], category=request.POST['category'], capacity=request.POST['capacity'], advance=request.POST['advance'], manager=request.user.username) room.save() # Implemented Post/Redirect/Get. return redirect('../rooms/') else: context = { 'form': form, 'username': request.user.username } return render(request, 'add_room.html', context) context = { 'form': AddRoomForm(), 'username': request.user.username } return render(request, 'add_room.html', context) I rendered the form like this in my … -
Deployment fails without prompting any errors on console on digitalocean app-engine django app
We have 2 apps that are running with similar settings, now we are trying to deploy another app but this time it's failing without telling any error in app engine. Python django app starts and then suddenly app engine stops deployment. How to find reason behind that? -
Django logging does not work inside views and viewsets
Can someone please help me understand why django does not print logging messages that I put inside views methods? When I call logger.debug() from outside views it works correctly my views.py import logging logger = logging.getLogger(__name__) logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS') class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated,) serializer_class = serializers.RequestGetResultSerializer queryset = Request.objects.all() def get_queryset(self):] logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') return self.queryset.filter(user=self.request.user.id) @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,)) def download(self, *args, **kwargs): logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP') # working code here return response my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG' , }, 'loggers': { 'django': { 'handlers': ['console'], }, } -
Hello everyone, help me write a test to Check if a post has been removed from the old group
You need to check that the post has disappeared from the old group page. You get our old band by its slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And you compare, что old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. You can check another new one, that there is 1 post there. Please help me write correctly) from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) I know what rubbish is written here (I'm just learning), this is what I was able to sketch)) -
Django: create_user_profile() missing 1 required positional argument: 'self'
I want to change the user's password. For this I use the following code user = User.objects.get(id=kwargs.get('user_id')) user.set_password(kwargs.get('password')) user.save() I get an error in response create_user_profile() missing 1 required positional argument: 'self' But I don't create a user. I checked, it finds the right user -
Styling prefilled Django radio input as buttons
I have a Django form field that is prefilled({form.clothingType}) and using widget gave it the attribute of class="closet-form-section form-clothing-type". The form is rendered out in html as <div id="id_clothingType" class="closet-form-section form-clothing-type"> <div> <label for="id_clothingType_0"><input type="radio" name="clothingType" value="11" class="closet-form-section form-clothing-type" required="" id="id_clothingType_0"> Accessory</label> </div> <div> <label for="id_clothingType_1"><input type="radio" name="clothingType" value="12" class="closet-form-section form-clothing-type" required="" id="id_clothingType_1"> Top</label> </div> <div> <label for="id_clothingType_2"><input type="radio" name="clothingType" value="13" class="closet-form-section form-clothing-type" required="" id="id_clothingType_2"> Outerwear</label> </div> <div> <label for="id_clothingType_3"><input type="radio" name="clothingType" value="14" class="closet-form-section form-clothing-type" required="" id="id_clothingType_3"> Bottom</label> </div> <div> <label for="id_clothingType_4"><input type="radio" name="clothingType" value="15" class="closet-form-section form-clothing-type" required="" id="id_clothingType_4" checked> Shoe</label> </div> </div> My question is how do I style the radio inputs as buttons such that it changes its background color when it is checked without changing the html (form template)? Is there an alternative solution via widget, views.py of even models.py? Thank you! The problem is that the input is within the labels, so I am unable use the conventional way of the input:checked + label to style the radio inputs. In this case the 5th radio button(Shoe) should have a different background color as the others. -
Docker/Django/Gunicorn/Nginx Websockets not connecting
Dockerized Django chat app using gunicorn, nginx for reverse proxy (static files). I managed to get stuck trying to get the websockets to work, but I can't connect to daphne: daphne -p 8001 project.asgi:application. The app only says, "Connection refusesed for upstream localhost:8001". I'm using django-channels and redis and on local everything is working fine. Am I missing something? Here are some files: nginx.conf upstream project { server web:8000; } upstream websocket { server localhost:8001; } server { listen 80; location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } } asgi.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack import scrumboard.routing application = ProtocolTypeRouter({ "http": django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( scrumboard.routing.websocket_urlpatterns ) ) }) settings.py """ Django settings for project project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib … -
Script JS only working on HTML page , is there a way to make it work and include the path to HTML?
I have an issue where I have a html 'p' tags where it should applies a javascript function. It is an animated typing script , however it doesn't seems to be working. The script only works if I put it below the html 'P' tags. <link href="{% static 'js/animation.js' %}" rel="stylesheet"/> <!--test active type writing animation--> <div class="container-animation"> <p id="p_type">I'm <span class="typed-text"></span><span class="cursor">&nbsp;</span></p> </div> <!-- To check , how to implement the script in js file and why it isn't working and only working--> <script> const typedTextSpan = document.querySelector(".typed-text"); const cursorSpan = document.querySelector(".cursor"); const textArray = ["a Data Analyst", "a Developer", "Henry Dumont"]; const typingDelay = 100; const erasingDelay = 100; const newTextDelay = 2000; // Delay between current and next text let textArrayIndex = 0; let charIndex = 0; function type() { if (charIndex < textArray[textArrayIndex].length) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent += textArray[textArrayIndex].charAt(charIndex); charIndex++; setTimeout(type, typingDelay); } else { cursorSpan.classList.remove("typing"); setTimeout(erase, newTextDelay); } } function erase() { if (charIndex > 0) { if(!cursorSpan.classList.contains("typing")) cursorSpan.classList.add("typing"); typedTextSpan.textContent = textArray[textArrayIndex].substring(0, charIndex-1); charIndex--; setTimeout(erase, erasingDelay); } else { cursorSpan.classList.remove("typing"); textArrayIndex++; if(textArrayIndex>=textArray.length) textArrayIndex=0; setTimeout(type, typingDelay + 1100); } } document.addEventListener("DOMContentLoaded", function() { // On DOM Load initiate the effect if(textArray.length) setTimeout(type, newTextDelay + 250); }); … -
Django rest framework - restricting user from granting himself permission
I have a django-program that has a few number of different permission levels. For example, I have a super-user, a doctor, an assistant and a patient. I have a class AssistantViewSet(ModelViewSet) which allows to change an assistant user. I just found out that an assistant might go directly to the link that corresponds to that ModelViewSet with method PUT (which is a resonable behavior as an assistant can change their own information), and change their permissions by sending a permission_list key with many permissions they shouldn't have. how can I make sure that an assistant will be able to change their information without having the ability to change their permissions? my code: class AssistantViewSet(ModelViewSet): serializer_class = AssistantSerializer queryset = Assistant.objects.all() permission_classes = [AssistantViewPerm, ] def get_queryset(self): assistants = Assistant.objects.filter(...) return assistants and the permission class: class AssistantViewPerm(BasePermission): def has_permission(self, request, view): action = view_action_map(request) try: if action == 'update': ... except: ... return checkBasicPerms(...) and checkViewPerm(...) -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'
I am working on a Django chat application using Django channels but I have run into a problem. I am getting the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User' in my console and I cannot figure out how to solve this issue. In my project, I am checking whether users have an history in their chat, and if there is no history I create one. Inside the users app where I am registering users, I have used the AbstractUser model and therefore I have AUTH_USER_MODEL='users.User' inside the setting.py. Here is my Models.py for the chat application: from django.contrib.auth import get_user_model from django.conf import settings User = get_user_model() class TrackingModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='personal') users = models.ManyToManyField('users.User') objects = ThreadManager() def __str__(self) -> str: if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('users.User', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) def __str__(self) -> str: return f'From <Thread - {self.thread}>' And here is the Managers.py file: User = get_user_model() … -
Not use Django static files
I am quite new to Django, and I hope my question is not too silly. I am currently running my project locally, and each time I do an API call with the browser, I see the server log something similar: my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/css/default.css HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/jquery-3.5.1.min.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 179 my_table | [08/Jan/2023 20:20:42] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 404 179 There are a tons of static files that are served via the API. If I do the same with Postman or similar, here is the log: my_table | [08/Jan/2023 20:25:12] "GET /api/v1/category/ HTTP/1.1" 200 2 It looks like it only sends the response I wanted, via JSON or whatever. I was wandering if there is a way to prevent Django from serving static files at all, since I will only use the Rest Framework, or maybe gRPC in the future, but never static files. I tried to delete the static file constant from settings, and then nothing … -
Use node module in django
I'm trying to use nodejs modules (lodash) inside of my Django app but nothing happen. The architecture is as follow: - myproject - dist - myapp - templates - index.html - apps.py - views.py - ... - myproject - settings.py - urls.py - ... - nodes_module - static - js - script.js - manage.py - package.json I edited my settings.py so nodes_module/ is considered as static: STATIC_URL = "/static/" STATIC_ROOT = 'dist/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ('node_modules', os.path.join(BASE_DIR, 'node_modules/')), ) And here is the content of my index.html: hello <div id="result"></div> <script>console.log("yolo")</script> <!-- This should write "2 4 6 8 10" on console and page but doesn't --> {% load static %} <script src="{% static 'node_modules/lodash/lodash.js' %}"> import _ from 'lodash'; console.log("yolo2") const array = [1, 2, 3, 4, 5]; const doubled = _.map(array, function(n) {return n * 2;}); const resultElement = document.getElementById('result'); resultElement.innerHTML = doubled; console.log(doubled); </script> I got a lot of errors while trying but now, with this architecture and code, I don't have errors anymore but nothing appear on my page except the "hello". For some reasons, the first console.log("yolo") does appear on the console but not the second one console.log("yolo2"). It's like it never went … -
How can I add related models on the form at the same time?
I need your help with something. I'm new to the software field. I would like to consult you on an issue that I am stuck with. I don't know much about Django docs. My English is not very good. My problem is that I have two models, Boat model and Features model, I assigned a foreignkey to the features model and associated it with the boat model. I created two forms for these models. Features Model Boat Model BoatForm FeaturesForm I need to save the form at the same time in the views, but I can't assign the foreign key. In summary, while adding a new boat, I need to save its features at the same time. Sorry if the English pronunciations are wrong.