Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Custom Serializer from different models without relationships.?
I have 3 different models. I need to build a custom serializer with these 3 models. I tried using some code, but it didn't reach what I expected. There is structure, but I was not able to get the data I was expecting # Serializer This my Serializer and ModelOne, ModelTwo, ModelThree these are my models. class ModelOneSerializer(serializers.ModelSerializer): class Meta: model = ModelOne fields = ['id', 'obj_1', 'obj_2'] class ModelTwoSerializer(serializers.ModelSerializer): class Meta: model = ModelTwo fields = ['id', 'obj_1', 'obj_2'] class ModelThreeSerializer(WritableNestedModelSerializer): class Meta: model = ModelThree fields = ['id', 'obj_1', 'obj_2'] class CustomSerializer(serializers.Serializer): model_1 = ModelOneSerializer(many=True) model_2 = ModelTwoSerializer(many=True) model_3 = ModelThreeSerializer(many=True) # View class CustomView(APIView): def get(self, request, *args, **kwargs): serializer = CustomSerializer(context={'request': request}) return Response({'response': 'ok', 'result': serializer.data}) # Expected Output { "response": "ok", "result": { "model_1": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" }, { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ], "model_2": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ], "model_3": [ { "id":"1", "obj_1":"test", "obj_2":"test", "obj_3":"test" } ] } } The results may have multiple data in the model_2 and model_3 as in the model_1 structure -
'NoneType' object has no attribute 'name' django
I have three model CustomUser, Profile and artist. what i want to achieve that when i create customuser it should create userprofile and artist also when i update userprofile field it should also update artist field. CustomUser Model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=100, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) Artist model: class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) #userprofile = models.ForeignKey(UserProfile,null=True,on_delete = models.CASCADE) user = models.OneToOneField(CustomUser,null = True, on_delete = models.CASCADE) name = models.CharField(max_length=100,null= True) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return str(self.name) UserProfile Model: class UserProfile(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE) artist = models.ForeignKey(Artist,related_name='userprofile', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True) artist_category = models.IntegerField(choices= CHOICES, null=True) mobile_number = PhoneNumberField(null=True) country = CountryField(default = 'IN') city = models.CharField(blank=True, max_length=100) bio = models.TextField(blank=True) def __str__(self): return str(self.user) creating User Profile: def create_profile(sender,instance, created,**kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_profile,sender=CustomUser) @receiver(post_save, sender= CustomUser) def … -
Django authentication with custome model
I have custome login authentication with mysql table , while login how can i compare hash password with plain-password in backends.py(Working fine with plain password) class MyBackEnd(object): def authenticate(self, request, email=None, password=None): existing_user = RegAuth.objects.get(email=email,password=password) if not existing_user: # Checking the user Regauth Custom DB. user_data = RegAuth.objects.get(email=email,password=password) if email == user_data.email: user = RegAuth.objects.create_user(email=email, password=password) user.save() return user else: return None else: return existing_user def get_user(self, email): try: return RegAuth.objects.get(email=email) except Exception as e: return False Login view def logauth(request): if request.method == "POST": email = request.POST['username'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: messages.error(request, 'if part : user is not None') login(request, user) return redirect('emp') else: messages.error(request, 'else part : user is None') return redirect('login_url') else: messages.error(request, 'Please provide valid credentials') return render(request, 'registration/login.html') -
How to set up Nginx to unify Django and Reactjs server?
I've done Django + React application. The backend and frontend servers will run on their own ports. I want to set up Nginx to unify both development servers. How can combine this two server using ngnix? -
How to check two models ID whitout nested loop?
My problem is the nested loop of my template... i use it to check if my model sitio.id_sitio have a equivalent ID with other model comprobante.id_sitio with a Foreign Key and then print A if one result is found and B if none The conditional if work fine but i dont want the nested loop print multiple times. If one result is found i want to break the cycle and print the html only one time, like <a href=""> Checkouts </a> Else if result dont exist in the records at the end of the for i want to print <p>No payments</p> I dont know if i have to write a query in the views.py or if i have to do something else in the templates... Is there a correct way to do this? This is my code: Models.py class Comprobante(models.Model): id_sitio = models.ForeignKey('Sitio', models.DO_NOTHING, db_column='id_sitio', blank=True, null=True) class Sitio(models.Model): id_sitio = models.IntegerField(primary_key=True) sitio = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.sitio Views.py def topsitios(request): sitio = Sitio.objects.all()[0:100] comprobante = Comprobante.objects.all()[0:100] context = {'sitio': sitio, 'comprobante': comprobante} return render(request, "sitio_ptc/topsitios.html", context) Template.html {% block content %} {% for s in sitio %} <tr> <th scope="row"> {{ forloop.counter }}</th> <td> {{ s.sitio … -
Why can't the seeking attribute work on the chrome browser..?? it works on IE however
my model code is like this content_type = models.ForeignKey(contentType, on_delete = models.CASCADE) content_subject = models.ForeignKey(Subject, on_delete = models.CASCADE) content_title = models.CharField(max_length=200) upload_content = models.FileField(upload_to=user_directory_path) this is what i have on my view but bk = Content.objects.get(id=id) how i acquired my video content from database to site then to template list_of_subjects = Subject.objects.filter(grade=grade_id) subject_video = contentType.objects.filter(content_types = 'SubjectVideos') subject_video_list = Content.objects.filter(content_type__in=subject_video) bk = Content.objects.get(id=id) context={ 'list_of_subjects':list_of_subjects, 'subject_video_list':subject_video_list, 'bk': bk } return render(request,'bgcse/bgcse_subject_video_list.html',context) then i have used this video tag on my html template the class video-fluid and etc only takes care of the video sizes and margins etc the video plays and works just fine, the only problem is seeking on chrome <video class="video-fluid z-depth-1" autoplay controlsList="nodownload" controlsList="seeking"> <source src="{{bk.upload_content.url}}"> </video> {% endblock %} ``` -
Using @swagger_auto_schema with recursive serializer in Django
I have a recursive serializer (data is a tree) which is the format of the response of an API. I tried to use it in @swagger_auto_schema like a bunch of other APIs I have implemented but the app collapsed. Can anyone tell me the solution for this, I really need this serializer to be shown on swagger for documenting for my colleagues. Here's my code: class CategoryExtendedSerializer(SkipBlankFieldsSerializer): children = serializers.ListField(source='get_children', child=RecursiveField(allow_null=True)) class Meta: model = Category exclude = ('lft', 'rght', 'tree_id', 'mptt_level') class CategoryListView(APIView): @swagger_auto_schema( operation_description="Get categories list", responses={200: base_page_response(CategoryExtendedSerializer)} ) def get(self, request): # some irrelevant code here pass -
How to mock a method inside another module during unit testing
In one of my test case the flow requires that a customer provision process wherein the call goes to the api.py file where in the response is saved from the function create_t_customer like following: In api.py file it is using the method create_t_customer imported from file customer.py response = create_t_customer(**data) In customer.py file the code for function is def create_t_customer(**kwargs): t_customer_response = Customer().create(**kwargs) return t_customer_response I want to mock the function create_t_customer inside the unittest. Current I have tried the following but it doesn't seem to be working class CustomerTest(APITestCase): @mock.patch("apps.dine.customer.create_t_customer") def setUp(self,mock_customer_id): mock_customer_id.return_value = {"customer":1} But this is not able to mock the function. -
How could I make the modal show up after clicking the Update(submit) button?
This is the footer code: <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button id="employee_update_btn" type="submit" class="btn btn-success btn-round ">Update</button> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> {% if success %} <script> $('#employee.employee_id_{{ employee.employee_id }}').show(); </script> {% endif %} </script> </form> I wanted to open the modal after clicking the Update button. views.py return render(request, 'index.html', context={'success': True}) the Modal i wanted to open: <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="card"> <div class="modal-content"> <div class="modal-header"> <div class="card-header-success" > <h4 align="center" class="card-title">EMPLOYEE PROFILE</h4> </div> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> -
Django: Inconsistent test that depends on other test
I am getting inconsistent tests. For visualization, Let me use examples: tests/test_animals.py tests/test_plants.py I have 2 tests. When I run individual test like: python manage.py test apps.living_things.tests.test_plants it would have no errors. However when I run python manage.py test apps.living_things.tests, to test everything, it would affect the second test: tests/test_plants.py I am using fixtures for them, one is initial and the other is just a test fixtures: fixtures/initial.json # general models fixtures/test_living_things.json # sample input for animals and plants I have been debugging. One class of test in tests/test_animals.py includes the 2 fixtures: class TestAnimals(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass When I commented out the block code above in test/test_animals.py everything works fine. So I am suspecting it has to do with the 2nd fixture: fixtures/test_living_things.json since I also have a Test Class without that fixture but works fine. The error I get when messed up is that Client.get does not respond well in tests/test_plants.py class TestPlants(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass def test_plants(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'animalplants'}) response = c.get("/living_things/plants/1/") # Gets Error here, returns 404 -
Django search query feature like Django admin or Django rest framework
I am trying to figure out a proper way to make a search functionality for my model fields like Django's admin or Django rest framework's search feature. Suppose I have this model, I would like to search through all the fields.: class User(models.Model): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) mobile = models.BigIntegerField(unique=True) First, I tried this way: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) This works fine if I am filtering with only the integer search terms. However, if I pass a string value, this breaks and it gives me an error: ValueError: invalid literal for int() with base 10 So now what I came up is something like this, to catch any Value errors and exclude integer searches from the filter: try: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) except ValueError as e: user_list = User.objects.filter( Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | ) I am hoping there's a better way then this. Or maybe a field look up feature that I am not aware of? -
How to make a django/vuejs website available offline?
I am working on a online_test application which tests users on mcq, mcc, blanks and code questions. The basic flow of website is: It has courses. Student enrolls in the course watches video lessons Solves questions based on those videos. The first version of the website is live and built entirely in django. The second version I want is the offline version of the course available to the user in which he is enrolled, so that he can study or solve problems without worrying about the internet. Once he completes the test, his responses should be stored in some localstorage (I was thinking IndexedDB) and submitted only when the user comes online. For the second version I am using API written in DRF and for frontend Vue. Vue has helped me reduce number of hits to server and also improved the performance of the website. So I was thinking if there is any way in which I can have a simple Download Course button somewhere inside the course. And when the user click that button, a offline version of the course is available to user. The problem here is even if it is possible to make the course offline, I … -
Lost previous values on overriding change_list.html of django admin
I wanted to add a row in the django admin and for that I customized the django's change_list.html but after doing all the stuff I lost my previous fields. I had this previously: Previous fields image Not I wanted to add total in the footer of the page and I got this: Image after customizing I want the image 1 and image 2 in the same page. @admin.register(Section4, site=admin_site) class Section4Admin(ReadOnlyParamsMixin, admin.ModelAdmin): list_display = ['__str__', 'count_review', 'changelist_view'] def count_review(self, obj): ...... ...... return mark_safe( render_to_string( "section4/count_review.html", {'id': obj.resident.id, 'counts': counts, 'completed': review_completed, 'to_add': review_not_added, }) ) change_list_template = 'section4/total_review_count.html' def get_total(self, user): ........ ....... return total_review_upto_date, total_review_tobe_updated, total_review_tobe_added def changelist_view(self, request, extra_context=None): total_review_upto_date, total_review_tobe_updated, total_review_tobe_added = self.get_total(request.user) my_context = { 'total_review_upto_date': total_review_upto_date, 'total_review_tobe_updated': total_review_tobe_updated, 'total_review_tobe_added': total_review_tobe_added } return super(Section4Admin, self).changelist_view(request, extra_context=my_context) I have templates/admin/section4/section4/change_list.html In section4/templates/section4/total_review_count {% extends "admin/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} <footer> <p>The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> {% endblock %} -
Advantages of django rest_framework over AJAX and JsonResponce
I can get data in JSON format, using a view and url by calling an AJAX function from JQuery. Which only needs to create a view and a url to access it. But is rest_framework to do the same thing I need to create serializer, views and a url to do the same. So is it good to use AJAXX in these cases or I need to use rest_framework every time. Thanks. -
connect() to unix:///tmp/uwsgi_dev.sock failed (111: Connection refused) while connecting to upstream
I'm running django application with uwsgi + Nginx with crontab command given below /usr/local/bin/lockrun --lockfile /path/to/lock_file -- uwsgi --close-on-exec -s /path/to/socket_file --chdir /path/to/project/settings/folder/ --pp .. -w project_name.wsgi -C666 -p 3 -H /path/to/virtualenv/folder/ 1>> /path/to/log_file 2>> /path/to/error_log but nginx error log file shows the error *83 connect() to unix:///path/to/socket_file failed (111: Connection refused) while connecting to upstream, client: xxx.xxx.xx.xxx, server: localhost, request: "GET /auth/status/ HTTP/1.1", upstream: "uwsgi://unix:///path/to/socket_file:", host: "xx.xxx.xx.xxx", referrer: "http://xx.xxx.xx.xxx/" -
What will be the best way to perform the CRUD with DRF?
There are several ways of performing CRUD operation with django-rest-framework.One will be by using the plain API view, another is Generic API view and other is with ViewSets.I want to know which will be the better way to create an API ? -
Segmentation fault (core dumped) with django-storages
I'm using Django 2.x and Django-storages to upload files to the S3 Bucket. While running the sample test from manage.py shell, it gives the following error and terminates the console. Segmentation fault (core dumped) The console log as per the doc. In [1]: from django.core.files.storage import default_storage In [2]: default_storage.exists('storage_test') Out[2]: False In [3]: file = default_storage.open('storage_test', 'w') In [4]: file.write('storage content') Out[4]: 15 In [5]: file.close() In [6]: default_storage.exists('storage_test') Out[6]: True In [7]: file = default_storage.open('storage_test', 'r') In [8]: file.read() Segmentation fault (core dumped) File is uploaded to the S3 Bucket but unable to access or read it. -
PATCH with Django REST framework
I have models, serializers, and viewsets as following. models.py class OrderStatus(models.Model): ORDER_STATUS_CHOICES = ( ('NEW', 'New'), ('PROCESSING', 'Processing'), ('DELIVERING', 'Delivering'), ('DELIVERED', 'Delivered'), ) status = models.CharField( max_length=20, choices=ORDER_STATUS_CHOICES, default=ORDER_STATUS_CHOICES[0][0]) def __str__(self): return self.status class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='order', on_delete=models.CASCADE) order_items = models.ManyToManyField(OrderItem) order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username serializers.py class OrderItemSerializer(serializers.ModelSerializer): pizza_type = serializers.CharField(source='pizza_type.name') pizza_size = serializers.CharField(source='pizza_size.size') class Meta: model = OrderItem fields = ('pizza_type', 'pizza_size', 'quantity', ) class OrderSerializer(serializers.ModelSerializer): user = UserSerializer() order_items = OrderItemSerializer(many=True) order_status = serializers.CharField(source='order_status.status') class Meta: model = Order fields = '__all__' views.py class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer Listing, retrieving and deleting worked expectedly but how can I execute PATCH correctly to change order_status with the code above? I tried to run http://0.0.0.0:8000/api/orders/3/?order_status=PROCESSING and received "PATCH /api/orders/3/?order_status=PROCESSING HTTP/1.1" 200 313 but the data didn't look like it changed. Any hints? -
how to create dynamic model in django?
How do i create a dynamic model in django? here i am trying to create dynamic model using CreateDynamicModel,but it is not creating model and admin interface. ''' def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a class attrs = { '__module__': 'myapp.models' } # Add in any fields that were provided if fields: attrs.update(fields) # Create the class, which automatically triggers ModelBase processing model = type(name, (models.Model,), attrs) from django.core.management import sql, color from django.db import connection # Standard syncdb expects models to be in reliable locations, # so dynamic models need to bypass django.core.management.syncdb. # On the plus side, this allows individual models to be installed # without installing the entire project structure. # On the other hand, this means that things like relationships and # indexes will have to be handled manually. # This installs only the basic table definition. # disable terminal colors in the sql statements style = color.no_style() with connection.schema_editor() as editor: editor.create_model(model) class Admin(admin.ModelAdmin): list_display = ['first_name', 'last_name'] admin.site.register(model, Admin) return model def CreateDynamicModel(request): … -
html page should be updated when mysql table is updated without reloading in django
I have an issue that i want html page should update values which are fetched from mysql database whenever mysql table is updated. I have tried to implement javascript. here is what i have tried. ''' <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type = 'Get', url = '{% url 'index' %}', data = {response.id_data} success : function(response){ $("#user_info ").html(`<tr> <td>${response.id_data || "-"}</td> </tr>`) }, }); }) </script> ''' here is my views.py. ''' def index(request): mycursor.execute("select id from face_counter") data = mycursor.fetchall() id_data = { "id": data } return JsonResponse({'id_data':id_data.get("id"),},status=200) ''' i have tried this but html page gets only json data and displayed it. script doesn't work what should i do. -
Retrieving count of unique Django objects based on multiple fields of another Django model
I have a Django model defined as follows: class Session(models.Model): ... leader = models.ForeignKey(User, related_name='leader') follower = models.ForeignKey(User, related_name='follower') ... Now let's say I have a QuerySet of Session objects: all_sessions = Session.objects.all() How can I get a simple count of unique Users that have been either a leader or follower in any Session in all_sessions? For example, a particular User may have been a leader in some number of Session objects, but a follower in a handful of other Session objects. That particular User should only contribute 1 to the desired unique Users count. There are of course some naive solutions to this, but for performance reasons, I'm wondering if there's a solution that leverages the power of QuerySets a bit more, if possible. -
google auth redirect uri miss match issue
In my django project i want to use google authentication for user login. i followed some articles but now stuck at point, where i'm getting error like: Error: redirect_uri_mismatch. i searched allot but could not resolved this issue. plz help I'm sharing my code here: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xnph^f^z=wq^(njfp*#40^wran3' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', # <-- ] ROOT_URLCONF = 'simple.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = 'login' LOGOUT_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False WSGI_APPLICATION = 'simple.wsgi.application' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxxxx my key xXXXXXX' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx my secrete XXXX' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N … -
Best way to specify dedicated sub domain for authentication views in Django Rest Framework
I'm building and API using DRF and will be using it with a React SPA. I've chosen session authentication for my project because of the following reasons: It's built-in to DRF, so no dependence on 3rd party developers (a lot of auth packages or their dependencies are not maintained) CSRF + Cookie protection Ability to use Secure and HTTPOnly cookies However, I'm aware that it's recommended that we use Django's authentication views for the authentication pages and the single page app for the post authentication API calls. In this scenario, there are some views (i.e. Login, Logout, Password Reset, Register) for which the server responds with HTML and the rest return JSON. I would like to use different subdomain for these views i.e. different subdomain for HTML views and different subdomain for the JSON views. I'm a Django newbie and would really appreciate some suggestions on the best way to handle the separation of subdomains. I have some idea that the few ways I could achieve this are: using django-hosts using django sites (although I'm not sure if the cookie made by one site, would work on the other) point 2 domains to my server and handle the separation bit … -
django project always trying (and failing) to load file in separate app
I'm going back to an old django project and am trying to make a new site in a new app I just made, popularify. I want to load an httpResponse and nothing else when I go to the /popularify path , but it keeps trying and failing to get a favicon.ico file, the 404 error always appears in the chrome web console and django logs. I have it set up correctly so my popularify page loads a basic httpResponse: my main urls.py file in my project folder has a path: path('popularify/', include('popularify.urls')), The popularify app urls.py file looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And the popularify views.py file looks like this from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") All very basic to just load some text, but in console I am getting a unrelated 404 error trying to load a file I never directly specified, and dont want to load: If I click the favicon.ico link it shows the html file _base.html I have in my templates folder, a file I use as a base file in … -
How do I accept the friend request in django after sending a hyperlink in mail which redirects the user to accept/reject page?
models.py : class Friend(models.Model, LoginRequiredMixin): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs): friend = self.create(from_user_id=request.user.id, status="pending") return friend views.py : This view contains 2 buttons: Accept and reject and based on user response it will be updated in the database def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" try: uid = urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(id=Friend.to_user.id) & Friend.from_user print(friend_user) f = Friend.objects.filter(friend_id = friend_user) print(f) if f: f.status = "accepted" f.save() return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except(FieldError, AttributeError): return render(request, 'blog/base.html') Thanking you in advance,