Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data from an attribute of foreign key table to primary key table in Django
I want to get all the issues.reference with status "Exemption" in Project model's exemption field, in order to send the it as a response. As issue model has project as a foreign key field so I can't import Issue in Project model, that leads to circular import. Project Model ''' class Project(models.Model): creation_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) expiry_date = models.DateTimeField(null=True, blank=True) exemption = ListField(models.CharField(max_length=128), blank=True, null=True) ''' Issue Model ''' class Issue(models.Model): requestor = models.ForeignKey(User, related_name='issues', on_delete=models.CASCADE) projects = models.ManyToManyField(Project, related_name='issues_projects') reference = models.CharField(max_length=16, unique=True, editable=False, null=True) status = models.CharField(max_length=12, choices=IssueStatus.choices, null=True) ''' -
loop.last in jinja2 not working properly in django
guys I am trying to avoid printing two divs in my table in the last iteration of the loop of my Django template. I have used loop.last variable to check if the loop is in its last iteration, but it is not working for some reason. Here program session is simply a range(number_of_iterations_required). Here is my code: {% for n in program_sessions %} <!-- 1st session start --> <tr class="mb-2"> <td class="border border-0"> <div class="row"> <div class="col-6 mx-0 px-0"> <span class="float-end">Row: &nbsp;</span> </div> <div class="col-6 mx-0 px-0"> <span class="text-white">{{program.workout_time}}m</span> </div> {% if not loop.last %} <div class="col-6 mx-0 px-0"> <span class="float-end">Rest: &nbsp;</span> </div> <div class="col-6 mx-0 px-0"> <span class="text-white">{{program.rest_time}}min</span> </div> {% else %} <div class="col-6 mx-0 px-0"> <span class="float-end">Last Iteration boii! &nbsp;</span> </div> {% endif %} </div> </td> </tr> <!-- 1st session ends --> {% endfor %} </tbody> </table> </div> Thank you in advance for your help. Have a good day. -
Annotate getting wrong calculations
class Order(): pass class OrderItems(): parent = models.ForiegnKey(Parent, related_name="items") class OrderItemSalesTax(): child = models.ForiegnKey(OrderItems, related_name="sales_tax") I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. But in second annotate I am not getting correct results, as you can see the query is straight forward to calculate sales tax (price + price * tax_percentage / 100). After struggling for hours, I couldn't figure it out, Am I doing something wrong ? Order.objects.annotate(trade_price= \ ExpressionWrapper( Sum(F('items__trade_price') * ExpressionWrapper(0.01 * (100 - F('items__discount__discount')), output_field=DecimalField()) * F('items__quantity') ) , output_field=DecimalField() ) ).annotate(total_price=F('trade_price') + F('trade_price') * Sum(F('items__sales_tax__percentage') / 100)) -
Unable to use reactjs ldap-authentication module, Error: 80090308: LdapErr: DSID-0C090447, comment: AcceptSecurityContext error, data 52e, v3839
I am developing one web application. I am using Django in the backend and reactjs in the frontend. I want to implement LDAP authentication with GroupWise permission. I am unable to find out good example or way to do this. Where should I implement LDAP - Djnago or reactjs?? If I use node module that is ldap-authentication. Source code is https://www.npmjs.com/package/ldap-authentication I am getting below error: Error: 80090308: LdapErr: DSID-0C090447, comment: AcceptSecurityContext error, data 52e, v3839 below are the param I am providing in code: let options = { ldapOpts: { url: CONFIG.ldap.url, }, // note in this example it only use the user to directly // bind to the LDAP server. You can also use an admin // here. See the document of ldap-authentication. userDn: `uid=${req.body.username},${ldapBaseDn}`, userPassword: req.body.password, userSearchBase: ldapBaseDn, usernameAttribute: 'UID', username: req.body.username, adminPassword: CONFIG.ldap.password, adminDn: 'cn=CONFIG.ldap.name,dc=xxx,dc=xxx,ou=Service Accounts,ou=xxx,ou=Common', verifyUserExists : true } Note: My LDAP server is not public and in reactjs ldap-authentication example they have used public ldap server. I am using https://github.com/shaozi/passport-ldap-example example for reactjs ldap implementation. Thank you. -
Django rest framework how to pass authorizing token in nextjs post request?
How to pass django authorization token in nextjs axois. I tried this for pass authorization token but getting 404 error. token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers: { Authorization: `Bearer ${token}` }, contact_name:contact_name,contact_email:contact_email,contact_body:contact_body, }) -
I want to save the selected radio button into the database? How can I accomplish that in django?
models.py from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. # from django.utils.encoding import smart_unicode from enum import Enum from django.contrib.auth.models import AbstractUser from django import forms class CommentForm(forms.Form): name = forms.CharField() comment = forms.CharField(widget=forms.Textarea) class Username(AbstractUser): firstName = models.CharField(max_length=200, null=True) lastName = models.CharField(max_length=200, null=True) email = models.EmailField(unique=True, default=None, null=True) password = models.CharField(max_length=32) REQUIRED_FEILDS = [] def __str__(self): return self.username class Option(models.TextChoices): OPTION1 = 'OPTION1', _('OPTION1') OPTION2 = 'OPTION2', _('OPTION2') OPTION3 = 'OPTION3', _('OPTION3') OPTION4 = 'OPTION4', _('OPTION4') class Question(models.Model): # id = models.AutoField(primary_key=True) question=models.CharField(max_length=600) option1=models.CharField(max_length=200, default=None) option2=models.CharField(max_length=200, default=None) option3=models.CharField(max_length=200, default=None) option4=models.CharField(max_length=200, default=None) difficulty=models.PositiveIntegerField() exam=models.BooleanField() key=models.CharField(max_length=100) correct_answer = models.CharField(max_length=7,choices=Option.choices,default=None,) def __str__(self): return str(self.id) class Answer(models.Model): username=models.ForeignKey(Username,max_length=200, null=True,on_delete=models.CASCADE) question_id = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField( max_length=7, choices=Option.choices, default=None, ) surety=models.PositiveIntegerField( null=True) difficulty=models.PositiveIntegerField( null=True) def __str__(self): return self.answer views.py from django.shortcuts import render, redirect from .models import * from django.http import JsonResponse from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib.auth import get_user_model from django.template import loader from django.views.generic import ListView from django.core.paginator import Paginator from ada.models import Question from django.db.models.functions import Lower from django import forms # class TestScreen(ListView): # paginate_by = 6 … -
How to display Selected option value Selected in option tag in Django Template File?
I want to keep user selected option active from the long SELECT OPTION dropdown list what they choose from SELECT OPTION. This is my HTML form in template file. <form action="" method="post"> {% csrf_token %} <div class="d-flex form-inputs"> <select class="form-select" aria-label=".form-select-lg" name="lang_txt"> <option value="span_to_eng">Spanish To English</option> <option value="eng_to_span">English To Spanish</option> <option value="french_to_eng">French To English</option> </select> <input name="txt" class="form-control p-3" type="text" placeholder="Search..."> <a href="#"><img src="/static/assets/image/search.png" alt=""></a> </div> </form> This is views function def lang_convert_view(request): if request.method == "POST" and 'txt' in request.POST: txt = request.POST.get('txt') selected_lang = request.POST.get('lang_txt') data = custom_function_name(txt) context = {'data': data} else: context = {} return render(request, 'index.html', context) Please help me -
Xlxs file response not correct. It returning garbage symbols on response
def daily_report_summery(request): body = request.body data = json.loads(body) date = data['date'] generate_summary_report_xl(date) with open('./Daily_Report.xlsx', "rb") as file: response = HttpResponse(file.read(),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=Daily_Report.xlsx' return response I am getting this responce: response I want to send Daily_Report.xlsx file from backend. -
Delete object in django by two parameters by ajax.The object is deleting during declaration .How to retain object for using in templates?
When I try to delete an object by ajax call both ID's are not passing to url Am getting url like 127.0.0:8000/delete// The object is deleting during declaration .How to retain object for using in templates?? urls.py path('delete/<int:a_id>/<int:b_id>',views.delete,name="delete") views.py def delete(request,a_id,b_id): obj=Table.objects.get(a_id=a_id,b_id=b_id) obj.delete() return render(request,"delete.html",{'obj':obj}) delete.html <input type="hidden" id="a_id" data-value="{{obj.a_id}}"> <input type="hidden" id="b_id" data-value="{{obj.b_id}}"> script.js var a_id=$("#a_id").data("value"); var b_id=$("#b_id").data("value"); #some code $.ajax({ url:'delete/'+ a_id +'/' + b_id, #some code }); -
How to store images using Django forms?
I'm new to django. I've been stuck for a while. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files/images. I have done the settings file, urls, views, models, forms everything. Here are relevant files: // setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') // models.py class Trip(models.Model): city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) description = models.CharField(max_length= 255) creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True) favoriter = models.ManyToManyField(User, related_name= 'fav_trips') photo = models.ImageField(null=True, blank =True, upload_to='trips/') // urls.py ( there were 2 ways to write media according to tutorial) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('travelsiteapp.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) // views.py (lastly) def tripAdd(request): form = TripForm() if request.method == 'POST': form = TripForm(request.POST, request.FILES) if form.is_valid(): form.photo = form.cleaned_data["photo"] form.save() context = { 'form': form} return render(request, 'tripAdd.html', context) // html/ form <form action="/createTrip"method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> // forms.py from django import forms from django.forms import ModelForm from .models import Trip from django import forms … -
How to use the foreign key in condition html Django
everybody. Im beginner in Python and I have this question. Anyone knows why this condition dont works? In the h4 the lancamento.tipo show the information "Receita", but in the condition not works. list.html <div class="list-group"> {% for lancamento in object_list %} {% if lancamento.tipo == 'Receita' %} <a href="#" class="list-group-item list-group-item-success"> <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4> <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p> <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p> </a> {% else %} <a href="#" class="list-group-item list-group-item-danger"> <h4 class="list-group-item-heading">{{lancamento.tipo}}</h4> <p class="list-group-item-text">Descrição: {{lancamento.descricao}}</p> <p class="list-group-item-text">Valor: R$ {{lancamento.valor}}</p> </a> {% endif %} {% endfor %} And the models.py class Usuario(models.Model): nome = models.CharField(max_length=255) cpf = models.CharField(max_length=11, unique=True) saldo = models.FloatField(default=0) def __str__(self): return self.nome class Lancamento(models.Model): tipo = models.ForeignKey('Tipo', on_delete=models.CASCADE) nome_usuario = models.ForeignKey('Usuario', on_delete=models.CASCADE, default='') valor = models.FloatField() descricao = models.TextField() data_lancamento = models.DateTimeField(null=True, blank=True) class Meta: ordering = ['-data_lancamento'] class Tipo(models.Model): nome = models.CharField(max_length=255) def __str__(self): return self.nome And the views.py, using the Class Based Views from django.shortcuts import render from django.views.generic import ListView from core.models import Lancamento # Create your views here. def index(request): return render(request, 'core/index.html') class LancamentoList(ListView): model = Lancamento queryset = Lancamento.objects.all() -
DJango channels subscribe to multiple events
I have django application with channels. It opens websocket connection to Crypto-market data provider. I received tick data, I insert those ticks in the database. I also want to send that tick data to other application (say frontend). But I am not able to it efficiently. Currently only single frontend application is present. So when it connects to django channels, I add that connection to group named('root') and send all the market-tick data to that group. So the problem here is, If I decide to connect second frontend application, I get all the data that first user was requesting (as both clients are present in group 'root' on django). I tried a method were when a users requests data for particular crypto, then I added him to that crypt-named group (if user want bitcoin data only, I added him to bitcoin group) But I get lots crpto-data on django server and very big number of ticks per second. It feels kind of slow to send each tick data to that particular crypto group channel ( on tick check symbol and forward that tick to that symbol-named django channel). Any suggestion on how to approach to this problem.? -
Django Import-Export: Issues importing to model with UUID for id field
I am trying to import a csv file (utf-8 encoded) via Django Admin into a Django model using the Django-import-export package(v3.0.0b4). I was initially working with the last stable version but was encouraged to try the pre-release. The import preview looks correct but the interface shows the following error for all rows of the csv: Non Field Specific “” is not a valid UUID. I have tried several permutations of including 'id' in import_id_fields or excluding the 'id' field and using a renamed 'unique_id' field as a hook. I've also attempted the import with blank entries in both an 'id' column and 'unique_id' column of the csv. Also with the id field omitted from the csv entirely. For some reason a blank field is being returned regardless of whether I populate the id fields or not. I suspect I'm doing something small wrong, but I'm not clear on what. resources.py, models.py, and admin.py included below. Happy to share other snippets if needed. models.py from django.db import models from django.db.models import Sum import uuid from datetime import datetime class Purchase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False) date = models.DateField(blank=True,null=True) seller = models.CharField(max_length=200,default='') number = models.CharField(max_length=200,blank=True,default='') customer = models.CharField(max_length=200,default='') salesperson = models.CharField(max_length=200,blank=True,default='') discount = … -
Javascript regex to solve fill in the words
I'm looking for a way to solve hangman puzzles automatically. Let's say my input is ___o_ and I have a word bank of "llaory" just to make it easy. I'll look through a big list of all english words and use a regex to search for anything that matches. What I have so far that works is this. import raw from "./static/wordlist.txt"; let reg = new RegExp( "\\b" + letters.replace( /_/g, `[${bank}]` ) + "\\b", "g" ); fetch(raw) .then((r) => r.text()) .then((text) => { if (text.match(reg)) { console.log(text.match(reg)); } }); Bank is the word bank so in this case it is llaory. The results from this are 2 words ['alloy', 'alloo']. The correct and only option should be alloy but alloo is an option because the code can't recognize that only 1 o can be used. How can I make it so that the regex knows that letters can only be used as much as there are in the bank? I've seen this post Regex with limited use of specific characters (like a scrabble bank of letters) but it doesn't seem to work when there is a letter already present as shown with the ___o_ -
Activate function every <tr>>javascript | django [duplicate]
I'm not a JS expert, and i'm facing some struggles to activate a function on every table row in a django aplication. I would like that, in every time that i click on the item_total it calculates the inputed value from the item_value * item_qt, but when i try it out, it only work for the first row That's my table: <tbody> {% for item in contract_items %} <tr> <td>{{ item }}</td> <td><input type="number" style="width: 90px;" placeholder="Item value" id="item_value"></td> <td><input type="number" style="width: 90px;" placeholder="Item qt" id="item_qt"></td> <td><input type="number" style="width: 90px;" placeholder="Item total" id="item_total" onclick="calculateForm();"></td> </tr> {% endfor %} </tbody> And that's my script: var calculateForm = function () { document.getElementById("item_total").value = ( Number(document.getElementById("item_value").value) * Number(document.getElementById("item_qt").value) ) }; -
Django sign in form, the stylizing with Bootstrap is not doing anything
I am having some troubles with Django. So, I wanted to use Bootstrap´s sign in template and use it in my project. So, I have been able to do it correctly, except the username and password fields, which are showing up as regular {{form.username}} even though I have used the form-control class. Let me show you: forms.py from django import forms from django.forms import TextInput, PasswordInput class LogINFO(forms.Form): username= forms.CharField(label= 'Usuario: ', max_length=20, widget=forms.TextInput(attrs={"placeholder": "Username", 'style': 'width: 300px;', "class": "form-control"})) password=forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'style': 'width: 300px;', 'class': 'form-control'})) and my login.html {% csrf_token %} <div class="form-floating"> {{form.username}} </div> <div class="form-floating"> {{form.password}} </div> Well, it apparently omits everything and it just shows up as a regular form input. I am not using model as I am using the auth application. Every little bit of help is appreciated! -
Assertion Error when trying to create a view to update one field in model
I have a model that looks like this class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) is_online = models.BooleanField(default=False) is_active = models.BooleanField(default=False) I would like to create an API endpoint to update specifically the is_active field. This is what I have in my views to cater for this class UpdateProfileActive(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer lookup_field = 'profile.is_active' def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data='profile.is_active', partial=True) if serializer.is_valid(): serializer.save() return Response({"message": "user is active field has been updated"}) else: return Response({"message": "failed", "details": serializer.errors}) Here is my serializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = Base64ImageField(source='profile.profile_pic', max_length=None, use_url=True, required=False) is_online = serializers.BooleanField(source='profile.is_online', required=False) is_active = serializers.BooleanField(source='profile.is_active', required=False) # serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic', 'is_online', 'is_active'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False}, 'is_online': {'required': False}, … -
Sendgrid not sending email: 401 Unauthorized Django
I'm trying to send the email using SendGrid and I'm using django-sendgrid-v5 to send the email but I don't why it throws me the error. error HTTP Error 401: Unauthorized" settings.py EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') view.py from django.core.mail import send_mail send_mail('Here subject', 'Here is the message.', 'from_email', ['to_email'], fail_silently=False) -
Correct working thousand separator with locale awareness in Django 4.04
I'm looking for any possibility to humanize values not in general but for some selected values. To be more specific, it's about thousand separator. Enabling thousand separator like this: settings.py USE_L18N = True USE_THOUSAND_SEPARATOR = True views.py def test (request): return render (request, 'example.html', {'example_context_int': 1000}) example.html #... {% load_humanize %} {{ example_context_int }} generates 1.000 as output. This is followed by at least two problems: using any integer given by context as reference for creating links (e.g. passing object id) leads to something like link-to/1.000/ instead of link-to/1000/. pre-populating forms with any integer > 999 forces conversion to a float instead of an integer after submit (e.g. pre-populated 1.000 becomes 1 instead of 1000). This is a known issue. I got two possibilities to solve this: using |stringformat:"s" for any variable which shall not be humanized or converting every integer which is not allowed to be humanized into a string like str (example_context_int). Both methods have pros and cons and I don't prefer any of these. What I would prefer is to explicitly humanize values instead of this implicit conversion of all integers and floats. Following documentation on that, |intcomma have to be used on specific variables instead of … -
Django 4.0. Updating field once every day
Hello I am new to Django and was stuck. I have a Book model that has a integer field count which is the number of users that have this book in their readlist. Users can add a book to their ReadList model (many to many field). I want to update the count in the book model once a day...how should I go about doing this? Will be using this to displaying trending books and book rank based on user count. Book Model: class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) def __str__(self): return self.name ReadList Model: class ReadList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) readlist = models.ManyToManyField(Book, related_name='readlist', blank=True) def __str__(self): return self.user.username Any help is appreciated, thank you. -
How to update a many to many field in DRF
So in my project, I have a User model and a School model. My user model has a schools field that has an M2M relation with the School model. Now what I want to know is, how can I create a view that can take the email of a user and the school Id, and add the school or delete it from the schools that a user belongs to. Here is my user model: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) schools = models.ManyToManyField("School", related_name="members") USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } School: class School(models.Model): name = models.CharField(max_length=300, verbose_name='school name', ) principal = models.ForeignKey("User", related_name="my_schools", on_delete=CASCADE) address = models.CharField(max_length=200) class Type(models.IntegerChoices): PUBLIC = 1, "Public" PRIVATE = 2, "Private" type = models.PositiveSmallIntegerField(choices=Type.choices, default=Type.PUBLIC) class Level(models.IntegerChoices): NATIONAL = 1, "National" EXTRACOUNTY = 2, "Extra County" COUNTY = 3, "County" SUBCOUNTY = 4, "Subcounty" level = models.PositiveSmallIntegerField(choices=Level.choices, default=Level.COUNTY) def __str__(self): return self.name Here is the serializer to enroll the members: class EnrollSchoolMembersSerializer(): class … -
How to check the data of related fields for compliance with the user before creating a record in django rest framework?
Good evening, I need help. I recently started using django rest framework. I have an application in which the user model has a "company" field, so several users can be in the same company and work with common data. Each company can have one or more warehouses in which goods are stored (each company has its own) There is a page in which data is collected from forms in json and sent to the server via api [ { "id": 9, "doc_type": 1, "warehouse": 5, "date": "2022-06-07", "number": 98, "contragent": 3, "comment": "", "items": [ { "product": 7, "buy_price": "1689.00", "sell_price": "2000.00", "quantity": 1 } ] }, Problem: If the user somehow gets this api and changes the id for example of the "warehouse" field to the id of the warehouse of another company, then the document will be created anyway, also if the user replaces the id of the "product" field Question: How can I check the data for compliance with the user's company before creating it? Here is my code #models.py Class CustomUser(AbstractUser): ... company = models.ForeignKey(Company, on_delete=models.PROTECT, null=True) ... class Company(models.Model): name = models.CharField(max_length=50) ... class Warehouse(models.Model): name = models.CharField(max_length=200) company = models.ForeignKey(Company, on_delete=models.CASCADE) #serializers.py class ConsignmentNoteSerializer(serializers.ModelSerializer): … -
Am I on the right track to implementing multiple native and studying languages in a user signup form?
I am trying to create a simple digital flashcard-like learning platform, where a user can select their native languages and the languages they are studying. As you can imagine, there can be people who speak several languages at a native level, and I am sure there are people out there than are studying a bunch of languages. To outline my problem, let's just say a user is studying 20 languages and can speak 3 languages fluently. Eventually down the road, I would like to use the user's languages (both studying and native) and use them as a filtered drop-down choices. For example, they could attach one language to a card, but the language selection drop-down would show all their studying languages. I am not quite sure what I should be googling to figure out my language selection problem during user signup. I know I could easily accomplish this by hard-coding the fields in my User model, but that breaks the DRY principle and would probably become a mess to maintain, and then tried to accomplish this using the ArrayField, but in my admin the choices are not showing up and it's just a blank CharField. (Hard coded) Terrible Implementation I … -
Django DRF how to restrict access normal user to browsable api page and prevent unauthorized post request
I have an contact forms api for unauthenticated user. I integrated my api in reactjs. But anyone can view the json data if he directly visit the api url. Anyone can also submit post request using POSTMAN using the api url. How to restrict anyone to view the api page and also prevent unauthorized post request. here is my code: settings.py: REST_FRAMEWORK = { # Only enable JSON renderer by default. 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'anon': '10/minute', } } views.py api_view(['POST', 'GET']) def farhyn_api(request): if request.method == 'POST': data = request.data serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() print(serializer.data) return Response({ 'status': True, 'message': 'sucess' }) return Response({ 'status': False, 'message': serializer.errors }) if request.method == "GET": contact = Contact.objects.all() serializer = ContactSerializer(contact, many=True) return Response(serializer.data) I used AnonRateThrottle but still now anyone can submit POST request using the api url. How to prevent it? and also how to restrict access view api page? -
Is Django and ftplib connection posible?
I am trying to upload a file from a Django server to another FTP Server using ftplib This is what I am trying to do in views.py @background(schedule=1) def uploadToFTP(folder): """ Async function to upload the images to FTP Server. """ print("-------------------Start FTP ----------------------------") #establish ftp connection ftp = FTP(conf_settings.FTP_DOMAIN,conf_settings.FTP_USER, conf_settings.FTP_PASSWORD) file = os.path.join(folder, filename) ftp.storbinary('STOR ' + filename, file,102400) # send the file I am getting all sorts of errors like this: ftp.storbinary('STOR ' + filename, file,102400) File "/opt/anaconda3/lib/python3.8/ftplib.py", line 489, in storbinary buf = fp.read(blocksize) AttributeError: 'str' object has no attribute 'read' So I have tried many methods, but nothing works. Is this even posible.