Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django IntegerField min length numbers
MinValueValidator How can i define the min length of the IntegerField? nummer = models.IntegerField( unique=True, validators=[MaxValueValidator(99999999), MinValueValidator(00000001), ]) Error Message: SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers -
Recommendation for the creation of a complex web application
My goal is to create a complex and modern web application, however, it has been three years since I last developed. I was using Spring API REST for the backend and React for the frontend at the time. Are there any other more interesting choices for you to consider? I heard about Django for the backend, what do you think? I would like to have a frontend that allows me to create a lot of interaction with the user (React?). A backend that allows to provide APIs usable by the frontend. -
How can i get username througth queryset?
I have some model: class Comments(models.Model): user = models.ForeignKey(User, related_name='user_comment', on_delete=models.CASCADE) heading = models.CharField(max_length=100) score = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(5)]) text = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.heading And i when make .get request in shell: Comments.objects.get(pk=1).user I get: <User: user9> But when i make that request: Comments.objects.filter(pk=1).values('user') I get: <QuerySet [{'user': 9}]> For some reason, in the queryset I get only id, but not username. Due to the peculiarities of my application, I need to use exactly .filter or .all (), so I must somehow get the username in the queryset. Please help me. -
How to use filter method for user model in another model (django)
I have a custom user model : # accounts > models.py > ... class MyUser(AbstractUser): ... fallowing_tags = models.ManyToManyField('posts.tag', blank=True) and i want to filter all users who fallowed a specefic tag: from accounts.models import MyUser as User # ---- or ----- from django.contrib.auth import get_user_model User = get_user_model() class Tag(models.Model): name = models.SlugField(max_length=50, unique=True) @property def fallowers(self): return User.objects.filter(fallowing_tags=self) But the program gives an error: File "~/path/to/blog/accounts/models.py", line 13, in <module> from posts.models import Tag, Post File "~/path/to/blog/posts/models.py", line 3, in <module> from accounts.models import MyUser as User ImportError: cannot import name 'MyUser' from partially initialized module 'accounts.models' (most likely due to a circular import) (~/path/to/blog/accounts/models.py) -
What are the default expiry time for Access Token and Refresh Token? (Django GraphQL JWT)
I use Django GraphQL JWT. Then, I could set the expiry time for Access Token and Refresh Token in "settings.py" as shown below: # "settings.py" from datetime import timedelta GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, "JWT_EXPIRATION_DELTA": timedelta(minutes=60), # For "Access Token" "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=180), # For "Refresh Token" } Now, I want to ask: What are the default expiry time for Access Token and Refresh Token in Django GraphQL JWT? -
How do I create range slider in django?
I want this type of slider in django I have searched a lot but I am not getting this particular slider, any help would be appreciated. -
django - nothing under added model
What i am trying to tackle is best shown in pics , enter image description here Whenever I try to click on View others to see everything in the Recently added genre it leads to the following page enter image description here What am i doing wrong? to make reading shorter for you guys - movie_category is what I am trying to access here movie\urls.py from django.urls import path from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear app_name = 'movie' urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('category/<str:category>', MovieCategory.as_view(), name='movie_category'), path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'), path('search/', MovieSearch.as_view(), name='movie_search'), path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('year/<int:year>', MovieYear.as_view(), name='movie_year'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.dates import YearArchiveView from .models import Movie, MovieLinks # Create your views here. class HomeView(ListView): model = Movie template_name = 'movie/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['top_rated'] = Movie.objects.filter(status='TR') context['most_watched'] = Movie.objects.filter(status='MW') context['recently_added'] = Movie.objects.filter(status='RA') return context class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category = self.kwargs['category'] return Movie.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(MovieCategory, self).get_context_data(**kwargs) context['movie_category'] = self.category return context Models.py STATUS_CHOICES = ( ('RA', 'RECENTLY ADDED'), ('MW', 'MOST WATCHED'), ('TR', 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = … -
django.core.exceptions.ValidationError: ['“None” is not a valid UUID.']
i'm trying to develop my app to heroku and i have this error: I'm trying to delete database, or connect with AWS RDS, but still this error stops me. I was trying some --fake migrations, or delete migrations files but there is other errors. Now i'm go back to first version and hope to find the solution. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(max_length=50, blank=True, null=True, unique=True) location = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, blank=True, null=True) short_intro = models.CharField(max_length=250, blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profile_images/", ) social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) draft_teams = models.ManyToManyField("Team", blank=True, related_name="draft_teams") id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) def __str__(self): return str(self.username) class Meta: ordering = ["created"] And error: Operations to perform: Apply all migrations: admin, auth, contenttypes, fifa_draft, sessions, users Running migrations: Applying fifa_draft.0001_initial...Traceback (most recent call last): File "/home/x/Desktop/projekty/draft_fifa/venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2614, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.8/uuid.py", line 168, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'Profile' object has no attribute 'replace' During handling of the above exception, another exception … -
Can't create Django superuser due to "TypeError: initializer for ctype 'wchar_t' must be a unicode string of length 1, not int"
I am trying to setup something with Django 2.0.7. I am following this [tutorial][1] and am trying to create a superuser in Django. This is what happened: (venv) PS C:\Users\testuser\Development\Projekte\diwa_portal2\src> python manage.py createsuperuser Username (leave blank to use 'testuser'): Email address: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 87, in execute return super().execute(*args, **options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 171, in handle password = getpass.getpass() File "C:\Users\testuser\Tools\WPy64-38120\pypy3.8-v7.3.7-win64\Lib\getpass.py", line 103, in win_getpass msvcrt.putwch(c) File "C:\Users\testuser\Tools\WPy64-38120\pypy3.8-v7.3.7-win64\Lib\msvcrt.py", line 112, in putwch _lib._putwch(ord(ch)) TypeError: initializer for ctype 'wchar_t' must be a unicode string of length 1, not int``` Thanks in advance! [1]: https://youtu.be/F5mRW0jo-U4 -
is there any way i can install Stack Overflow RichTextEditor for my Django project
Is there any way i can install Stack Overflow RichTextEditor for my django project. The Stack Overflow RichTextEditor is a mobile friendly and the visitors of my website are using their Mobile phones to add post. And they are complaining on my RichTextEditor for not being mobile friendly also or is there anyway i can style ckeditor to look like Stack Overflow RichTextEditor ?. my model: from ckeditor.fields import RichTextField class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) my settings.py file: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 100, 'width': 200, }, } my template: <div class="container"> <div class="row justify-content-center"> <div class="col-md-5"> {% load crispy_forms_tags %} <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <br> <input type="submit" value="submit" class="btn btn-warning"> </div> </div> </form> </div> -
FieldError Cannot resolve keyword: Django blog likebutton dosent work
am having problems i implemented my like button it shows up on the blog post sites when you click in to read more, but when you click on like i get a error msg below: I want the like button to work to add a like and also remove the like after if you feel like it. I also want it to count the number of likes. Any help with this will be very appreciated! folder newsapp views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'main.html', context) @login_required def like_post(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.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': … -
Can't migrate models to MySQL
Makemigrations and migrate commands work fine and they create files in 'migrations' folder (migration commands). But MySQL db does not change(MySQL screen). 0001_initial.py Code: from django.db import models class Student(models.Model): student_id = models.AutoField(primary_key=True) student_name = models.CharField(max_length=100) grade = models.IntegerField() class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) -
No type registered for model:
When I start the server and go to the GraphQL API. It shows me the exception - Model type not registered: UserAgreementAssociation. Someone will advise? mutations.py from graphene_django.forms.mutation import DjangoModelFormMutation from agreement.forms import UserAgreementAssociationForm, class CreateUserAgreementAssociationMutation(DjangoModelFormMutation): class Meta: form_class = UserAgreementAssociationForm forms.py from django import forms from agreement.models import UserAgreementAssociation class UserAgreementAssociationForm(forms.ModelForm): class Meta: model = UserAgreementAssociation fields = ('user', 'agreement', 'active',) models.py class UserAgreementAssociation(models.Model): user = models.ForeignKey(CloudTowerBaseUser , related_name='user', on_delete=models.CASCADE) agreement = models.ForeignKey(BaseAgreement, related_name='agreement_associations', on_delete=models.CASCADE) active = models.BooleanField(default=True) date_create = models.DateTimeField(auto_now_add=True, editable=False, blank=True) def __str__(self): return f'{self.date_create}/{self.user}/{self.agreement}' -
Why am I sometimes logged out of Django Admin?
Since the deployment of my Django website on Digitalocean with Nginx and Gunicorn I have the problem that I either can not log in to the admin panel and he jumps on the registration form again and again or when I am logged in, then only very briefly and then he jumps back again. In between, he also shows the error "Too many redirects" Nginx Config -
Cant upload pictures in django forms
I'm just getting started with Django and encountered the first problem that I can't solve. From the admin level, photos can be uploaded, but from the form on the website it is impossible. The only picture that can be uploaded is the default picture I set in the models file. If I delete the default picture from models and upload the photo from the form, an error pops up. Here are some of my files: models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) publish_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to='images/', blank=True, null=True, default='images/user.jpg') def publish(self): self.publish_date = timezone.now() self.save() def __str__(self): return self.title forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'image'] views.py: class Image(TemplateView): form = PostForm template_name = 'blog/image.html' def post(self, request, *args, **kwargs): form = PostForm(request.POST, request.FILES) if form.is_valid(): obj = form.save() return HttpResponseRedirect(reverse_lazy('image_display', kwargs={'pk': obj.id})) context = self.get_context_data(form=form) return self.render_to_response(context) def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) class ImageDisplay(DetailView): model = Post template_name = 'blog/image_display.html' context_object_name = 'image' def post_list(request): posts = Post.objects.filter(publish_date__lte=timezone.now()).order_by('publish_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def error_404_view(request, … -
How can I work with choice fields in Django rest framework?
I have some fields in my user models that are choice fields(I don't write the models) and I've been trying to figure out a way for implementing these fields in a way that I can use a POST method but everything that I tried didn't work my #models.py ''' class GenderType(models.TextChoices): man = "male", woman = "female" gender = models.CharField(max_length=7 , choices=GenderType.choices, default='man') ''' #serializers.py ''' class SignUpSerializer(serializers.Serializer): gender = serializers.ChoiceField(choices=GenderType) def create(self, validated_data): return User.objects.create(**validated_data) ''' #views.py ''' def post(self, request, format=None): serializer = serializers.SignUpSerializer(data=request.data) data = {} if serializer.is_valid(): serializer.save() data['response'] = 'seccesfuly registerd a new user' return Response(data, status=status.HTTP_200_OK) else: return Response({'status':'bad request',}, status=status.HTTP_400_BAD_REQUEST) ''' -
500 IIS Internal server error near Fetch Api in django
I have deployed a django web application through Microsoft IIS. The deployment seems to be successful except for the error I am getting while submitting a form. I assume it's occurring because of the URL string given in fetch API. Though I am not exactly sure what is causing the error. Seeking help for the same. P.S- The yellow highlighted part in Console.log is the hostname on which I have deployed and now accessing the web page. web.config <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="my_app.wsgi_app()" /> <add key="PYTHONPATH" value="C:\MyApp" /> <add key="DJANGO_SETTINGS_MODULE" value="my_app.settings" /> <!-- Optional settings --> <add key="WSGI_LOG" value="C:\Logs\my_app.log" /> <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" /> <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="__instrumentation_key__" /> <add key="WSGI_PTVSD_SECRET" value="__secret_code__" /> <add key="WSGI_PTVSD_ADDRESS" value="ipaddress:port" /> </appSettings> </configuration> Console.log Console.log urls.py urls.py Logs #Software: Microsoft Internet Information Services 10.0 #Version: 1.0 #Date: 2022-05-30 06:14:28 #Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken 2022-05-30 06:14:28 10.9.20.237 GET / - 90 - 10.156.68.147 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/102.0.0.0+Safari/537.36 - 200 0 0 978 2022-05-30 06:14:29 10.9.20.237 GET /static/AIG-Logo.png - 90 - 10.156.68.147 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/102.0.0.0+Safari/537.36 http://pwgsascs0597001.r1-core.r1.aig.net:90/ 200 0 0 32 2022-05-30 06:14:29 … -
Django (createsuperuser) Error: That username is already taken
I am developing a Django application with Docker & PostgreSQL. I was using the same settings I will post below and all was working well, but after I had shutted down and started back (after removing volumes from Docker, and deleting pycache from folder) with: docker-compose down docker-compose up --remove-orphans When I try to create the admin (same user of the last session) it tells me: Error: That username is already taken. But, when I try to lookup for the user in PgAdmin (localhost:5050) the user does not exists, and when I try to login from the website (localhost:8000) it raise Please enter a correct username and password. Note that both fields may be case-sensitive. Dockerfile: FROM python:3.7-slim as production ENV PYTHONUNBEFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install -r ./requirements/prod.txt COPY manage.py ./manage.py COPY website ./website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install -r ./requirements/dev.txt COPY . . docker-compose.yml version: "3.7" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres … -
Multiple Sites with Django and Apache - Can't get both to work at the same time
We have two sites made in Django, one is a fork of the other (same project name) so we had issues with the wrong settings.py loading for the second site in mod_wsgi. So we put mod_wsgi into Daemon mode to hopefully separate the two more so this didn't happen. One works fine when the other is either disabled or configured incorrectly. Once the second site is made to what should work, it doesn't and it brings the first one down with it, giving us an Apache 500 Error. Here is the conf.d file we have for one of them: WSGIDaemonProcess {siteName}.co.uk python-home=/var/www/vhosts/{siteName}.co.uk/venv python-path=/var/www/vhosts/{siteName}.co.uk/website/{djangoProject} WSGIProcessGroup {siteName}.co.uk WSGIScriptAlias / /var/www/vhosts/{siteName}.co.uk/website/{djangoProject}/{djangoProject}/wsgi.py WSGIPythonHome /var/www/vhosts/{siteName}.co.uk/venv WSGIPythonPath /var/www/vhosts/{siteName}.co.uk/website/{djangoProject} <VirtualHost *:80> ServerName {siteName}.co.uk ServerAlias www.{siteName}.co.uk <Directory /var/www/vhosts/{siteName}.co.uk/> Options Indexes FollowSymLinks MultiViews AllowOverride All </Directory> <Directory /var/www/vhosts/{siteName}.co.uk/website/{djangoProject}/{djangoProject}> <Files wsgi.py> Require all granted </Files> </Directory> CustomLog /var/log/httpd/{siteName}.co.uk-access.log combined ErrorLog /var/log/httpd/{siteName}.co.uk-error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn </VirtualHost> Note: The file is the same for the two sites, except for that {siteName} is different. {djangoProject} is the same, since one is a modified clone of the other. It also gives the error in the apache log that there was a permission … -
Can't display the children items (packets) that contain the same dev_address as the selected parent item (device) in React.js
(Please check below for screenshots) I have a relational DB where every packet belongs to only one device (through a foreign key dev_address) and a device can have many packets (many-to-one rel). I've been trying to display the packets that belong to the selected device which is in a mapped list. I'm using context to load packets and devices from the API. The stack is React-Django-MySQL. Can someone please direct/help me on the method I should use to resolve this? It's like an if statement that displays the packets that belong to X device if X device was selected. import React from "react"; import GlobalContext from "./GlobalContext"; const AppContext = (props) => { const [modules, setModules] = React.useState([]); const [devices, setDevices] = React.useState([]); const [packets, setPackets] = React.useState([]); const [fields, setFields] = React.useState([]); React.useEffect(() => { Promise.all([ fetch("http://localhost:8000/api/v1/modules") .then((res) => res.json()) .then((json) => { setModules(json); }), fetch("http://localhost:8000/api/v1/devices") .then((res) => res.json()) .then((json) => { setDevices(json); }), fetch("http://localhost:8000/api/v1/packets") .then((res) => res.json()) .then((json) => { setPackets(json); }), fetch("http://localhost:8000/api/v1/fields") .then((res) => res.json()) .then((json) => { setFields(json); }), ]); }, []); return ( <GlobalContext.Provider value={{ modules, devices, packets, fields, }} > {props.children} </GlobalContext.Provider> ); }; export default AppContext; Devices table Packets table What I want … -
Render a string containing a django template, form and svg
I'm new to django and I have a problem, I want to render a string like httpresponse does but the problem is that the string is the content of an html file containing a django template and an svg code. Httpresponse does not interpret the django template and the django csrf_token. IT just copies them as text. For example: def mysresponse(request): ch= " {% extends 'base.html' %} {% block content%}form django and svg content {%endblock%}" return httpResponse(ch) This code copies the templates {% extends 'base.html' %} {% block content%}, {%endblock%} but interprets the svg and form content except the csrf_token. Is there a way to do this please? Thank you very much -
how to connect API Printify with django
I have problems connecting to the printify api with django, I am not very practical so I would need to understand why and above all what to pass as parameters views: def home(request): payload = settings.TOKEN_PRINTIFY # ?? response = requests.get('https://api.printify.com/v1/.json') print('-----------------', response) #error 401 context = {} return render(request, 'home.html', context) the response it gives me how 401 status and I don't understand where to put that token -
Insufficient permissions for deploying ARM template using Python SDK
I've got a simple scirpt that should deploy an ARM template: credentials = ClientSecretCredential( client_id="<client-id>", client_secret="<client-secret>", tenant_id="<tenant-id>" ) template = requests.get("<template-url>").json() deployment_properties = { 'mode': DeploymentMode.incremental, 'template': template } deployment = Deployment(location="eastus", properties=deployment_properties) client = ResourceManagementClient(credentials, subscription_id="<subscription-id>") deployment_async_operation = client.deployments.begin_create_or_update_at_subscription_scope("test_deployment", deployment) deployment_async_operation.wait() When I try to run it, I get this error: Exception Details: (InsufficientPrivilegesForManagedServiceResource) The requested user doesn't have sufficient privileges to perform the operation. Code: InsufficientPrivilegesForManagedServiceResource Message: The requested user doesn't have sufficient privileges to perform the operation. The app registration I created, does have user_impersonation permission, which should do the trick. Am I missing some permissions here? Thanks for the help! -
Automaticaly wrtite logged in superuser in model
In this piece of code, admin model in Registration should written automaticaly when add new registration in admin, and cannot be changed in admin panel Also it should be hidden in admin panel or read only import django.utils.timezone from django.db import models from django.contrib.auth.models import User import datetime year = datetime.datetime.now().year month = datetime.datetime.now().month day = datetime.datetime.now().day class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True, verbose_name='Релевантность') category = models.CharField(max_length=150, verbose_name='Категория') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', help_text='Номер в который хотите заселить гостя!', ) first_name = models.CharField(max_length=150, verbose_name='Имя') last_name = models.CharField(max_length=150, verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Администратор') #There should be written the of superuser which loggen in pasport_serial_num = models.CharField(max_length=100, verbose_name='Серия паспорта', help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа', help_text='Загружайте файл в формате .pdf') visit_date = models.DateField( default=django.utils.timezone.localdate, verbose_name='Дата прибытия') leave_date = models.DateField(blank=True, null=True, verbose_name='Дата отбытия', default='После ухода!') guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False, verbose_name='Релевантность', help_text='При бронирование отключите галочку') price = models.IntegerField(verbose_name='Цена (сум)', null=True) def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' -
How can we override Dango ModelAdmin queryset over ModelForm queryset?
Requirement is to display M2M instances in a dropdown for different logins. Each login will be able to see only instances belonging to their own domain. Since this dropdown is a dynamic list of table row values, I want to use widget = forms.CheckboxSelectMultiple which is part of the ModelForm where we need to pass the queryset. This queryset overrides the M2M form field definition: def formfield_for_manytomany(self, db_field, request, **kwargs): It doesn't filter as per the login and displays all the objects. I don't want to use the default <Ctrl +> for selection from the dropdown. Not very good with any JS related code. Please quide. Sharing the snippets of code tried: models.py: class GroupA(models.Model): address = models.EmailField( unique=True,verbose_name='Email id of the group') mailboxes = models.ManyToManyField(Mailbox, related_name='my_mailboxes') class GroupForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['mailboxes'].widget.attrs={"style":"height:100px;"} class Meta: model = GroupA fields = "__all__" mailboxes = forms.ModelMultipleChoiceField( queryset = Mailbox.objects.all(), widget = forms.CheckboxSelectMultiple ) In admin.py class GroupAdmin(admin.ModelAdmin): form = GroupForm def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "mailboxes": #if request.user.groups.filter(name__in=['customers']).exists(): kwargs["queryset"] = Mailbox.objects.filter( domain__customer__email=request.user.email) #print(kwargs["queryset"], 'qqqqqq') for k in kwargs["queryset"]: print(k, 'kkkkkkkkkk') return super(GroupAdmin, self).formfield_for_manytomany( db_field, request, **kwargs) Filtering works when we don't use the MultiCheckbox widget. Want …