Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it necessary add IsAuthenticated permissions to permission_classes in view that is inherited from LoginRequiredMixin
I have a class-based view called ProfileDetail. It is inherit LoginRequiredMixin from django.contrib.auth.mixins. And then set permission_classes = (IsAuthenticated,). Basically all client that view ProfileDetail is already logged-in, hence authenticated. My question is, is it necessary to set permission_classes = (IsAuthenticated,) even though all client already logged-in? What's your advice? Thank you. -
dj-rest-auth How to authenticate user with REST_USE_JWT = True when testing
I have Django Rest Framework site that use dj-rest-auth as authentication. I enable REST_USE_JWT = True in my settings.py. I want to test some API that require rest_framework.permissions.IsAuthenticated. I create client with rest_framework.test.APIClient() in my test. I try to login and view some API, but i got HTTP_401_UNAUTHORIZED. I try to login with post username, email, and password to dj-rest-auth login url, and got response access_token, refresh_token, etc. Then use credentials() to include it in header. But the client still got HTTP_401_UNAUTHORIZED. I don't know if i am doing it right. Please help me to authenticate the client in test. Thanks in advance! class ProfileTests(APITestCase): @classmethod def setUpTestData(cls): cls.username = "test" cls.email = "test@test.com" cls.password = "test" cls.user = get_user_model().objects.create_user( username=cls.username, email=cls.email, password=cls.password, ) cls.authenticated_client = APIClient() response = cls.authenticated_client.post( reverse("rest_login"), { "username": cls.username, "email": cls.email, "password": cls.password, }, format="json" ) cls.authenticated_client.credentials(HTTP_AUTHORIZATION=settings.JWT_AUTH_COOKIE + " " + response.data["access_token"]) -
Figuras interactivas HTML CSS JS DJANGO
Pará un proyecto de Django con HTML CSS y JS me piden poner una figura de un cuerpo humano en la que se puedan seleccionar articulaciones haciéndoles click y se marque un checkbox que tenga encima la articulación. Es decir, tiene que haber un checkbox posicionado encima de cada articulación y se tiene que poder intersctuar independientemente con cada uno. Alguna ayuda? Gracias! La única solución que se me ocurrió es posicionar la imagen del cuerpo fija y posicionar (también fijo) cada checkbox, pero me parece un laburo muy pesado y creo que debería haber alguna otra forma. -
Django 'runserver' displays blank page. It returns the source code and shows no errors. This problem was not here the last time I opened VS Code
I am doing a CS50 Web Project and it worked just fine until today. Now when I run the command 'python3 manage.py runserver (any port I want)' it displays: Just a blank page Django shows no errors, the settings are fine. the '/admin' page functions without issues and the page source code is shown without issues. This is not a Jinja syntax problem as well, as I checked it was correct to. It shows this blank screen no matter the URL I go too. If I open a live server it 'works' in that it displays contents to me. For example: Using this comand: Live server VS command It displays at least something close to the page: 'Live' display. !!! - I got also {% endblock %} at the end. I tried: Opening it with Live server, it displays contents, however, obviously, not what I need. Chaning the settings, they are fine. Chaning the port, that's not the issue. Checking the Jinja syntax, that's not the issue. Restarting VS code, no change (the last time, once again, had no issues regarding such problems). What is interesting is that if I remove all the code from a template like 'index.html': If … -
Internal Server Error 500 -- EC2, django, nginx, uwsgi
I'm developing and deploying django based web-app through EC2 with nginx and uwsgi. Because of developing Front-side (based on react), I send several http request to my server's public IPv4. And the first few moment, my request is normally answered by server. All data is safely delivered to "http://localhost:3000". But in some reason, after rebooting my EC2 instance, my nginx returned "500 (Internal Server Error)". More detailed information is descripted below. [log] /var/nginx/access.log --> any further information than internal server error 3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:08 +0000] "GET /beta/.env.local HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.production HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /beta/.env.staging HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246" "-" 3.21.102.102 - - [22/Dec/2022:04:07:09 +0000] "GET /live/.env HTTP/1.1" 500 32 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, … -
Reverse for 'add_vacation' with no arguments not found. 1 pattern(s) tried: ['ferias/adicionar/(?P<id_client>[0-9]+)/\\Z']
Boa noite pessoal, Espero que vocês consigam salvar este mero estudante. Estou desenvolvendo um sistema pro meu TCC e vou testar ele no quartel onde trabalho. É um sistema de lançamentos de saídas e retornos de férias, viagens, etc. Estou fazendo com Python + Django, porém está dando o seguinte erro depois que faço o log in no sistema. urls from django.urls import path, re_path from . import views app_name = 'holidays' urlpatterns = [ path('', views.list_vacations, name='list_vacations'), path('administrador-ferias/<int:id_client>', views.list_vacations_admin, name='list_vacations_admin'), path('adicionar/<int:id_client>/', views.add_vacation, name='add_vacation'), path('excluir/<int:id_client>/', views.delete_vacation, name='delete_vacation'), path('editar/<int:id_holidays>/', views.edit_vacation, name='edit_vacation'), path('editar-administrador/<int:id_holidays>/', views.edit_vacation_admin, name='edit_vacation_admin'), ] view # está função é reponsável pela adição das férias, dispensas, etc. @login_required(login_url='/contas/login/') def add_vacation(request, id_client): template_name = 'holidays/add_vacation.html' context = {} if request.method == 'POST': form = HolidaysForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.clients = Client.objects.get(id=id_client) f.user = request.user f.save() form.save_m2m() return redirect('holidays:list_vacations') form = HolidaysForm() context['form'] = form return render(request, template_name, context) template {% if user.is_authenticated%} <li class="nav-item"> <a class="nav-link" href="{% url 'clients:list_militar' %}">Cadastro pessoal</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'holidays:add_vacation' %}">Realizar Lançamentos</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'holidays:list_vacations' %}">Histórico de lançamentos</a></li> {% endif %} Não sei se o erro poderia ser causado do import de Client dentro da view Holidays. Eu … -
TypeError: PaystackPayment() missing 1 positional argument: "request"
I'm getting the error PaystackPayment() missing 1 required positional argument: 'request' at line 246 of my core.views of my Ecommerce project when trying to access the function PaystackPayment(). I don't know what is wrong. views: def PaystackPayment(request): try: order = Order.objects.get(user=request.user, ordered=False) secret_key = settings.PAYSTACK_SECRET_KEY ref = create_ref_code() amount = int(order.get_total() * 100) client_credentials = request.user.email paystack_call = TransactionResource( secret_key, ref) response = paystack_call.initialize( amount, client_credentials ) authorization_url = response['data']['authorization_url'] # create payment payment = PaystackPayment() payment.user = request.user payment.ref = ref payment.email = client_credentials payment.amount = int(order.get_total()) payment.save() # assign the payment to the order order.ordered = True order.email = client_credentials order.ref_code = ref order.paystack_payment = payment.amount order.save() # send confirmation order email to the user subject = f'New Order Made by {request.user.username} today totaled {int(order.get_total())} ' message = 'Hello there ' + \ ', Thanks for your order. Your order has been received and it is being processed as we shall get back to you shortly. Thank you once again!' email_from = settings.EMAIL_HOST_USER recipient_list = [request.user.email, ] send_mail(subject, message, email_from, recipient_list) messages.success(request, 'Your order was successful') return redirect(authorization_url) except ObjectDoesNotExist: messages.info( request, """ Their was an error when you where possibly entering the checkout or payment fields. You … -
Facebook comment section for multiple pages
I am trying to add a Facebook comments section on each page in my website. For example, pk=27 (https://www.donadogs.org/en/dogs/27/) should have its own section and pk=28 a different one. https://developers.facebook.com/docs/plugins/comments#configurator allows me to create a section per URL provided. This means that I can't add a section for each separate PK on my website as each URL has to be provided manually. Is there a workaround to this? -
Redirect with data in Django
I have a user authorization through a link: def ClientAuth(request, link_code): try: code = Links.objects.filter(code=link_code).values('code', 'status') if code[0]['status']: username, password = 'Client', '**************' client = authenticate(request, username=username, password=password) if client is not None: login(request, client) return redirect('clientPage') return HttpResponse("Hello its work") else: return render(request, 'client/404.html') except: return render(request,'client/404.html') If the link exists in the database and the active one authorizes us as a client and redirects it to his page, it looks like this in urls: urlpatterns = [ path('clientPage/',views.clientPage, name = 'clientPage'), path('<link_code>/', views.ClientAuth, name='ClienAuth') ] My task is that, depending on the link the client used to log in on the client page, he receives different information, for example, the link ID Is there any way I can pass this data from the ClientAuth function when redirecting? redirect to this page: def clientPage(request): print(request) return HttpResponse("Hello") -
Django's DRF has_object_permission method not called with get_object
I scratch my head to understand why the has_object_permission bellow has no effect, because the documentation says that this method should be executed with get_object. What could be the reason ? @permission_classes([HasViewObjectPermission]) class IndividualDetailsView(RetrieveAPIView): serializer_class = IndividualSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) return Individual.objects.get(pk=pk) class HasViewObjectPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): return False -
How can I Show Only my Videos in Django-Rest-Framework?
I'm using Django and React to create YouTube clone. And I have an admin panel where user can delete and edit his videos. But the problem is that it showing my videos and other users videos. How can make that the admin panel will show only my videos? views.py Api Views class AdminVideoDetail(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] quesryset = Video.objects.all() serializer_class = VideoSerializer videos.js Videos in the admin panel import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import Link from '@material-ui/core/Link'; import Paper from '@material-ui/core/Paper'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import DeleteForeverIcon from '@material-ui/icons/DeleteForever'; import EditIcon from '@material-ui/icons/Edit'; import Button from '@material-ui/core/Button'; const useStyles = makeStyles((theme) => ({ cardMedia: { paddingTop: '56.25%', // 16:9 }, link: { margin: theme.spacing(1, 1.5), }, cardHeader: { backgroundColor: theme.palette.type === 'light' ? theme.palette.grey[200] : theme.palette.grey[700], }, videoTitle: { fontSize: '16px', textAlign: 'left', }, videoText: { display: 'flex', justifyContent: 'left', alignItems: 'baseline', fontSize: '12px', textAlign: 'left', marginBottom: theme.spacing(2), }, })); const Videos = (props) => { const { videos } = props; const classes = useStyles(); if (!videos || videos.length === … -
Why is my Pillow Image not being considered a File when I try to save it into my django image field?
I'm writing a Form Creation/Filling out forms app, and I'm to the point where I'm taking canvas data from the front-end and filled out fields of text input and draw them on a picture of the form with the pillow library. The problem is when I try to save the data for the form I get this error from "serializer.error" from django-rest-framework: "'FilledForm': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}" Here is the Api view: @api_view(['POST']) def postForm(request): dataDict = request.data FieldCoords = {} # Define Formtype selectedForm = dataDict["SelectedForm"] del dataDict["SelectedForm"] # Get Datalist for form creation datalist = list(FormData.objects.filter(FormType=selectedForm).values()) #Set Signature Images on Form and Fill form with inputs for field in datalist: #Get Field Positions of Model if field["FieldType"] == "SignatureField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"]) elif field["FieldType"] == "TextField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"],abs(field["height"])) elif field["FieldType"] == "DateField": FieldCoords[field["FieldName"]] = (field["StartX"],field["StartY"]) #print(FieldCoords) #Place Signature Fields On FormImage sigFields = json.loads(dataDict["Signatures"]) FormImage = Image.open(f"{MEDIA_ROOT}/{selectedForm}") del dataDict["Signatures"] for field in sigFields: datauri = sigFields[field] uri = datauri.split("base64,") sNameselect = field.split(" - ") bytes = base64.b64decode(uri[1]) img = Image.open(io.BytesIO(bytes)) for keyCoordSet in FieldCoords: print(keyCoordSet) print("Name" + sNameselect[0]) if sNameselect[0] == keyCoordSet: print("Im here") FormImage.paste(img, FieldCoords[keyCoordSet], … -
How to test Django API that uses Celery task with send_email?
So, in my Django project, I have an API view that sends data by email to the user. That job doing by Cerely (celery task). I want to test that API sends the right data. But I can't realize how to do that with that celery job, because the user created in a testcase has a non-exist email. So even if I run celery worker in a test it'll fail due to the wrong email with SMTP error... If we implement the view without celery we can use Django mail.outbox[0].body to inspect the mail. But with Celery we can't. Pls, advise. -
Django Rest Framework - nested serializer is not working like expected or how the docs explains
I have a post model and i have a post image model. I would like to show the images related to a post in the API, but I cannot seem to get it right.I only see the post data and not the related images. Here are my post and post image models: class Post(models.Model): EV = "Everybody" FO = "Followers" FR = "Friends" AUDIENCE = [ (EV, "Everybody"), (FO, "Followers"), (FR, "Friends"), ] category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=user_directory_path, null=True, blank=True) can_view = models.CharField(max_length=10, choices=AUDIENCE, default=EV) can_comment = models.CharField(max_length=10, choices=AUDIENCE, default=EV) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] def get_absolute_url(self): return self.slug class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post") image = models.FileField( upload_to=post_directory_path, default="posts/default.png", null=True ) class Meta: db_table = "post_images" ordering = ["post"] def image_tag(self): return mark_safe( '<img src="/storage/%s" width="50" height="50" />' % (self.image) ) image_tag.short_description = "Image" This is the post and post images serializers: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ["id", "image", "post"] extra_kwargs … -
How to use two loop correctly in python
Hi guys I have problem This is my code : services = { 'first':[], 'second':[] } x = [1,2,3,4,5] for i in services: print('loop-one - ',i) for i in x: services['first'].append(i) print(services) Output of this code is {'first': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5], 'second': []} If you notice He added twice . my purpose is something like this , I want add once {'first': [1, 2, 3, 4, 5], 'second': []} Thanks ! -
Getting "TypeError: Object of type IFDRational is not JSON serializable" while trying to json.dumps EXIF info
I'm trying to extract EXIF information from an image and store it as a JSONField. It works well for some image types but not for others. Below my code: image_open = Image.open(self.image) image_open.verify() image_getexif = image_open.getexif() if image_getexif: exif = { ExifTags.TAGS[k]: v for k, v in image_getexif.items() if k in ExifTags.TAGS and type(v) is not bytes] } print(json.dumps(exif, indent=4)) I'm getting TypeError: Object of type IFDRational is not JSON serializable when trying to json.dumps(). When dumping the exif dict I notice it is pretty standard so not sure what this is about. {'ResolutionUnit': 2, 'ExifOffset': 204, 'Make': 'Apple', 'Model': 'iPhone 13', 'Software': '15.3.1', 'Orientation': 1, 'DateTime': '2022:03:04 17:35:15', 'XResolution': 72.0, 'YResolution': 72.0, 'HostComputer': 'iPhone 13'} -
Django - Link search bar with autocomplete to item detail page as a result of the search
I have a search bar with autocomplete but I don't know how to link it to the search bar action. Once the user selects one of the items from the autocomplete list, I want to move to the detail.html of that item (using the slug). How do I nest the autocomplete function into the search function? Right now I have a search function which takes the term searched, creates a list of potential item candidates with their url and shows them in the following search_result.html. I want to avoid this step and go straight from the search bar with autocomplete to the detail page of the item. See below the functions. Any ideas on how to do this? Sorry if this is too basic :/ def search(request): if request.method == "POST": searched = request.POST['keyword'] search_vector = SearchVector("descr") search_query = SearchQuery(searched) item = Object.objects.annotate(search=search_vector, rank=SearchRank( search_vector, search_query)).filter(search=search_query).order_by("text_len","-rank") return render(request, 'search_result.html', {'searched':searched, 'item':item}) else: return render(request, 'home.html', {}) def autocomplete(request): if 'term' in request.GET: search_vector = SearchVector("descr") search_query = SearchQuery(request.GET['term']) qs = item = Object.objects.annotate(search=search_vector, rank=SearchRank( search_vector, search_query)).filter(search=search_query).order_by("text_len","-rank") titles = list() # source at the autocomplete in the JQuery expects an url with a list of potential items. for i in qs: … -
Problem converting LDAPS connection from ldap3 to django_auth_ldap in Python Django
Problem getting LDAPS user authentication in Django Works with ldap3 module When I run the code below, the response indicates that the LDAP server was able to connect and find a user with the common name "MyUser" in the "ou=grouping,dc=example,dc=ad" search base. import ldap3 #Set up LDAP connection and bind server = ldap3.Server('ldaps://ad.example.com', use_ssl=True) conn = ldap3.Connection(server, 'cn=crunchy-test,cn=users,dc=example,dc=ad', 'PASSWORD') conn.bind() #Check if bind was successful if conn.bound: print('Successfully bound to LDAP server') else: print('Failed to bind to LDAP server') #Specify search base and search filter search_base = 'ou=grouping,dc=example,dc=ad' search_filter = "(cn=MyUser)" #Perform search and specify search scope as subtree conn.search(search_base, search_filter, search_scope=ldap3.SUBTREE, attributes=['givenName', 'sn', 'mail']) #Iterate over search results for entry in conn.response: print(entry['dn'], entry['attributes']['givenName'], entry['attributes']['sn'], entry['attributes']['mail']) #Unbind from LDAP server conn.unbind() Output Successfully bound to LDAP server <br/> CN=MyUser,OU=userGroup,OU=Grouping,DC=example,DC=ad My User My.User@email.com Does not work with from django_auth_ldap , ldap module #Configuration for LDAP login authentication - https://django-auth-ldap.readthedocs.io/en/latest/authentication.html #Baseline configuration. AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com" AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) #--------test search bind------ AUTH_LDAP_BIND_DN = "cn=crunchy-test,cn=users,dc=example,dc=ad" AUTH_LDAP_BIND_PASSWORD = "PASSWORD" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=grouping,dc=example,dc=ad",ldap.SCOPE_SUBTREE,"(cn=%(user)s)") #---ldap user login config #A dictionary of options to pass to each connection to the LDAP server AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0, ldap.OPT_PROTOCOL_VERSION: 3, } #A string template that … -
When I am filtering the product but when i run the project i don't get the images
When I am filtering the product but when i run the project i don't get the images if i changethe Product.objects.filter(slug=slug) to replce the Product.objects.get(slug=slug) the i am facing this type off error Django 'Product' object is not iterable Views.py """ def product_detail(request, slug): try: product = Product.objects.filter(slug=slug) context = { 'product': product, } return render(request, 'buyer/product_details.html', context) except Product.DoesNotExist: return render(request, 'buyer/product_details.html', {'error': 'No data found.'}) """ Urls.py """ path('product/<slug:slug>', views.product_detail, name="product_detail"), Models.py """ class Product(models.Model): total_quantity = models.IntegerField() availability = models.IntegerField() feature_image = models.ImageField(upload_to='media/Product_image') product_name = models.CharField(max_length=100) price = models.IntegerField() discount = models.IntegerField() product_information = RichTextField() model_name = models.CharField(max_length=100) categories = models.ForeignKey(MainCategory, on_delete=models.CASCADE) tags = models.CharField(max_length=100) description = RichTextField() section = models.ForeignKey(Section, on_delete=models.DO_NOTHING) slug = models.SlugField(default='', max_length=500, null=True, blank=True) def __str__(self): return self.product_name def get_absolute_url(self): from django.urls import reverse return reverse("product_detail", kwargs={'slug': self.slug}) class Meta: db_table = "buyer_Product" def create_slug(instance, new_slug=None): slug = slugify(instance.product_name) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, Product) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_url = models.ImageField(upload_to='media/Product_image') def __str__(self): return self.product.product_name """ … -
Django abstract model not working as expected
I have an abstract django model and a basic model. I am expecting any instance of the basic model to have a value for the field created_at or updated_at. However, as of now, all my instances have None for both these fields. What am I doing wrong? from django.db import models class Trackable(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Quotation(Trackable): reference = models.CharField(null=True, max_length=80) quotation = Quotation(id=1) print(quotation.created_at) >>> None -
How to combine AND and OR in DRF permission_classes decorator?
Before executing a view I would like to verify multiple permissions within the permission_classes decorator, by checking permissions with AND and OR operators. My problem is that IsUserInstance isn't checked in the example bellow, and when I replace & by and then both permission into the parenthesis are not checked. What is the best way to do that ? or, alternatively, how can I create a new permission that check IsIndividual and IsUserInstance ? views.py @permission_classes([IsSuperUser | IsManager | (IsIndividual & IsUserInstance)]) class IndividualDetailsView(RetrieveAPIView): serializer_class = IndividualSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) return Individual.objects.get(pk=pk) permissions.py class IsIndividual(permissions.BasePermission): def has_permission(self, request, view): return Individual.objects.filter(pk=request.user.pk).exists() class IsUserInstance(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user -
django.db.utils.OperationalError: no such table: App_useraccount
from django.db import models from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin ) class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, email,username,password=None): if not email: raise ValueError('user must have an email address') if not username: raise ValueError('user must have an username') user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name,username, email, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password, first_name = first_name, last_name = last_name ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser,PermissionsMixin): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=64, unique=True) state = models.CharField(max_length=30) city = models.CharField(max_length=30) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=80) dob = models.CharField(max_length=50) gender = models.CharField(max_length=30) min_salary = models.IntegerField(null=True) max_salary = models.IntegerField(null=True) profile_pic = models.ImageField(upload_to='app/img/condidate') # required_fields date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, add_label): return True class Company(models.Model): user_id = models.ForeignKey(UserAccount, on_delete=models.CASCADE) post_by = models.CharField(max_length=60) company_name = models.CharField(max_length=150) … -
Django 4 REST framework JSON POST request filter
I have this API where I need to filter some data. My user will pass a JSON containing several instances that I need to return to them if there existis or not on my database. But I don't know how I can make Django 4 make several POST requests within the same JSON (I guess since they would be only getting information this would be several "GET" requests, but I need to make them in a POST). Thoughts on how should I do it? I don't even know how to start. For example, the POST request could be: [ { "name": "media1" }, { "name": "media2" }, { "name": "media3" } ] And if I had medias 1 and 3 but not 2, the API would return the following: [ { "id": 0, "name": "media1" }, { None }, { "id": 1, "name": "media3" } ] This is my current viewset. I have implemented a filter that works only for one GET request at a time: class MediasViewSet(viewsets.ModelViewSet): queryset = Media.objects.all().order_by('name') serializer_class = MediaSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self, *args, **kwargs): print(self.request) queryset = super().get_queryset() if(self.request.data.__contains__("name")): query = self.request.data['name'] if query: queryset = Media.objects.filter(name=query) return queryset This … -
How i can show:{{ if citizen.nizo.name == category.name }}?
I'm new to django. My problem is that I can't use "i .nizo.name".if citizen.nizo..name == category.name should work. Please answer me for 1 day.I have a deadline( P.S Sorry my english so bad)**** my one_category.html {% for i in citizen %} {% if i.nizo == category.name %} <p>if</p> <a href="{% url 'citizen' i.slug %}"><h3> {{ i.name }} - haqida malumuot</h3> </a> <br> {% else %} <p>else</p> {% endif %} {% endfor %} my models.py class Citizen (models.Model) : name = models.CharField(max_length=255, verbose_name= "F.I.SH",blank=True,null=True) #widget=models.TextInput(attrs={'class':'form-input'}) tugilgan_sanasi = models.DateField(max_length=255, verbose_name= "Tug'ilgan sanasi",blank=True,null=True) slug = models.SlugField(max_length=255, unique=True,verbose_name= "Slug") yashash_manzili = models.CharField(max_length=240, verbose_name= "Yashah manzili",blank=True,null=True) content = models.TextField(verbose_name ="Текст статьи",blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Izoh",blank=True,null=True) is_published = models.BooleanField(verbose_name= "Organilgan/Organilmagan") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания",blank=True,null=True) time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения",blank=True,null=True) nizo_shaxs =models.CharField(max_length=240, verbose_name="Nizoloshyatgan Shaxs F.I.SH",blank=True,null=True) nizo = models.ForeignKey('Category',on_delete=models.PROTECT, null=True,blank=True, verbose_name ="Nizo не выбрана") mah = models.ForeignKey('Mahalla',on_delete=models.PROTECT,null=True,blank=True, verbose_name= "Mahalla не выбрана") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:citizen', kwargs={'citizen_slug': self.slug}) class Category(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Nizo") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:category', kwargs={'nizo_slug': self.pk}) class Meta: verbose_name = 'Nizo' verbose_name_plural = 'Nizo' my views.py def show_one_category(request,nizo_slug:str): citizen = Citizen.objects.all() category = get_object_or_404(Category, slug=nizo_slug) context = { 'category':category, … -
How to access user Input as GET request and output the responce in HTML page using Flask Python
sorry to asking questions like this I am new to flask and html not able to figure out error where I am getting. building small application where it calculates the cycle count of the time series curves when curve profile lower end value <13 and peak end of the curve >20 my script calculates the count how many time the curve goes up above >20 and billow 13 values this is i did for static data if user input the data below 4 and above 15 it has to show the count value so far i used this script for count calculation import numpy as np from flask import Flask, render_template, request app = Flask(__name__) x = np.array([0, 7, 18, 24, 26, 27, 26, 25, 26, 16, 20, 16, 23, 33, 27, 27, 22, 26, 27, 26, 25, 24, 25, 26, 23, 25, 26, 24, 23, 12, 22, 11, 15, 24, 11, 12, 11, 27, 19, 25, 26, 21, 23, 26, 13, 9, 22, 18, 23, 26, 26, 25, 10, 22, 27, 25, 19, 10, 15, 20, 21, 13, 16, 16, 15, 19, 17, 20, 24, 26, 20, 23, 23, 25, 19, 15, 16, 27, 26, 27, 28, 24, 23, …