Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration does not update the current models and throw error: django.db.utils.OperationalError: foreign key mismatch
initially I made 'webpage' as foreign key referencing 'Topic' but then I changed to 'Name' and 'car_name' . The 'webpage' and 'topic' no longer exist in my models but when I try to migrate the model, it throws django.db.utils.OperationalError: foreign key mismatch - "first_app_webpage" referencing "first_app_topic" I even reversed all previous migration (python manage.py migrate first_app zero) made on the app and tried again. It still throws the error. Models.py: from django.db import models class Cars(models.Model): car_name=models.CharField(max_length=264,unique=True,primary_key=True) def __str__ (self): return self.car_name class Specification(models.Model): Name=models.ForeignKey(Cars,on_delete=models.CASCADE) Mileage=models.CharField(max_length=264) def __str__ (self): return self.Mileage class Record(models.Model): Mileage=models.ForeignKey(Specification,on_delete=models.CASCADE) date=models.DateField() Admin.py: from django.contrib import admin from first_app.models import Cars,Specification,Record admin.site.register(Cars) admin.site.register(Specification) admin.site.register(Record) -
Django. How to restrict the number of coupon redeemed
Hey guys I am learning to develop a ecommerce website, I have a coupon model with number object, which take care of max number of coupon available to use, I want to implement that in my views, such that if the coupon is redeemed more than the number(number of coupons), then it should show an error message. I made this in views, but now, even for new coupons I am getting a message showing, you have no active orders. How to implement that correctly? views class AddCouponView(View, LoginRequiredMixin): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') coup_num = 0 order = Order.objects.get(user=self.request.user, complete=False) coupon_qs = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now) coupon_quantity = Coupon.objects.get(code=code, number=form.cleaned_data.get('number')) order_coupon = Order.objects.filter(coupon=coupon_qs.first(), user=self.request.user) if order_coupon: messages.error(self.request, 'You can\'t use same coupon again') return redirect('store:checkout') if coupon_qs: if coup_num <= int(coupon_quantity): order.coupon = coupon_qs[0] order.save() coup_num = coup_num + 1 messages.success(self.request, "Successfully added coupon") return redirect('store:checkout') else: messages.success(self.request, "Coupon Does not Exists") return redirect('store:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('store:checkout') model class Coupon(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) code = models.CharField(max_length=15) amount = models.FloatField() valid_from = models.DateTimeField(null=True) valid_to = models.DateTimeField(null=True) number = … -
Payment for products before they are seen
How can someone code for a site where before you view a certain product you need to pay it. The products are paid individually each with different type of amount . After payment the product can be seen. Someone help Regards -
Ordering of field beyond parent and child models in inlineformset_factory blank form
I have a setup below: models.py class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=200, null=True, choices=STATUS, default="To be confirmed") def __str__(self): return self.product.name views.py def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=5) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none().order_by("product__name"), instance=customer) The form shown up is a blank form as expected but the field "product" shown cannot be ordered by 'name'. How can the drop down list in "product" field can be sorted by 'name' as currently only sorted by 'id'. Any help is highly appreciated. Thanks. -
Conditionally redirect to different dashboards based on user permissions in Django
I have two types of users in my project; students and teachers. I have given the teachers access to course material for the students. Problem is I have buttons in the course material that I initially built for the students. When they click the button they are redirected to their dashboard. However, since teachers have access to the same pages when they click said button they get an error message because they cannot be redirected to the student dashboard because of limited permissions. How would I go about making the button conditional. So if the user has student permissions they would be redirected to their dashboard and if the user has teacher permissions they would be redirected to their dashboard. This is the html button on the curriculum content <div data-scroll-watch><h3><a href="{% url 'students:app-student-dashboard' %}" class="btn btn-primary btn-lg btn-block">Back to your Dashboard</a></h3></div> and my students views: @login_required @student_required @check_is_allow def dashboard(request): # if request.user.is_allow: return render(request, 'classroom/students/app-student-dashboard.html') # else: -
AttributeError: module 'six' has no attribute 'memoryview' occurs when configuring django database for django-mssql
My Django is the latest version, python3.8. I want to configure the database for sql server 2008 R2, so I install django-mssql(aka,sqlserver_ado). After running the server, an error occurs: ......... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Program Files\Python38\lib\site-packages\sqlserver_ado\base.py", line 13, in <module> from . import dbapi as Database File "C:\Program Files\Python38\lib\site-packages\sqlserver_ado\dbapi.py", lin e 45, in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (C:\Program Files\Pyth on38\lib\site-packages\django\utils\__init__.py) Following this suggestion, I open "C:\Program Files\Python38\lib\site-packages\sqlserver_ado\dbapi.py" and change "from django.utils import six" to "import six" , as well as upgrading the six module to latest version. And this time another Error raised: ...... File "C:\Program Files\Python38\lib\site-packages\django\db\utils.py", line 20 7, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Program Files\Python38\lib\site-packages\django\db\utils.py", line 11 1, in load_backend return import_module('%s.base' % backend_name) File "C:\Program Files\Python38\lib\importlib\__init__.py", line 127, in impor t_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Program Files\Python38\lib\site-packages\sqlserver_ado\base.py", line 13, in <module> from . import dbapi as Database File "C:\Program Files\Python38\lib\site-packages\sqlserver_ado\dbapi.py", lin e 750, in <module> Binary = six.memoryview AttributeError: module 'six' has no attribute 'memoryview' I check the six module, and yes, it doesn't include a single word named "memoryview". But why the dbapi.py include the code "Binary = six.memoryview"? And I search … -
First parameter to ForeignKey must be either a model, a model n ame, or the string 'self'
Hey I am using the First Parameter as a model but still it keeps on giving the error: First parameter to ForeignKey must be either a model, a model n ame, or the string 'self' for my code. It works totally well if I use 'self' as first parameter for foreign key. but thats not what I want. Also i am unable even to makemigrations after the following code. models.py from django.db import models import datetime from django.utils import timezone class commentt(models.Manager): comment_id=models.IntegerField(primary_key=True) name=models.CharField(max_length=100, default="No Comment Added") comment_created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # Create your models here. class task_check_manager(models.Manager): def create_task(self, title,c1,c2,c3,list,score_occurence,score_occurence_csm,To): Task_check = self.create(title=title,c1=c1,c2=c2,c3=c3,list=list,score_occurence=score_occurence,score_occurence_csm=score_occurence_csm,To=To) # do something with the book return Task_check class task_check(models.Model): LIST = ( ('DAILY', 'DAILY'), ('WEEKLY','WEEKLY'), ('FORTNIGHT','FORTNIGHT'), ('MONTHLY','MONTHLY') ) STATUS=( ('YES','YES'), ('NO','NO'), ('NEUTRAL','NEUTRAL') ) title=models.CharField(max_length=50) c1=models.CharField(max_length=20,default='C1') c2=models.CharField(max_length=20,default='C2') c3=models.CharField(max_length=20,default='C3') From=models.DateTimeField(default=timezone.now()) To=models.DateTimeField(default=timezone.now()) #created_task=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=15,default="NEUTRAL",choices=STATUS) list=models.CharField(max_length=15, default='DAILY',choices=LIST ) score_occurence_csm=models.IntegerField(default=0) score_occurence=models.IntegerField(default=0) comments=models.ForeignKey(commentt, on_delete=models.SET_NULL, null=True) vendor=models.TextField(max_length=200,default="NONE", editable=False) objects = task_check_manager() def __str__(self): return self.title -
How to custom validate Serializer using overridden is_valid()?
I am using ModelSerializer from django-rest-framework to Serialize the Basic Django User model to register a new user. class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','email','password'] extra_kwargs = { 'password': {'write_only':True}, } I have serializer.save() method written to validate data and call save function to the User Model. def save(self): print('Trying to Save') user = User( email = self.validated_data['email'], username = self.validate_data['username'] ) username = self.validate_data['username'] password = self.validated_data['password'] password2 = self.validated_data['password2'] email = self.validated_data['email'] print('Got Username Password and Email') print(username) print(email) if User.objects.filter(username = username).exists(): raise serializers.ValidationError({'username':'Username already exists'}) user.username = username if User.objects.filter(email = email).exists(): raise serializers.ValidationError({'email':'Email already exists,you can choose to reset your password'},code=400) user.email = email if password != password2: raise serializers.ValidationError({'password':'Both Passwords must match'}) user.set_password(password) user.is_active = False user.save() return user The problem that I am facing is that these internal validation are not working and the overridden save method is not being called. In my view for registration of user, serializer.is_valid() also calls the default is_valid of User Model and then serializer.save() calls the save method of User Model. Here is my View: def api_user_registration(request): if request.method =='POST': serializer = RegistrationSerializer(data= request.data) data = {} if serializer.is_valid(): user = serializer.save() data['response'] = … -
Serving different timezone DRF based on user's area
I wish to serve different times based on the location of my users . All my models which have a time stamp is recorded using the DateTimeField , which i believe would automatically store the datetime as UTC . I have created a extension of my User model as seen here: class UserProfile(models.Model): import pytz TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) ... timezone = models.CharField(max_length=32, choices=TIMEZONES, default='UTC') ... This would allow me to save to DB the location of the user. Previously , before converting to a DRF based application , i was using the default django templates to handle the front end. So inorder to display the correct timezone , i created this middleware: class TimezoneMiddleware(object): """ Middleware to properly handle the users timezone """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # make sure they are authenticated so we know we have their tz info. if request.user.is_authenticated: if hasattr(request.user, 'userprofile'): # we are getting the users timezone string that in this case is stored in # a user's profile print('we are inside the timezone middleware') tz_str = request.user.userprofile.timezone print(tz_str) timezone.activate(pytz.timezone(tz_str)) else: timezone.deactivate() response = self.get_response(request) return response However , this does not work for DRF. My question is … -
Django DRF - How to serialize a list of values (not list of objects)
I am trying to serialize this data { dates : [2020-06-11, 2020-06-12, 2020-06-13 ...], sources : ['Facebook', 'Twitter'...], count: [{'date': 2020-06-11, source: 'Facebook', 'count': 4}, ....] How am I able to serialize the dates, and sources? It comes in a list and is not a list of objects, but merely a list of values. I have only serialized lists of objects before using the many=True keyword, but have never tried serializing a list of values. Do let me know how I am supposed to approach this, thanks all! -
Login form Django redirects to the home page
I am trying to make Login page in Django, but when I am going to http://127.0.0.1:8000/login/ it redirects me to the home page instead of login page. If someone knows why is that I would be very thankful for any ideas of how to fix that. here's my urls.py script from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from register import views as v from django.contrib.auth import authenticate urlpatterns = [ path('admin/', admin.site.urls), path("register/", v.register, name="register"), path('', include('gamechangersapps.urls')), path('', include('django.contrib.auth.urls')), ]+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) my login page script {% block title %} Login Here {% endblock %} {% load crispy_forms_tags %} {% block content %} <form method="post" class="form-group"> {% csrf_token %} {{form|crispy}} <<button type="submit" class="btn btn-success">Login</button> <p>Don't have an account? Create one <a href="/register">here</a></p> </form> {% endblock %} Hierarchy of folders -
Implement typing indicator in Angular 6 websocket chat application
I have a working chat application built in Angular 6 and Django, I want to create a typing indicator, I'm using Websocket for this chat application. -
Error with Django fields ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
Can everyone be helpful in this situation: I have a project in pythonanywhere host. I created models and register in admin.But after make migrations command I write migrate and have this error: File "/usr/lib/python3.7/site-packages/django/db/models/fields/init.py", line 1399, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] There is my code: models.py from django.db import models class User(models.Model): login = models.CharField(max_length=50) passw = models.CharField(max_length=50) email = models.CharField(max_length=50) regdate = models.DateTimeField() status = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Category, Product @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'price', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated'] list_editable = ['price', 'available'] prepopulated_fields = {'slug': ('name',)} please, somebody explain me my … -
Cascade delete not working with django models
I have been using a Video model related with the user on a cascade basis. from django.conf import settings class Video(models.Model): uuid = models.CharField(max_length=255, default="") title = models.CharField(max_length=255, default="") description = models.CharField(max_length=5000, default="") privacy = models.CharField(max_length=10, default="public") category = models.CharField(max_length=50, default="General") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) def delete(self, *args, **kwargs): publisher = pubsub_v1.PublisherClient() topic_name = '...' message_to_publish = self.path publisher.publish(topic_name, data=message_to_publish.encode('utf-8'), spam='eggs') logging.info("Sending pubsub to delete folder : {0}".format(message_to_publish)) super(Video, self).delete(*args, **kwargs) When I trigger a delete on the user, def clear_user(request): user = request.user user.delete() This does not trigger the overloaded delete function. How can I achieve that overloaded delete function to be called on user delete? -
how to install third party app in my existing Django project?
I'm trying to install django-geoposition app in my existing project but it's not working why? i follow this documentation of django-geoposition https://django-geoposition.readthedocs.io/en/latest/#settings I installed using pip. pip install django-geoposition my installed_apps in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'images', 'projects', 'firms', 'manufacturers', "geoposition", ] when I try to run the project I got this error. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' I think my Django project unable to find this app. what's the problem. -
How to create a unique id for a new created user in Django
I have been using a custom user model for my Django user model. Now, I want to create a new member for the model "uuid" which will be a random long unique string for every new user and users that have been created before. How can I do that in model.py ? from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) language = models.CharField(max_length=30, blank=False, default="en-gb") location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) picture = models.CharField(max_length=1000, default="") is_custom_picture = models.BooleanField(default=False) x -
jquery.min.js:2 Uncaught TypeError: jQuery(...).flexdatalist is not a function
I have been trying to include the flexdatalist plugin (http://projects.sergiodinislopes.pt/flexdatalist/) into my html file which is a template in my Django project. The datalist seems to be working fine when I load the html page. However, whenever I try to use a flexdatalist function or even load the page the console displays the following error: jquery.min.js:2 Uncaught TypeError: jQuery(...).flexdatalist is not a function at HTMLDocument.<anonymous> (jquery.flexdatalist.min.js:3) at e (jquery.min.js:2) at t (jquery.min.js:2) Here is my HTML code: <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% load static %} <link href="{% static 'css/jquery.flexdatalist.min.css'%}" rel="stylesheet" type="text/css"> {% load static %} <script src="{% static 'js/jquery.flexdatalist.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function(){ $(".flexdatalist").flexdatalist(); }); </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title> Choose Universities </title> </head> <body> <h1>Choose your universities</h1> <form method="POST"> {% csrf_token %} <input type='text' placeholder='University' class='flexdatalist' data-min-length='1' multiple='' data-selection-required='1' list='school' name='school22'> <datalist name="schoolChoice" id="school"> {% for school in uniList %} <option value="{{school}}"> {{ school }} </option> {% endfor %} </datalist> <button onclick ="addInput()"> Check values </button> <script> $('.flexdatalist').flexdatalist({ selectionRequired: 1, minLength: 1 }); </script> <!-- <script> function addInput() { var value = $.flexdatalist('value'); console.log(value); } </script> --> <br></br> <input type="submit" name="selectedUnis"> </form> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" … -
why i am receiving this error ? django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
I have created already postgresql database in my local and i already imported it in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mytransactiondb', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } when i creating my database in pgadmin 4 i didnt encounter any password. then why i receiving this error? django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" here is my pgadmin 4 -
Django AttributeError type object 'CommonInfo' has no attribute 'filepath'
I keep receiving this error when trying to run the makemigrations command to my app in django even though the filepath function is no longer in the CommonInfo model that I have. I looked over my migrations files in my django app and I did notice that one file still referenced CommonInfo.filepath and I assume that is what is causing the issue. When I changed assets.models.CommonInfo.filepath to 'assetsimages' in the 0007_auto_20200611_2202.py file I'm able to migrate successfully. I should note that the CommonInfo class is an abstract base class for 3 other models for this app. However, I am a bit confused on why this problem occurred. Would anyone be willing to let me know what mistake I made that caused this problem so I can avoid it in the future and if what I did was the correct way to fix it? Below is the model, the migration files that I referenced and the Traceback. Thank you in advance for any help you may be able to provide. Below is the code, I believe I have everything but if I am missing something please let me know and I will update my question. Most Recent Migration File class Migration(migrations.Migration): … -
i want to count new entries in model field after every refresh
I want to get no of new users whenever i refersh my page. I want to add this in my api class User(models.Model): user=models.CharField(max_length=30) def __str__(self): return self.user -
display item from the db in an order
I am looking for a solution to order the data in a 4 items at a row model , thanks -
what's the use if I am querying all the database before pagination in Django?
as per below code I am doing the query for database then I am paginating the query result. so My question what's the use if we already hit the database for all result before pagination. Is this like Django pagination working or I am pretending something wrong? Code: class GetAllUserStoryListViewTest(APIView,LimitOffsetPagination): permission_classes = (IsAuthenticated,) def get_object(self,user_id): user = User.objects.filter(id = user_id).first() posts = Post.objects.filter(user = user) return posts def get(self,request,user_id): posts = self.get_object(user_id).order_by('-post_time_stamp') #setting the limit of this user post pagination LimitOffsetPagination.default_limit = settings.PAGE_SIZE posts = self.paginate_queryset(posts, request) serializer_context = { 'request': request, } serializer = PostListSerializer(posts,many=True,context=serializer_context) # return Response(serializer.data) return self.get_paginated_response(serializer.data) -
Change django bound data in UpdateView
I'd like to prefill a field, regardless what's in there already, on an update view so a user can just hit save and save the new value. If there is already data in there, I can't use initial. class MyView(LoginRequiredMixin, UpdateView): model = Artwork fields = ['template',] template_name = 'page.html' def get_form(self): form = super(MyView, self).get_form() form.fields['template'].initial = 'hello' return form This doesn't work because there is data in template. So I tried class MyView(LoginRequiredMixin, UpdateView): model = Artwork fields = ['template',] template_name = 'page.html' def get_form(self): form = super(MyView, self).get_form() form.data['template']= 'hello' return form But the value in the form is the saved value. I'd read form.data would do this, but it was an 8 year old answer. So not sure how to do this in Django 3.0.6 in case helpful: print(form.data): <MultiValueDict: {}> print(form): <tr><th><label for="id_template">Template:</label></th><td><input type="text" name="template" maxlength="100" id="id_template"></td></tr> print(form.fields): {'template': <django.forms.fields.CharField object at 0x7f937ae20bd0>} print(self.get_form_kwargs()): {'initial': {}, 'prefix': None, 'instance': <Artwork: Tim>} -
Django rest framework, perform update doesn't work
I have a small messaging API where the message contains a mark read boolean field. I'm trying to automatically update the message instance so if the user logged in after the message was created, it'll be marked as read. class MessagesViewSet(ModelViewSet): """ A simple ViewSet for viewing and editing the messages associated with the user. """ authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated] serializer_class = MessageSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = FILTERS.FILTER_SET search_fields = FILTERS.SEARCH_FIELDS ordering_fields = FILTERS.ORDERING_FIELDS ordering = [MessageFields.DATE, ] def get_user(self): user = self.request.user return user def get_queryset(self): return Message.objects.filter(sent_to=self.get_user()) def perform_create(self, serializer): """ Set the sender to the logged in user. """ serializer.save(sender=self.get_user()) def perform_update(self, serializer): """ Update the message read field to true if necessary. """ date = self.kwargs[MessageFields.DATE] mark_read = self.kwargs[MessageFields.MARK_READ] last_login = self.get_user().last_login # If the message hasn't been read yet. if not mark_read: if last_login > date: serializer.save(mark_read=True) pass pass But this is not updating the object when I access it. -
Django: authenticate user using another application
I have two django applications, A and B, which make use of the same User model. The User model is in A , and B sends a request to A for user authentication as follows: # Application B: url = ... # Application A's url data = {'username':request.POST.get('username'), 'password':request.POST.get('password')} resp = requests.post(url, data=data) # A authenticates with the username and password if resp.text == 'True': # login the user: how? user = ... else: # Login fails My question: how do I create an authenticated user in B?