Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create model instance with a button and no forms
I have a model with 2 fields, the first one is user and the second one is member. I want to create an instance just clicking a button without filling a form. I want to get the I want to get the user from the logged user and the member from the current block in the HTML This is my model: class Applicant(models.Model): member_proyect = models.ManyToManyField(Member, related_name=('vacancy')) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to get the user from the logged user. I did this for loop to display all the members in the HTML {% for member in member_list %} {% if member.proyect_id == page.id %} {% with n=forloop.counter %} <div class="accordion-item"> <h2 class="accordion-header" id="heading{{n}}"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{n}}" aria-expanded="false" aria-controls="collapse{{n}}"> {{member.rol}} </button> </h2> <div id="collapse{{n}}" class="accordion-collapse collapse " aria-labelledby="heading{{n}}" data-bs-parent="#accordionExample"> <div class="accordion-body"> {{member.content |safe }} <form action="" method="post"> <!-- I want to click this button and create the instance --> {% csrf_token %} <input type="submit" value="Aplicar" class="btn btn-primary" /> </form> </div> </div> </div> {% endwith %} {% endif %} {% endfor %} In this case, there is no form, just a button and I am not sure how to do it. -
Django + DRF + Djoser: Unable to send api request to create a user due to Forbidden (CSRF cookie not set.) error
I am using dojser urls to create a user. However I am unable to send api request due to the following error shown in the terminal Forbidden (CSRF cookie not set.): /auth/users/ [28/Mar/2022 16:44:56] "POST /auth/users/ HTTP/1.1" 403 2870 Below is my set up urls.py urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', "corsheaders", 'djoser', 'account', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL' : True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS':{ 'user_create': 'account.serializers.UserCreateSerializer', 'user': 'account.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } AUTH_USER_MODEL = 'account.CustomUser' The url at which I am sending the request to for creating a user is POST: http://127.0.0.1:8000/auth/users/ Please suggest me what should how to rectify the error. -
Why hide a django secret key?
I wanted to ask, why should I hide the secret key in a Django application? Why not just commit it to public source control? I understand the effects of an attacker finding out the secret key (from here). But if I just upload the code to github and ask people to download it, run python manage.py runserver and go to 127.0.0.1:8000, I don't need to hide it, right? Don't those effects of revealing the secret key apply for when you run the code on your device using your device as a server, and have them visit it at a public URL? If they're running it on their own device, that doesn't pose a security risk to me, right? I read that knowing the secret key can allow them to bypass form validations, etc. But they would just be messing up the db of their own local installation of the app so why should I care? -
Displaying table x's fields in GET request of table y that has foreign key of table x (Django)
I could use some help please, been stuck on this for awhile. I have two tables, Share and Fund. Share.py class Share(models.Model): ShareName = models.CharField(max_length=100, unique=True, default="N/A") ISINCode = models.CharField(max_length=100, primary_key=True, default="N/A") Fund.py class Fund(models.Model): FundID = models.AutoField(primary_key=True) FundName = models.CharField(max_length=100, default="N/A", unique=True) FundIdentifier = models.CharField(max_length=100, default="N/A") PercentOfFundNetAssets = models.DecimalField(decimal_places=2, max_digits=5, default=0.00) ISINCode = models.ForeignKey(Share, to_field='ISINCode', related_name="toshares", on_delete=models.CASCADE) class Meta: unique_together = ('FundIdentifier', 'ISINCode') Individually they has been no issue for GET/POST/PUT etc. Its important now though that on GET requests to fetch the fund table while also retrieving the relevant share fields that fall under each fund row. See below: What fund JSON looks like now upon GET request [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": "3.82", "ISINCode": "SHR001" }, ] What I want fund JSON to look like upon GET request [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": 3.82, "ISINCode": "SHR001", "share": [ { "ISINCode": "SHR001", "ShareName": "Some share" } ] } ] I'd also settle for something like this though. [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": 3.82, "ISINCode": "SHR001", "ISINCode": "SHR001", "ShareName": "Some share" } ] Either way, each fund json object will only have one share object within with its relevant fields … -
Does acccessing nested FK relation's field value downgrade performance?
I have various models which are interconnected through Foreign key relations, does doing this make any performance downside. I want to know how does django perform this internally. PriceSheet.objects.select_related('query').filter(id=pricesheet_id).values('query__campaign_name', 'query_id', 'query__campaign_status', 'query__lead_id', 'query__lead__legal_name', 'query__lead__brand_name' # nested 'query__lead__working_capital', 'query__lead__payment_terms', ) # 7 -
Running docker container: iptables failed
im moving a django app and dependencies (redis & celery) from docker containers hosted on VM to Azure app service but get the below error 2022-03-28T10:15:36.671Z ERROR - Container start failed for testoms_application_0_6c28f745 with System.AggregateException, One or more errors occurred. (Docker API responded with status code=InternalServerError, response={"message":"driver failed programming external connectivity on endpoint testoms_application_0_6c28f745 (a92233c6cf84a60789ac7fb71e71e3b1fbc358c4694917ce4210a73ebf412c05): (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 127.0.0.1 --dport 3062 -j DNAT --to-destination 172.16.4.3:0: iptables v1.6.1: Port 0' not valid\n\nTry iptables -h' or 'iptables --help' for more information.\n (exit status 2))"} ) (Docker API responded with status code=InternalServerError, response={"message":"driver failed programming external connectivity on endpoint testoms_application_0_6c28f745 (a92233c6cf84a60789ac7fb71e71e3b1fbc358c4694917ce4210a73ebf412c05): (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 127.0.0.1 --dport 3062 -j DNAT --to-destination 172.16.4.3:0: iptables v1.6.1: Port 0' not valid\n\nTry iptables -h' or 'iptables --help' for more information.\n (exit status 2))"} ) docker compose file points to port 8080 for django image, added WEBSITE_PORTS under configuration-> application settings. i have also set env variables under application settings. How do i fix this please -
django-grpc-framework: correct way to serialize/deserialize JSONFields?
what is the proper way to handle Django JSONFields in the django-grpc-framework ? How can I check, what kind of data is actually sent (Evans throw the same error) = When I try to receive a serialized JSONFiled with the django-grpc-framework, the following error is thrown in my data_grpc_client.py: python data_grpc_client.py Traceback (most recent call last): File "/my_data/data_grpc_client.py", line 8, in for datum in stub.List(my_data.lara_data_pb2.DataListRequest()): File ".../python3.9/site-packages/grpc/_channel.py", line 426, in next return self._next() File .../lib/python3.9/site-packages/grpc/_channel.py", line 826, in _next raise self grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.UNKNOWN details = "Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object." debug_error_string = "{"created":"@1648155177.535827174","description":"Error received from peer ipv6:[::1]:50051","file":"src/core/lib/surface/call.cc","file_line":905,"grpc_message":"Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object.","grpc_status":2}" I would be very happy for any help - thanks a lot in advance ! Elain Here are my python/proto modules - to reproduce the error: I have a django (4.0.3) model with a JSON field: # models.py class Data(models.Model): data_id = models.AutoField(primary_key=True) data_JSON = models.JSONField(blank=True, null=True, help_text="JSON representation of the data") My serializer.py looks like this: from my_data.models import Data from django_grpc_framework import proto_serializers from rest_framework import serializers import my_data.my_data_pb2 class DataProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: … -
Does render in Django obfuscate the HTML cord that it loads?
I am using render in Django to load an HTML file that contains different calculators/simulators. I would like to use render because I believe it may help obfuscate the HTML to code to prevent people from doing right click view source? Is this accurate? Are there other ways to achieve my goal of not having my HTML code be viewable? -
TypeError: render() missing 1 required positional argument: 'template_name'
I created simple form register user but something is wrong. This is my django project: settings.py account/urls.py forms.py views.py Directories: error: I don't understand this issue. I use render(request, 'name_template', {}) but django request name_template. What did I do wrong? Sorry for my english but I still learn ;) -
Django - grouping in serializer
I'm struggling to create a serializer that groups the result, I can make it my "dirty" way but i am curious what is the proper way my models: class Station(models.Model): type = models.ForeignKey(StationType, on_delete=models.SET_NULL, null=True) line = models.CharField(max_length=1) number = models.CharField(max_length=3) bool1= models.BooleanField( null=True, blank=True, default=False) bool2= models.BooleanField( null=True, blank=True, default=False) def str(self):return self.number my serializer: class mySerializer(serializers.ModelSerializer): class Meta: model = Station fields = ['line', 'number','bool1', 'bool2'] result: [ { "line": "1", "number": "001", "bool1": false, "bool2": false }, { "line": "1", "number": "001", "bool1": false, "bool2": false }, { "line": "3", "number": "013", "bool1": false, "bool2": false } ] expected result (more or less): [ {"line": "1",{ "number": "001", "bool1": false, "bool2": false }, { "line": "1", "number": "001", "bool1": false, "bool2": false }}, {"line": "3", { "number": "013", "bool1": false, "bool2": false }} ] I would be grateful for all kinds of help ;) If you could give me the source where I could learn more about serializers I would be even more grateful -
django Form, MultipleChoiceField and circular import
I try to setup a ModelForm Formset - with Checkbox fields... But if I set a queryset for my MultipleChoiceField I get an "ImportError" ImportError: cannot import name 'Event' from partially initialized module 'ferienspiel.event.models' (most likely due to a circular import) How can I make a queryset for my MultipleChoiceField-Fields in `forms.py? to avoid a circular import Error? My setup: - app --- model.py (contains Model and Formhandler, for Wagtail Page `def serve()` ) --- form.py (formset setup) --- ulrs.py --- views.py forms.py class ChildForm(ModelForm): def __init__(self, *args, **kwargs): super(ChildForm, self).__init__(*args, **kwargs) self.fields["event"].widget = CheckboxSelectMultiple() self.fields["event"].queryset = Event.objects.all().order_by("date", "time") class Meta: model = Child fields = ("first_name", "last_name", "date_of_birth", "text") widgets = { ... ... model.py class Event(Page): location = models.TextField(max_length=500, null=False) date = models.DateField(null=False) time = models.TimeField(null=False) class EventRegistrationPage(Page): intro = models.TextField(blank=True) def serve(self, request): if request.method == "POST": parent_form = ParentForm(request.POST, request.FILES) childs_form = ChildFormSet(request.POST, request.FILES) if all([parent_form.is_valid(), childs_form.is_valid()]): for child in childs_form: # print(f"child {child.cleaned_data}") if child.is_valid(): new_child = child.save(commit=False) new_child.parent = new_parent new_child.save() new_child.event.set( child.cleaned_data.get("event") ) child.save_m2m() childs_data.append(new_child) -
Django Select2 ModelSelect2TagWidget Problem
I followed the documentation on how to use the ModelSelect2TagWidget from the django-select2 library, but when I submit the form I get "Select a valid choice error" on the tag field regardless the tag is saved in the database. models.py class FromTo(models.Model): from_to = models.CharField(max_length=100) class Course(models.Model): from_to = models.ForeignKey( FromTo, null=True, on_delete=models.SET_NULL) forms.py class FromToWidget(s2forms.ModelSelect2TagWidget): queryset = models.FromTo.objects.all() search_fields = ['from_to__icontains'] def value_from_datadict(self, data, files, name): values = super().value_from_datadict(data, files, name) queryset = self.get_queryset() pks = queryset.filter( **{'pk__in': [v for v in values if v.isdigit()]}).values_list('pk', flat=True) cleaned_values = [] for val in values: if represent_int(val) and int(val) not in pks or not represent_int(val) and force_text(val) not in pks: val = queryset.create(from_to=val).pk cleaned_values.append(val) return cleaned_values class CourseModelForm(forms.ModelForm): from_to = forms.ModelChoiceField( models.FromTo.objects.all(), widget=FromToWidget(model=models.FromTo)) -
Issue with Django redirect to previously visited page
I am trying to update the login view. For now, if someone will try to enter http://127.0.0.1:8000/articles/ then the user is redirected to http://127.0.0.1:8000/ (login page) and after successful log, it is redirected to http://127.0.0.1:8000/home. What I want is to redirect users to the page they tried to visit before logging in. So if someone will try to visit http://127.0.0.1:8000/articles then after log in the website should redirect him to the articles page, not to home. This is what I tried: views.py class UpdatedLoginView(LoginView): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST['next']) login.html <form method="post" class="login-form background" novalidate> {% csrf_token %} {{ form|crispy }} {% if request.GET.next %} <input type="hidden" name="next" value="{{request.GET.next}}" /> {% endif %} <button type="submit" class="text-center mx-auto border-0 join-btn col-sm-12 col-md-6 main-btn">Login</button> <a href="{% url 'login' %}?next={{request.get_full_path|urlencode}}">Login test</a> // this is just a test element, I want to have button in my form </form> My question is how to modify UpdatedLoginView and form in order to redirect users to previously visited page. The code I tried is taken from here. -
Why is Django letting me instantiate a model without a required field?
I have the following model in Django (using v4.0): class MyModel(models.Model): owner = models.OneToOneField(OtherModel, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50) value = models.FloatField(default=0) # Some methods ... My question is why I don'get any errors when I execute anywhere the following code: new_model = MyModel.objects.create(owner=get_valid_owner(), value=500) Shouldn't name be required since I did not set blank=True to it? If I got it wrong, how can I make that field required? Thanks in advance. -
Not able to scrape data from ziprecruiters.com
I want to scrape some job data from ziprecruiters.com for populating my database. It is working with indeed but not with ziprecruiters.com class Command(BaseCommand): base_url = "https://www.ziprecruiter.com/" def generate_search_url(self, radius, search, location): url_template = self.base_url+"candidate/search?radius={}&search={}&location={}" url = url_template.format(radius, search, location) return url def request_url_from_website(self, url): response = requests.get(url, verify=False, timeout=10,) if response.status_code == 200: return response.text else: return response.reason command_class = Command() url = command_class.generate_search_url("10","python","remote") print("Generated url: ", url) request_url = command_class.request_url_from_website(url) print("Response received: ", request_url) Generated url: https://www.ziprecruiter.com/candidate/search?radius=10&search=python&location=remote Response received: Forbidden -
django filters - dictionary of filters alongside Q filtering
I have a django query which is built from URL get paramaters. These are constructed by a dictionary named 'filters': filters['published_date__year'] = year filters['published_date__week'] = week filters['source__slug'] = source queryset = Headline.objects.filter(**filters) What I'm also wanting to do is apply multiple AND filters on a field name 'tag'. filter1 = Q(tags__slug=windows) filter2 = Q(tags__slug=microsoft) Where the results would be filtered to only show headlines that have windows AND microsoft. Is it possible to apply both these Q filters, alongside the standard ones? Cheers -
What is a "slug" in Djang0?
How does slug work on this site?? This is slug test. Stack over flow slug test. When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used? a=1 b=1 c=a+b print(c) -
Not getting perfect results using ngram
this is the python code , the model includes many foreign key connections.I dont know how to make accurate matching. we need accurate results for example instacart.com , this website is made with elasticsearch. class ProductSearchelastic(generics.ListAPIView): # serializer_class = ListVariantSerializer permission_classes = [AllowAny] pagination_class = SmallPagesPagination queryset=Variant.objects.all() serializer_class = NewsDocumentSerializer def get(self, request,*args,**kwargs): query=self.request.GET.get("q",None) query=query.lower() # super().get(self,request,*args,**kwargs) try: document = NewsDocument # serializer_class = NewsDocumentSerializer # fielddata=True search = NewsDocument.search() # search = search.filter('match', code=query) groupField=Item.objects.filter(group_id__name=query).first() uomField = Item.objects.filter(uom_id__name=query).first() materialField = Item.objects.filter(material_id__name=query).first() brandField = Item.objects.filter(brand_id__name=query).first() categoryField = Item.objects.filter(group_id__category_id__name=query).first() divisionField = Item.objects.filter(group_id__category_id__division_id__name=query).first() itemField = Item.objects.filter(name=query).first() variantField = False if divisionField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=divisionField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if categoryField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=categoryField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if brandField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=brandField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if materialField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=materialField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page = self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if uomField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=uomField.code) ) # print("search",search1.to_queryset()) v=NewsDocumentSerializer(search1,many=True) page =self.paginate_queryset(v.data) return Response ({'status':'success','response_code':200,"data":self.get_paginated_response(v.data)}) if groupField: search1 = search.filter( 'nested', path='item_id', query=Q('match', item_id__code=groupField.code) … -
Upload a CSV file to a DB table in Django
I am trying to develop a button that uploads a CSV that has some words in it to a DBtable through a button, the problem is that when I click the button nothing happens, I don't know if I'm missing something or I have to do it some other way. Thank you views.py: def uploadWords(request): up = request.POST.get('Upload') if up == "Upload": if request.user.is_authenticated: form = UploadFileForm() if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] usr = User.objects.get(username=request.user) if file.name.endswith(".csv"): reader = csv.reader(file) for row in reader: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() messages.success(request, "File uploaded successfully") return redirect("home") else: messages.info(request, "File is not csv") return redirect("home") context = {'form': form} return render(request, "base.html", context) else: return redirect("index") urls.py: urlpatterns = [ path('', views.index, name='index'), path('home/', views.home, name='home'), path('login/', views.loginView, name='login'), path('logout/', views.logoutUser, name='logout'), path('register/', views.register, name='register'), path('upload/', views.uploadWords, name='upload'), ] base.html: <div style="text-align:center;display:block;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=".csv, .xlsx"> <br> <button class="button btn btn-primary" type="submit" name="up" value="Upload">Upload</button> </form> </div> -
CSRF verification failed. Request aborted error for sending request error. Unable to send api request to djoser urls
I am trying to use djoser to create user. So I am using vscode thunder client to do send the api request. However even after writing the url correctly along with the trailing slash I am still getting the below error Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. This is how I have configured the settings and the urls urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL' : True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS':{ 'user_create': 'account.serializers.UserCreateSerializer', 'user': 'account.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } Please suggest what should I do. -
Which one to use [closed]
I am creating a enterprise web application, I want it to be scalable, super fast, secure. I want to do it with django(python), spring boot(Java), asp.net(c#), Can someone tell me which one to use with my above requirements -
I want to get e-mail authentication
An authentication number function that generates eight random characters was implemented. i inputted username, and mail. because i want to write searching password html and request it at view with Ajax. When I enter my username and email, I want the authentication number to be sent to the email. At the same time, the code created in ajax should show the authentication number window. but, it happened nothing. what should i do...? help me! #html <body> {% block content %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="inner-box"> <div class="title"> <h1>비밀번호 찾기</h1> </div> <div class="input-box"> <div class="id"> <input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required /> </div> <div class="password"> <input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required /> </div> </div> <div class="btn"> <div class="btn-white" id="btn_white"><button type="submit">임시 비밀번호 발송</button></div> </div> <div class="loading-box"> <div id="loading"></div> </div> </div> <script> $(document).ready(function () { $('#find_pw').click(function () { $('#loading').replaceWith('<div id="loading_end" class="loading"></div>') var name = $("#pw_form_name").val(); var email = $("#pw_form_email").val(); $.ajax({ type: "POST", url: "/users/recovery/pw/find/", dataType: "json", data: { 'name': name, 'email': email, 'csrfmiddlewaretoken': '{{csrf_token}}', }, success: function (response) { // loading_end 이걸 지움 $('#loading_end').remove() alert('회원님의 이메일로 인증코드를 발송하였습니다.'); // 나는 이메일전송버튼이지 $('#btn_white').remove() $('#result_pw').replaceWith( '<hr><div class="row justify-content-md-center"><form class="form-inline" … -
Ordering alphabetically words and numbers in django
I have a queryset to be ordered alphabetically. I have this series of names such as: Mission 1, Mission 2 etc. My problem is that, once the database has more than 9 entries, the sorting works like that: Mission 1, Mission 11, Mission 2, Mission 3 etc. I tried a query like: Mission.objects.all().order_by('name') but the problem is still there. I need to have an order like --> Mission 1, Mission 2 .... Mission 9, Mission 10, Mission 11 etc. -
Controlling access to fake model in Django admin
I have the below code in admin.py where it creates models. However, this model is available to anyone in the system how can i control access to this model like any other model class BalaceForm(admin.ModelAdmin): def has_add_permission(*args, **kwargs): return False def has_change_permission(*args, **kwargs): return True def has_delete_permission(*args, **kwargs): return False def changelist_view(self, request): context = {'title': 'My Custom AdminForm'} if request.method == 'POST': form = CustomerProfilesForm(request.POST) if form.is_valid(): # Do your magic with the completed form data. # Let the user know that form was submitted. messages.success(request, 'Congrats, form submitted!') return HttpResponseRedirect('') else: messages.error( request, 'Please correct the error below' ) else: form = CustomerProfilesForm() context['form'] = form return render(request, 'admin/change_form.html', context) class AccountStats(object): class _meta: app_label = 'onboardapi' # This is the app that the form will exist under model_name = 'account-stats' # This is what will be used in the link url verbose_name_plural = 'Account summary' # This is the name used in the link text object_name = 'ObjectName' app_config = "" swapped = False abstract = False admin.site.register([AccountStatsAll],BalaceForm) -
How to get image url directly in django queryset
I have a filefield where images are present, class MyModel(models.Model): display_picture = models.FileField(blank=True, null=True) # #In Use this field is in use so I can not make any model changes. Now this model is connected to another model PriceList. Now previously I was making two db query with one to MyModel and another to PriceList. But right now as they are connected, i want to do this in a single query. so my query looks something like this ( I am accessing the MyModel through PriceList so I am making a query over PriceList, as they are connected through a inf field ) all_info_with_price_list.values('inf__display_picture', # I can do this 'inf__display_picture__url' # but not this ) How can I get the url in the query itself? just doing inf__display_picture gives me the complete filename.