Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the purpose of Django Secret Key?
I want to know the purpose of SECRET KEY in Django. And what happens if the secret key is exposed to someone or on GITHUB or any other distributing platform publically? I have tried to read the documentations but I want to know the usage in clear words. -
django oauth2 invalid client
oauth in development server is working fine. However oauth in apache server is returning "invalid_client". curl -X POST -u "<clientid>:<clientsecret>" -d "grant_type=password&username=<username>&password=<password>" http://localhost:8000/api/o/token/ Token returned successfully. However when using the exact same syntax in my apache server (only difference being servername) its returning {"error": "invalid_client"}. curl -X POST -u "<clientid>:<clientsecret>" -d "grant_type=password&username=<username>&password=<password>" http://servername.com/api/o/token/ -
Trying to convert Left Join of SQL into Django query-set?
here is my models.py file class Customer(models.Model): """All Customers details goes here""" name = models.CharField(max_length=255, null=False) firm_name = models.CharField(max_length=255, null=False) email = models.EmailField(null=False) phone_number = models.CharField(max_length=255, null=False) location = models.CharField(max_length=255,null=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: """Meta definition for Customer.""" verbose_name = 'Customer' verbose_name_plural = 'Customers' def __str__(self): """Unicode representation of Customer.""" return self.name class Order(models.Model): """All order details goes here.It has OneToMany relationship with Customer""" STATUS = ( ('CR', 'CR'), ('DR', 'DR'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) bill_name = models.CharField(max_length=255, null=False) payment_date=models.DateField(auto_now=False) status = models.CharField(max_length=255, choices=STATUS, null=False) amount = models.FloatField(max_length=255, null=False) date_created = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True) class Meta: """Meta definition for Order.""" verbose_name = 'Order' verbose_name_plural = 'Orders' def __str__(self): """Unicode representation of Order.""" return self.bill_name i want to access only Customer's name and all fields of Order,in short i want to convert the following SQL in Django Query-set select name ,bill_name ,status from accounts_customer left join accounts_order on accounts_customer.id = accounts_order.customer_id where accounts_order.status="DR"; -
How to filter an empty list? Many to many relationship
I filter as follows: queryset = queryset.prefetch_related( Prefetch('level', queryset=Level.objects.filter(id=level))) In this case, empty lists remain: { ... "level": [] ... }, { ... "level": [ 2 ] ... } I tried to filter like this: queryset = queryset.prefetch_related( Prefetch('level',queryset=Level.objects.filter(id=level).exclude(id__isnull=True))) But it didn't help. I also want to know if it is possible to get a value without lists? { ... "level": 2 ... } -
How to render the column of dataframe in django template and make it clickable?
i have a data frame a b c d e 0 51 53 65 61 54 1 69 5 46 9 44 2 30 31 3 65 5 3 25 38 46 43 15 4 81 37 57 67 17 5 9 39 12 38 32 6 56 41 84 62 62 7 28 6 38 80 17 8 16 85 28 89 24 9 11 98 94 47 36 Now i want to render the column name of this dataframe in my django template. some thing like this. Some heading here: a b c d e where each name should be clickable.When someone will click on any name (suppose i click on 'b') then the data of 'b' should stored in the some other variable. eg. i clicked on 'b' then in views.py the data of b gets stored as a single column in 'new' the resultant output should look like: new 0 53 1 5 2 31 3 38 4 37 5 39 6 41 7 6 8 85 9 98 I'm new to django so it would also be helpful if someone can improve or suggest changes to this question . Thanks in advance -
OSError: no library called "cairo" was found
i am running a project that i cloned from git. I already installed the all packages from requirements.txt. And when i run command: python manage.py runserver i got the below error at end that is OSError: no library called "cairo" was found. I am new to django can you please guide me that how can i overcome this error. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\UMAIR\Documents\python_projects\saleor-master\saleor\plugins\checks.py", line 20, in check_plugins check_single_plugin(plugin_path, errors) File "C:\Users\UMAIR\Documents\python_projects\saleor-master\saleor\plugins\checks.py", line 43, in check_single_plugin plugin_class = import_string(plugin_path) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\UMAIR\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
django: part of javascript translation doesnot work
here is my code: text += "<li>" + gettext(" Start from: ") + "<br>" + data[i].start_name + "<br>" + "<br>" + gettext(" Line ID: ") + line_id + "<br>" + "<br>" + gettext(" Departs at: ") + getTime(data, i) + `<div id='arrival_${stop_id}'></div>` + "<br>" + gettext(" Arrives to: ") + "<br>" + data[i].end_name + "<br>" + "<br>" + gettext(" Stops: ") + data[i].num_stops + " • " + data[i].travel_time + "mins <span id='arrow'>&#9660</span>" + "<div id='directions_stops_list'>"; in my djangojs.po file, there are only : #: .\static\javascript\modals.js:49 msgid " Arrives to: " msgstr " 到达:" #: .\static\javascript\modals.js:54 msgid " Stops: " msgstr "站点:" so part of gettext are found by django. but Why can't it read: gettext(" Start from: "),gettext(" Line ID: ") and gettext(" Departs at: ")? -
Pythonanywhere is giving NOREVERSEMATCH at/blog but the localhost is working perfectly
Pythonanywhere is giving NOREVERSEMATCH at/blog but the locahost is working perfectly. I have gone and resaved the project and committed it again to GitHub as well as pulling it on pythonanywhere. But is still not working. I tried to reload it but is still doing the same. NoReverseMatch at /blog/ Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['user\/(?P[^/]+)\/profile\/$'] -
populating models in django using faker
Why this code is not throwing an Integrity Error: Unique constraint failed. In the population.py file:- the line top = add_topic() will be called 10 times, which means it will create 10 instances of the Topic table, but it can't create 10 instances of Topic table because the column it has is unique. So, my question is should this code not throw a unique constraint Error? Because it's not and is running just fine. Why? #models.py file from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length = 264,unique = True ) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) name = models.CharField(max_length = 264, unique = True) url = models.URLField(unique = True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.CASCADE) date = models.DateTimeField() def __str__(self): return str(self.date) #population.py file import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','protwo.settings') import django django.setup() import random from first_app.models import AccessRecord,Topic,Webpage from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N = 10): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic = top, url … -
in Django How to filter dropdown selection list as ForeignKey
in Django How to filter dropdown selection list as ForeignKey only those patient which are assigned to a doctor because in Appointment Model I already select a doctor now after selecting a doctor I want to show only patient with foreginkey of that doctor not all patient class Patient(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, null=True, blank=True) doctor = models.ForeignKey(Doctor, null=True, blank=True ,on_delete=models.SET_NULL) class Appointments(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(USER, null=True, blank=True, on_delete=models.SET_NULL) doctor = models.ForeignKey(Doctor, null=True, blank=True ,on_delete=models.SET_NULL) patient = models.ForeignKey(Patients, on_delete=models.CASCADE, null=True, blank=True) -
Multiple values from many to many field in one html div class - Django
I have a item model that contains a many to many field. Now I am trying to show the value of the field into the template for the sake of filtering. I need to get the multiple values into one and the same div. views.py def get(self, request): items = Item.objects.all() context_item = {'items': items} return render(request, self.template_name, context_item) I am returning the instances with the following html {% for i in items %} {% for group in i.itemgroups.all %} <div class="card {{ group }}"> FOO </div> {% endfor %} {% endfor %} Obviously this return multiple divs, depending on the number of groups that are attached to the item instance. Is it possible to somehow get all the groups into one div, so it will return multiple groups in one line rather then output a single div for every group value? -
Accessing user details in django
I have a question. I have a blog where users can log in and post or comment something. When they are posting or commenting the text appears with their name as links on the right side(see picture). Now I want to have a userprofile page where the email name etc. are displayed. So I have to grab the name from the first template and use it. Now I can grab their name :) but I don't know how to use them. For example the users name is alex. I can display alex on the new template but what I need is something like that. alex.email or alex.name. Thank you very much. view.py @login_required def user_profile(request,username): return render(request, "user_profile.html",{'username':username}) home.html this is the template where I want to grab his name {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left mx-auto"> {% for posts in postmodel_list %} <div class="card mb-4 block"> <a class="overlay" href="{% url 'post_detail' posts.slug %}"style="text-decoration:none"> </a> <div class="card-body inner"> <h2 class="card-title">{{ posts.post }}</h2> <p style="text-align:right;" class="card-text text-muted h6"><a style="text-decoration:none" href="{%url 'user_profile' posts.author %}">@{{ posts.author }}</a> </p> </div> </div> {% endfor %} </div> </div> </div> … -
how to update a extended Django User model?
I have created the user authentication system which includes both the default User model and an extended User model. They are as below: from django.db import models from django.urls import reverse from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) Photo = models.ImageField(upload_to='documents/%Y/%m/%d/', null=True) uploaded_at = models.DateTimeField(auto_now_add=True, null=True) dob = models.DateField(max_length=20, null=True) country = models.CharField(max_length=100, null=True) State = models.CharField(max_length=100, null=True) District = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=10, null=True) def get_absolute_url(self): return reverse('profile', kwargs={'id': self.id}) forms.py class UserProfileForm(forms.ModelForm): Photo = forms.ImageField( max_length=100) dob = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'})) country = forms.CharField(max_length=100) State = forms.CharField(max_length=100) District = forms.CharField(max_length=100) phone = forms.CharField(max_length=10) class Meta: model = UserProfile fields = ('Photo', 'dob', 'country', 'State', 'District', 'phone') With the help of the above model and form, I am able to create user, and enter values for those custom model fields and see the user profile. So far so good. However, I am facing issues while I update those custom fields. I have used the Django's in-built modules to update the default User fields(email). But I am not able to find a way to update those custom fields('dob', 'country', 'State', 'District', 'phone'). Below is the method from views. views.py @login_required(login_url="/login/") def editUserProfile(request): if request.method == "POST": … -
The sql string from queryset of django cannot be executed in pymysql?
I'm using Django to make some param filtering, and then I got a filtered queryset like below: sql_str = str(my_queryset.query) # print(sql_str) SELECT `market_accounts`.`agency`, `market_accounts`.`id`, `market_accounts`.`entity`, `market_accounts`.`related_entity` , `market_accounts`.`type`, `market_accounts`.`our_side_entity`, `market_accounts`.`short_title`, `market_accounts`.`titl e`, `market_accounts`.`settlement_type`, `market_accounts`.`ae`, `market_accounts`.`sale`, `market_accounts`.`medium`, `m arket_accounts`.`is_pc`, `market_accounts`.`is_new_customer` FROM `market_accounts` WHERE (`market_accounts`.`entity` LIK E %madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR `market_accounts`.`short_title` LIKE %madbaby% OR `market_accounts`.`title` LIKE %madbaby%) ORDER BY `market_accounts`.`id` DESC And for some reason I want to execute the sql above by pymysql, but error showed like : # cursor.execute(sql_str) pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near '%madbaby% OR `market_accounts`.`related_entity` LIKE %madbaby% OR ` market_acco' at line 1") Get Data Error! Why the sql string generated by django cannot be executed by pymysql? -
How to change form field attribute in the view?
I have a model form containing four fields, by default only one field is active waiting for the user input. class SaleOrderInvoiceForm(forms.ModelForm): class Meta: model = SaleOrderInvoice fields = ( 'supplier', 'sale_order', 'invoice_number', 'invoice_date', ) widgets={ 'supplier':forms.Select(attrs={'class':'form-control'}), 'sale_order':forms.Select(attrs={'class':'form-control', 'disabled':'disabled'}), 'invoice_number':forms.TextInput(attrs={'class':'form-control', 'disabled':'disabled'}), 'invoice_date':forms.DateInput(attrs={'class':'form-control','type':'date','disabled':'disabled'}), } Based on the user selection of the first input, the rest of the form is loaded via AJAX. Now in the view, after necessary filtering, I want to swtich the disabled form fields to enabled and the enabled to disabled. I have tried the following but with no luck. form = SaleOrderInvoiceForm() form.fields['sale_order'].disabled = True form.fields['sale_order'].disabled = False form.fields['invoice_number'].disabled = False form.fields['invoice_date'].disabled = False can anyone suggest a way forward with this? -
I can't use unicode characters in EMAIL_PASSWORD with django
I am using django 3.0.8 and in my settings.py, I've specified the password for my e-mail account using EMAIL_PASSWORD = '...'. My password contains umlauts and upon manually sending a mail from the shell I get this error: >>> from django.core.mail import send_mail >>> send_mail('Django mail', 'This e-mail was sent with django', ..., fail_silently=False) Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/admin/.local/lib/python3.6/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/admin/.local/lib/python3.6/site-packages/django/core/mail/message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/admin/.local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/admin/.local/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.6/smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "/usr/lib/python3.6/smtplib.py", line 630, in auth response = encode_base64(initial_response.encode('ascii'), eol='') UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 19: ordinal not in range(128) If I remove the umlaut everything works as it should. Apparently smtplib manually encodes with ascii and I don't know how to tell it not to. Any ideas? -
Django rules re-using predicate
I've created 2 predicate's, which are extremely similar in nature. One consumes a list and the other a static string. @rules.predicate def can_edit_items(user, fields): for perm in user.groups.all() if perm.name not in settings.fields[fields] return False return True @rules.predicate def can_edit_specific_item(user, field): for perm in user.groups.all() if perm.name not in settings.fields[field] return False return True My requirements are that can_edit_specific_item() must make use of can_edit_items() by passing in a single string field_1 I've tried creating the following variation, but it doesn't seem to work as I intend it to @rules.predicate def can_edit_specific_item(user, field): for perm in user.groups.all() if perm.name not in can_edit_items[field] return False return True -
MultiValueDictKeyError, when I press sign up button
<div class="modal-signin" > <h1>Login</h1> <button id="exit_login">X</button> <div class="form-for-signin"> <center> <form id="login-form" method="post"> {% csrf_token %} <label id="username-label">Username:</label><br> <input class='username-input-field' id={{ form.username }} <br> <label id="password-label">Password:</label><br> <input class="password-input-field" id={{ form.password }} <br> <button type="submit" class="submit-btn">Log in</button> </form> </center> </div> <div class="social-links"> <div id="social"> <a class="facebookBtn smGlobalBtn" href="#"></a> <a class="twitterBtn smGlobalBtn" href="#"></a> </div> <div class="dont-have-an-account"> <p>Don't have an account?<button id="sign-up-button" style="font-size: inherit; outline: none; background: none; border: none">Sign up</button></p> </div> </div> </div> <div class="modal-signup"> <center> <form method="post"> {% csrf_token %} <h1>Sign up</h1> <div class="inside-the-signup-form"> <label id="first-name-label">First name:</label><br> <input id="{{ form_signup.first_name }}" required> <br> <label id="last-name-label">Last name:</label><br> <input id="{{ form_signup.last_name }}"><br> <label id="username-label">Create Username:</label><br> <input id="{{ form_signup.username }}"><br> <label id="email-label">Email:</label><br> <input id="{{ form_signup.email }}"><br> <label id="createpassword-label">Create password:</label><br> <input id="{{ form_signup.password }}"><br> <label id="password2-label">Confirm password:</label><br> <input id="{{ form_signup.password2 }}"><br> </div> <button type="submit">Sign Up</button> </form> </center> def logging_in(request): if request.method == 'POST': form= LoginForm(request.POST) username = request.POST['username'] password = request.POST['password'] user= authenticate(username=username, password=password) if user is not None: if form.is_valid(): login(request, user) messages.success(request,'Logging in...') else: messages.error(request,'username or password is incorrect') form= LoginForm() else: form = LoginForm() return render(request, 'home.html', {'form': form}) def sign_up(request): if request.method == 'POST': form_signup = SignUpForm(request.POST) if form_signup.is_valid(): password= request.POST['password'] password2= request.POST['password2'] if password != password2: messages.error(request,'Password does not match') form_signup= … -
How to join multiple Model in Django Rest Framework serializer
In Django, I have the following models. class Property(models.Model): address1 = models.CharField(max_length=512) address2 = models.CharField(max_length=128, blank=True, null=True) property_type = models.ForeignKey('PropertyType', models.DO_NOTHING, null=True, blank=True, default=None) geo_info = models.ForeignKey(GeoInfo, models.DO_NOTHING) class Meta: indexes = [ models.Index(fields=['address1', ]), ] db_table = 'property' class PropertyType(models.Model): name = models.CharField(max_length=128, blank=True, null=True) category = models.CharField(max_length=45, blank=True, null=True) color = models.CharField(max_length=45, blank=True, null=True) class Meta: db_table = 'property_type' indexes = [ models.Index(fields=['name', ]), ] class GeoInfo(models.Model): zipcode = models.CharField(max_length=25, blank=True, null=True) city = models.CharField(max_length=45, blank=True, null=True) state = models.CharField(max_length=45, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: db_table = 'geo_info' indexes = [ models.Index(fields=['zipcode', ]), models.Index(fields=['city', ]), ] def __str__(self): return '%s %s' % (self.zipcode, self.city) I'm trying to use Django REST Framework to serialize PROPERTY model as follows. class GeoSerializer(serializers.ModelSerializer): class Meta: model = GeoInfo fields = ['zipcode', 'city', 'state'] class PropertyTypeSerializer(serializers.ModelSerializer): class Meta: model = PropertyType class PropertySerializer(serializers.ModelSerializer): address_geo = GeoSerializer(many=False, read_only=True) prop_type = PropertyTypeSerializer(many=True, read_only=True) class Meta: model = Property fields = ['id', 'address1', 'address_geo', 'prop_type'] My expected outcome for each item is like { "id": 1, "address1": "test address", "geo_info":{ "zipcode":"12121", "city":"12121", "state":"12121", }, "property_type": "unknown", } and currently, I'm just getting the property data like { "id": 1, … -
Testing Model, View and Serializer in Django/DRM
I'm through my first project in Django & Django-rest-framework, and now i have to do the testing but i'm not sure what and how to test, i tried different methods but never succeded, below the code samples: models.py class Agent(models.Model): class Meta: db_table = 'itw_agent' verbose_name = 'agent' verbose_name_plural = 'agents' user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) phone = models.IntegerField() deleted = models.BooleanField(default=False) company = models.ForeignKey(Company, related_name='agents', on_delete=models.CASCADE) views.py class AgentListCreateView(ListCreateAPIView): queryset = Agent.objects.all() serializer_class = AgentSerializer permission_classes = [AllowAny] def get_serializer_class(self): return AgentSerializer class AgentRetrieveUpdateDestroyView(RetrieveUpdateDestroyAPIView): queryset = Agent.objects.all() serializer_class = AgentSerializer permission_classes = [AllowAny] def get_serializer_class(self): return AgentSerializer serializer.py class UserSerializer(ModelSerializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] class AgentSerializer(ModelSerializer): user = UserSerializer() class Meta: model = Agent fields = ['user', 'phone', 'company'] def create(self, validated_data): user = validated_data.pop('user') new_user = User.objects.create(**user) agent = Agent.objects.create(user=new_user, company=validated_data['company'], phone=validated_data['phone']) return agent def update(self, instance, validated_data): validated_user = validated_data.pop('user') user = instance.user user.username = validated_user['username'] user.first_name = validated_user['first_name'] user.last_name = validated_user['last_name'] user.email = validated_user['email'] user.password = validated_user['password'] user.save() validated_data['user'] = User.objects.get(id=user.id) return super(AgentSerializer, self).update(instance, validated_data) -
DJANGO | How to make the object in the application take the value of the name when viewing the list
https://i.stack.imgur.com/30M2y.jpg - Image Admin Panel Admin Code: from django.contrib import admin from .models import Destination admin.site.register(Destination) Summery: I did dynamic migration to the main page. I want the name of the destination to be accepted in the list in admin panel. How to do it? -
how to create a password protected post page
So I have develop a web site by django, everything works fine now. But I want to make one post that are protected by password which means you need to put in password to view the content of post. I search the internet and really didn't found a way to do that, some suggested hard code in post with password. I want more dynamic where you can edit in you admin post page with password protect option. similar to question here. -
Group serializer in elasticsearch+django
I am using elastic search in django project. In django, if you want to serialize a list of dictionaries you can do it by GroupModelserializer. I am not sure about how to do it with elastic search serializers. "items": [ { "name": "Milk", "uid": "VKQEF" }, { "name": "Juice", "uid": "ZYJXL" } ] I want to create this field which store multiple objects in elastic search and how to to create custom fields methods in elastic search serializers. -
Middleware django authenticate
I want to create middleware that authenticate user role = "level1' or role = "level2" if user login for level 1 they only see level 1 content and if user login level 2 they can see both level 1 and level 2 content from django.shortcuts import render from django.http import HttpResponse from .forms import loginForm from .models import memberModel # Create your views here. def login(request): lf = loginForm return render(request, 'member/login.html', {'lf':lf}) def getLogin(request): username = request.POST['username'] password = request.POST['password'] user = memberModel.objects.get(username = username) if (user.password == password): if (user.role == 'level1'): return HttpResponse('you are level 1 basic') else: return HttpResponse('you are VIP') else: return HttpResponse('login fail') def level1(request): #if login level 1 and level 2 role can see this return render(request, 'member/level1.html') def level2(request): # only login level 2 role can see this return render(request, 'member/level2.html') how can i do that, please help -
Function pgp_sym_encrypt(numeric, unknown) does not exist
I am using https://github.com/incuna/django-pgcrypto-fields for pgcrypto in my Django project. It's working fine with inserting, updating fields. But when I am trying something like MyTable.objects.filter(some_code=somecode).update( some_value=some_price * F('some_units'), updated_on=datetime.now() ) Its throwing me psycopg2.errors.UndefinedFunction: function pgp_sym_encrypt(numeric, unknown) does not exist Any help would be great. Thanks :)