Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
White page why clicking on button
I've created a button which is supposed to make a redirection on a new page. But when I click on it, I got a white page without any information on it. Here is the urls.py for the file. url(r'^layer_quarantine/', TemplateView.as_view(template_name='layer_quarantine.html'), name='layer_quarantine'), Here's the file named _layer_quarantine.html {% extends "layers/layer_base.html" %} {% load i18n %} {% load staticfiles %} {% load url from future %} {% load base_tags %} {% block title %} {% trans "Explore Layers" %} - {{ block.super }} {% endblock %} {% block body_class %}layers explore{% endblock %} {% block body %} <div class="page-header"> {% user_can_add_resource_base as add_tag %} {% if add_tag %} <a href="{% url "layer_upload" %}" class="btn btn-primary pull-right">{% trans "Upload Layers" %}</a> <a style="margin-right:30px" href="{% url "layer_browse" %}" class="btn btn-success pull-right"> {% if LANGUAGE_CODE == "fr" %} Toutes les couches {% else %} All layers {% endif %}</a> {% endif %} <h2 class="page-title"> {% if LANGUAGE_CODE == "fr" %} Couches en attente de validation {% else %} Layers awaiting validation {% endif %} </h2> </div> {% with include_type_filter='true' %} {% with facet_type='layers' %} {% with header='Type' %} {% with filter='type__in' %} {% include "search/_search_content.html" %} {% endwith %} {% endwith %} {% endwith %} … -
Is there a better way to schedule a task with Django?
I have made a Django project and I would like to run several scripts automatically, some of them every minutes other every hour ... My first thoughts were to make a custom Django command and create a crontab. Django - Set Up A Scheduled Job? Like this. I'm looking for if there is a better way in 2019 to made it or eventually if Django framework implemented this functionnality. My project work with docker (Image : Python / OS :Ubuntu). Thanks -
User registration by email confirmation in Django Rest API returns me "AttributeError: 'list' object has no attribute 'rsplit'
#here is my view class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): email = request.data.get('email', False) password = request.data.get('password', False) role = request.data.get('role') if email and password and role: user = User.objects.filter(email=email) if user.exists(): return JsonResponse('Такой email уже существует', safe=False) else: temp_data = { 'email': email, 'password': password, 'role': role } serializer = CreateUserSerializer(data=temp_data) serializer.is_valid(raise_exception=True) # user.is_active = False user = serializer.save() current_site = get_current_site(request) print(current_site) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) print(message) from_email = settings.EMAIL_HOST_USER print(from_email) to_email = email print(to_email) user_email = EmailMessage( subject, message, to=[to_email] ) print(user_email) user_email.send() return HttpResponse('Please confirm your email address to complete the registration') else: return JsonResponse('Email не указан', safe=False) here is my url url(r'^register/$', RegisterView.as_view(), name='register'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), I'm trying to make a registration for users with email confirmation. But it turns me 'AttributeError: 'list' object has no attribute 'rsplit'. Also activation also returns 'can't set attribute'. Could anyone help me, please! -
Cannot log my superuser in ( custom user model / manager )
I'm trying to build super user using a custom user model and a custom user manager. I did exactly the same thing than the django doc about the create_superuser method and in my shell, I'm able to create a superuser with an email and a password. But when I try to log in on the django admin page, I have this wierd error : Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from multiselectfield import MultiSelectField class UserManager(BaseUserManager): #custom create_user method def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email) ) user.set_password = password user.save(using=self._db) return user #Custom create_super_user method def create_superuser(self, email, password=None): user = self.create_user( email = self.normalize_email(email), password = password ) user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): #setting up Choices for interest, Must add other fields ... MATHS = 'mat' PHYSICS = 'phy' HISTORY = 'his' BIOLOGIE = 'bio' ECONOMICS = 'eco' POLITICS = 'pol' MUSIC = 'mus' ENGLISH = 'eng' FRENCH = 'fra' SPANISH = 'spa' LAW = 'law' COMPUTER_SCIENCE = 'cs' COMMUNICATION = … -
Django Test "database table is locked"
In my Django project, I have a view that when a user posts a zip file, it will respond immediately back and then process the data in the background with the help of threading. The view works fine in normal test, but when I run the Django's test it fails with a database table is locked error. Currently, I'm using default SQLite database and I know if I switch to another database this problem may be solved but I'm seeking an answer for the current setup. I trimmed the code for simplicity. Model.py: class DeviceReportModel(models.Model): device_id = models.PositiveIntegerField(primary_key=True) ip = models.GenericIPAddressField() created_time = models.DateTimeField(default=timezone.now) report_file = models.FileField(upload_to="DeviceReport") device_datas = models.ManyToManyField(DeviceDataReportModel) def __str__(self): return str(self.id) Serializers.py: class DeviceReportSerializer(serializers.ModelSerializer): class Meta: model = DeviceReportModel fields = '__all__' read_only_fields = ('created_time', 'ip', 'device_datas') views.py: from django.utils import timezone from django.core.files.base import ContentFile from rest_framework.response import Response from rest_framework import status, generics import time import threading from queue import Queue class DeviceReportHandler: ReportQueue = Queue() @staticmethod def save_datas(device_object, request_ip, b64datas): device_data_models = [] # ... # process device_data_models # this will take some time time.sleep(10) return device_data_models @classmethod def Check(cls): while(True): if not cls.ReportQueue.empty(): report = cls.ReportQueue.get() # ... report_model = DeviceReportModel( device_id=report['device_object'], ip=report['request_ip']) … -
What's the best choice of django rest framework + JWT + LDAP microservices authentication architecure?
I have to write a microservices project with drf+JWT+LDAP auth backend. I choose service1 as an auth service. It will work as an individual django service with JWT+LDAP. And in service2/service3 settings.py I will also set REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = 'rest_framework_jwt.authentication.JSONWebTokenAuthentication'. Then my question is: in service2/service3 code, do I need to override the authenticate interface of class BaseJSONWebTokenAuthentication to verify token with a restful call to service1? Or just run jwt_decode_handler locally with a same secret key to service1 in settings.py? -
Error 404 when loading css in static folder
I have created CSS files in a folder static and currently I'm getting this error 404 when its trying to load the page and no css is being recognised. my folders are DEMOPROJECT -DEMOAPP --migrations --templates ---DEMOAPP -----homepage.html ----base.html -DEMOPROJECT --static ---css ----NavMENU.css --settings.py --urls.py My terminal is this (venv) C:\Users\jferguson\PycharmProjects\WebP1\DEMOPROJECT> I have tried different settings that every other person has asked. None seem to be working. THIS is in the urls.py file for static folder. urlpatterns = [ re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^documents/', include(wagtaildocs_urls)), re_path(r'', include(wagtail_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is in settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Is there any way we can import models in django settings.py?
I am using django-auth-ldap for authentication, now I want to get data for field like AUTH_LDAP_BIND_DN, AUTH_LDAP_BIND_PASSWORD, AUTH_LDAP_SERVER_URI from database. import subprocess from django.apps import apps from django.core.exceptions import ObjectDoesNotExist ldap = False Config = apps.get_model('config', 'Config') Config = Config() try: ldap = Config.objects.get(name="ldap") except ObjectDoesNotExist: pass if ldap and check_ldap_connection(): import ldap from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = Config.objects.get(name="ldap_server_uri") AUTH_LDAP_BIND_DN = Config.objects.get(name="ldap_bind_dn") AUTH_LDAP_BIND_PASSWORD = Config.objects.get(name="ldap_bind_password") ldap_search = Config.objects.get(name="ldap_search") AUTH_LDAP_USER_SEARCH = LDAPSearch( ldap_search , ldap.SCOPE_SUBTREE, "(uid=%(user)s)" ) def check_ldap_connection(): try: ldap_server_uri = Config.objects.get(name="ldap_server_uri") ldap_bind_dn = Config.objects.get(name="ldap_bind_dn") ldap_search = Config.objects.get(name="ldap_search") ldap_bind_password = Config.objects.get(name="ldap_bind_password") except ObjectDoesNotExist: return False cmd = "ldapsearch -H \"" + ldap_server_uri + "\" -D \"" + ldap_bind_dn + "\" -w \"" + ldap_bind_password \ + "\" -b \"" + ldap_search + "\" | " + "grep result" try: connection = "" connection = subprocess.check_output(cmd, shell=True).decode() except Exception as e: return False connection = connection.split() if "0" and "Success" in connection: return True return False Error: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Django group by a pair of values
I would want to do a group by with a pair of values in django. Consider I have the following model, class Vehicle: vehicle_id = models.PositiveIntegerField() version_id = models.PositiveIntegerField(default=1) name=models.CharField(max_length=8096) description=models.CharField(max_length=8096) vehicle_id is not the primary key since there can be multiple rows in the table with the same vehicle_id but with different version_id Now I would want to get the latest versions of all the vehicles. select * from ( select vehicle_id, MAX(version_id) as MaxVersion from Vehicle group by vehicle_id ) s1 JOIN Vehicle s2 on s2.vehicle_id = s1.vehicle_id AND s2.version_id=s1.MaxVersion; Tried to represent this in Django ORM like below, feed_max_version = ( self .values("vehicle_id") .annotate(max_version=Max("version_id")) .order_by("vehicle_id") ) q_statement = Q() for pair in feed_max_version: q_statement |= Q(vehicle_id__exact=pair["vehicle_id"]) & Q( version_id=pair["max_version"] ) return self.filter(q_statement) But this seems less efficient and takes long time to load. I am not very keen on having raw SQL since I would not be able to add any more queryset methods on top of it. -
Dynamic search using date
Can any one please help me i want to search my expenses income which is in my models.py using date wise dynamic search where user will input date and he will see the result in template i dont know how to code that template ..I tried form but not working.. :( my views.py def date_page(request): f_date = '2018-12-05' t_date = '2019-09-12' from_date = datetime.datetime.strptime(f_date, "%Y-%m-%d").date() to_date = datetime.datetime.strptime(t_date, "%Y-%m-%d").date() date_queryset = Add.objects.filter(date__range=(from_date, to_date)) print (date_queryset) return render (request , 'date_page.html',) -
What should be the port value for working on the production server?
When developing on a local machine I used standart code to authorize and work with Google disk creds = None cred = os.path.join(settings.BASE_DIR, 'credentials.json') # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( cred, SCOPES) creds = flow.run_local_server(port=8080) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) I use 8080 as the port parameter value. This works. When deploying a project on a production server, I get a message port is already in use. Server: Ubuntu 18.04, Nginx, uwsgi I tried to use the value port=None and on the local machine it worked, but on the server it gave an integer is required (got type NoneType) What values should I use? -
After deploying Django with Nginx, upload images to the admin background and see a PermissionError
After deploying Django with Nginx, upload images to the admin background and see a PermissionError I'm a Django project deployed on CentOS,The permissions on the folder have been changed to 777,Permission issues still arise # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { listen 80; server_name www.xxxxxx.com; charset utf-8; client_max_body_size 75M; location /static { alias /var/www/WebSite/static; } location /media { alias /var/www/WebSite/static/essay; } location / { uwsgi_pass 127.0.0.1:8080; include /etc/nginx/uwsgi_params; } location /static/ { root /var/www/ngstatic/; break; } } PermissionError at /admin/home/essay/10/change/ [Errno 13] Permission denied: '/var/www/WebSite/static/essay/20190912140555.jpg' Request Method: POST Request URL: http://119.3..*/admin/home/essay/10/change/ Django Version: 2.2.5 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: '/var/www/WebSite/static/essay/20190912140555.jpg' Exception Location: /usr/local/lib/python3.5/dist-packages/django/core/files/storage.py in _save, line 266 Python Executable: /usr/local/bin/uwsgi -
How to use connection pooling for redis.StrictRedis?
In order to be able to user redis lists in my django app, I use a lot of redis.StrictRedis connections instead of stardard django cache.get and cache.set. My example codes are like: r = redis.StrictRedis(unix_socket_path='/var/run/redis/redis.sock', db=3) posts = r.lrange('posts', 0 , -1) However I have encountered some performance issues (gunicorns being stalled at high load and I get frequent 502) I suppose these are due to excessive redis.StrictRedis connections without using a pooling. So I'm wondering how can I use a connection pool instead of making a connection to redis for each data fetch? -
How to fix csv upload with ID "3/Ewurafua/processed.cleveland.data.csv" doesn't exist. Perhaps it was deleted?
I am trying to upload a csv file on the django admin site using the tomwalker django-quiz-app open source library from github, when it tells me that the upload was successful but when i try to access the uploaded file, it gives an error. def csv_upload_post_save(sender, instance, created, *args, **kwargs): if not instance.completed: csv_file = instance.file decoded_file = csv_file.read().decode('utf-8') io_string = io.StringIO(decoded_file) reader = csv.reader(io_string, delimiter=';', quotechar='|') header_ = next(reader) header_cols = convert_header(header_) print(header_cols, str(len(header_cols))) parsed_items = [] ''' if using a custom signal ''' for line in reader: # print(line) parsed_row_data = {} i = 0 print(line[0].split('\t'), len(line[0].split('\t'))) row_item = line[0].split('\t') for item in row_item: key = header_cols[i] parsed_row_data[key] = item i+=1 # create_user(parsed_row_data) # create user parsed_items.append(parsed_row_data) # messages.success(parsed_items) print(parsed_items) csv_uploaded.send(sender=instance, user=instance.user, csv_file_list=parsed_items) instance.completed = True instance.save() post_save.connect(csv_upload_post_save, sender=CSVUpload) I expected to be able to view the file since it showed that the upload was successful but it prints out "Csv upload with ID "3/Ewurafua/processed.cleveland.data.csv" doesn't exist. Perhaps it was deleted?". -
How to pass validation of uniquely constrained field in order to update model record
I've created a view that pre-loads information from a previous entry and allows the user to make and save changes. I have a unique constraint in my model for a particular field which I need to maintain for initial record creation. However if they submit the form in the edit view with the same entry value for this field it obviously doesn't validate. I see there being some scenarios: Initial unique field value == edited unique field value: Doesn't pass validation but I want it to update the record. Initial unique field value != edited unique field value: Validates if field value not in fields list then Creates new record or doesn't validate as field value is in field list and returns unique errors to template I need to provide a means to pass validation in '1.' to enable me to update the record. Should I override the Validate method for the field or is there a better way of doing this? Thanks -
Using Django in Docker unable to fetch rest api
I have built the webapp using Django and also configured for Rest api. I am able to fetch the data via curl and also by python script. Issue I'm running into, when using Docker container, when user fill in the data and submit, it goes thru and ran the python function, but it stop working at when fetching the data via api and thru errors Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.6/site-packages/requests/models.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "/usr/lib64/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib64/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I'm able to curl the URL inside the container. I get the same error when shell into the container in python3.6 sh-4.2# python3.6 Python 3.6.8 (default, May 2 2019, 20:40:44) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> import requests, json >>> url = 'http://127.0.0.1:8001/db/data/' >>> response = requests.get(url) >>> parsedjson = json.loads(response.text) ERROR SAME AS ABOVE . . . parsedjson = … -
Coverage couldn't run 'manage.py' as Python code
I am using Coverage to measure my test code, but I stuck on a weird problem. I tried the command according to Django Documentation: coverage run --source='.' manage.py test myapp But I got this error: Coverage.py warning: No data was collected. (no-data-collected) Couldn't run 'manage.py' as Python code: SyntaxError: invalid syntax (manage.py, line 16) It works correctly using python manage.py test myapp. Here is my manage.py (I didn't modify anything). #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytestsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() What am I missing exactly? I ran my code and coverage in virtualenv, but I don't think this could be a problem. ENV: Python 3.6.8 Django 2.2.3 Coverage 4.5.4 -
Performance Issues in Celery
I already read other posts about that but none of them solve my problem. I have function to scan all ports for a given ip. It takes 5-10 seconds to complete without celery but if I use the celery to run this function, it takes approximately 15 minutes. I observed that function without celery, consuming approximately %90 cpu power but with celery this value is %2-%3 so task takes 15 minutes to finish. This causes a serious performance problem for me. How to increase a cpu power for a specific task or any idea to solve this problem? -
How to render Form-sets out of forms.ModelForm [model is connected to User using a ForeignKey]
I have a model called Ans as class Ans(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and a Form called AnswerForm class AnsForm(forms.ModelForm): class Meta: model = Ans fields = ('ans',) labels = { "ans": '' } help_texts = { 'ans': 'Click ADD or press Enter to add' } I want users to add multiple answers to the question. I have done a not so very exciting way around on this. What I do is that I render the form every time no matter what and then I have provided a link to Proceed so that users can go to next page. It does not look good. Can Somebody please tell me how can I use FormSets on this so that when user press the submit button, he can be directed to the link instead of re rendering the form again again. NOTE- When my form re-renders, it shows the old value as initial input. Can some one help me on this one too about how to clear that field when the form re renders -
Faling to create superuser using custom User model django
I'm trying to make a custom django user model. My User model looks like this: class User(AbstractBaseUser): username = models.CharField(max_length=255,unique=True, default='ak') builder = models.BooleanField(default=False) broker = models.BooleanField(default=False) standarduser = models.BooleanField(default=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['builder','broker','standarduser'] UserManager.create_user() def create_user(self, username, password, builder=False, broker=False, standarduser=True, active=True, staff=False, admin=True): if not username: raise ValueError('enter username') if not password: raise ValueError('enter password') user_obj = self.model( username, password=password, builder=builder, broker=broker, standarduser=standarduser ) user_obj.active = active user_obj.staff = staff user_obj.admin = admin user_obj.set_password(password) user_obj.save(using=self._db) return user_obj UserManager.create_superuser() def create_superuser(self, username, password, builder, broker, standarduser): user = self.create_user( username, password, builder=builder, broker=broker, standarduser=standarduser, staff=True, admin=True ) return user When I try to create a superuser (username: ak), after entering all the required fields I receive the following error: ValueError: invalid literal for int() with base 10: 'ak' I tried clearing the migrations as well but still received the same error. I have also tried this in a new environment, still no luck. Please help me out here, thanks. -
datefield does not show today date in html form even if datetime.date.today is specified
I am using a datefied in my form and html form to render it. i want the date field to be non-editable todays date, but it shows the datepicker. Could anyone please help model: Dataset_Creation_Date = models.DateField(null=True, blank=True, default=datetime.date.today) HTML: <label for="field3"><span>Date of Dataset Creation <span class="required">*</span></span><input class="input-field" name="Dataset_Creation_Date" value="" type="date"/></label> -
ImageField doesn't work when creating the ModelForm
models.py from PIL import Image class Award_list(models.Model): award_id=models.AutoField(primary_key=True) award_name=models.CharField(max_length=50,blank=False) award_image = models.ImageField(upload_to='award_pics') def __str__(self): return f'{self.award_name} award' def save(self,*args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.award_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.award_image.path) class Meta: verbose_name_plural = 'Award' forms.py from django import forms from movies_list.models import Award_list class Create_Award_list_form(forms.ModelForm): class Meta: model=Award_list fields=['award_name','award_image'] views.py from .models import Award_list from .forms import Create_Award_list_form def Award_list_create(request): form=Create_Award_list_form(request.POST or None) if form.is_valid(): # print(request.POST['award_name']) form.save() else: print(form.errors) context={ "hell":'sanjeet', "form":form } return render(request,'movies_list/award_list_create.html',context) urls.py urlpatterns = [ path('movies/awards/new/',Award_list_create,name="award-list-create"), ] award_list_create.html {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{form.as_p}} {{hell}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} This all line of code work all fine with admin page and selecting image save into MEDIA_URL/awards_pics file but when i create a models based forms it select the default option even after selecting the image in .html form. -
How to add 2FA in Django and DRF
I am not sure how to add 2FA to my django project and DRF ? I will eventually connect this DRF with react and redux as the frontend. Here is my Django side: Models: from django.contrib.auth.models import AbstractUser class User(AbstractUser): def __str__(self): return self.username My Django api serializer # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Check token and send back what user is associated with that token class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user My Django urls: from django.urls import path, include from knox import views as knox_views from accounts.api.views import LoginAPI, UserAPI urlpatterns = [ path('api/auth', include('knox.urls')), path('api/auth/login', LoginAPI.as_view()), path('api/auth/user', UserAPI.as_view()), path('api/auth/logout', knox_views.LogoutView.as_view(), name='knox_logout'), My django views: from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from accounts.api.serializers import LoginSerializer, UserSerializer # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Check token and send back what user is associated with that token class UserAPI(generics.RetrieveAPIView): permission_classes = … -
How to check is user email is already saved in DB
I am trying to add email field to a model but before saving data I need to check whether the entered email already exists in DB or not. If not then save the data otherwise display error message. The current code is saving duplicate data. Can someone explain me what I am doing wrong here? I am new to Djanog DRF, please bear with me. What I have done so far Model.py class Subscribe(models.Model): subscribe_email = models.EmailField(max_length=250) contacted_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subscribe_email Serializer.py class SubscriberCreateSerializer(ModelSerializer): class Meta: model = Subscribe fields = ('subscribe_email', ) def create(self, validated_data): instance = super(SubscriberCreateSerializer, self).create(validated_data) email = format(instance.subscribe_email) is_exists = Subscribe.objects.filter(subscribe_email=email).exists() if is_exists: raise ValidationError('Email exists') else: try: send_mail( 'Thank You for subscribing newsletter!', 'This mail is intended to confirm your successful submission for newsletter', settings.EMAIL_HOST_USER, [email, ], fail_silently=False, ) except BadHeaderError: raise ValidationError('Something went wrong, Please try again') return instance Views.py class SubscriberCreateAPIView(CreateAPIView): queryset = Contact.objects.all() serializer_class = SubscriberCreateSerializer def perform_create(self, serializer): serializer.save() Edited: I have found the solution. I changed the perform_create method Can someone please review this? def perform_create(self, serializer): subscribe_email = serializer.validated_data.get('subscribe_email') is_exists = Subscribe.objects.filter(subscribe_email=subscribe_email).exists() if is_exists: raise ValidationError('Email exists') else: serializer.save() -
In Django prevent deletion or editing of a single default record
I am using Django 1.6 version and I have a Django model for which i want to add a default record. I can add that record using fixtures or sql, but i want to prevent that particular record from being deleted. In the admin panel i should see the record say as disabled so that no user can edit or delete only that record. They can edit or delete other records. Is this possible? I tried looking at get_actions or has_delete_permission but that apply to all records and not just the single default record