Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save user preferences without logging user in flutter app
I am working on a flutter app that requires some user data to be saved on server side. But I don't want user to log in using username/password or any social account. Is there a way in flutter to identify the user/device without explicit login ? There seems to be a anonymous login using Firebase but I am looking for a generic solution without any specific backend. I am using Django as my backend. -
Django i18n using a translation from django.contrib module instead of LOCALE_PATHS file
My Django 3.2.9 project displays a translation of both _('Active') and {% translate 'Active' %} that comes from one of Django's modules instead of my application registration. However, other translations from registrations are properly used. By temporarily moving the locale directory outside of the application directory, I confirmed that not only LOCALE_PATHS is correctly set, but also used. Reordering my INSTALLED_APPS also does not change anything. Django seems to insist to use a translation from one of its modules instead from the one in LOCALE_PATHS. The translation in the file looks standard: #: .\registration\templates\users.html:109 #: .\registration\templates\list.html:34 .\registration\views.py:687 msgid "Active" msgstr "XXX" My settings look as follows: BASE_DIR = Path(__file__).resolve().parent.parent LOCALE_PATHS = [ BASE_DIR / 'registration' / 'locale', BASE_DIR / 'administration' / 'locale', ] I confirmed that the path is correct and contains django.po and django.mo in LC_MESSAGES under the language's code directory. As noted above, other translations work correctly. Why does Django use its own version, even though mine is in LOCALE_PATHS and, after changing settings, at the front of INSTALLED_APPS? How can I ensure that Django uses my version? -
Cant login in django when RLS is enabled in the user model?
I have a multi-tenant django application where I've enable Row Level Security using Postgres. Each table has a tenant_id column. I am able to do RLS on the tables using the following postgres policy CREATE POLICY {policy_name} ON "{table_name}" USING (tenant_id::TEXT = current_setting('rls.tenant_id'));" and a middleware from django.utils.deprecation import MiddlewareMixin from django.db import connection class RLSMiddleware(MiddlewareMixin): def process_view(self, request, **kwargs): with connection.cursor() as cur: cur.execute("""select set_config('rls.tenant_id', %(value)s, false)""", dict(value=request.user.pk)) Now when I enable this to the django user model, I'm can't login since the tenant in the current_setting isn't set. But I need to login to set the current_setting. Any work around for this? Can I maybe disable the RLS when in the login page? -
SQL raw to Django query
Can someone help me to change the following query to Django a query so that I use it in my views.py? select onhold_hour, onhold_date, clinic_id, hospital_id, region_id hospital_name, clinic, (select string_agg(clinic, ', ') as other_clinics from hospitals_core_clinic inner join hospitals_core_schedule on hospitals_core_clinic.id = hospitals_core_schedule.clinic_id where hospital_id = 263 and onhold_date = '2022-02-27') from hospitals_core_schedule inner join hospitals_core_clinic on hospitals_core_schedule.clinic_id = hospitals_core_clinic.id inner join hospitals_core_hospital on hospitals_core_schedule.hospital_id = hospitals_core_hospital.id and hospital_id = 263 and onhold_date = '2022-02-27' The onhold_date and the hospital_id will be custom variables My models.py are the following: class Region(models.Model): region = models.CharField(max_length=100, unique=True) region_display = models.CharField(max_length=100, unique=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.region def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.region)) super(Region, self).save(*args, **kwargs) class Hospital(models.Model): hospital_name = models.CharField(max_length=100, unique=True, blank=True, null=True) actual_name = models.CharField(max_length=100, unique=True, blank=True, null=True) #hospital_address = models.CharField(max_length=100, unique=False, blank=True, null=True) #hospital_phone = slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.hospital_name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.hospital_name)) super(Hospital, self).save(*args, **kwargs) class Clinic(models.Model): clinic = models.CharField(max_length=100, unique=True, blank=True, null=True) clinic_display = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.clinic def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.clinic)) … -
how to retrieve in a sql many to many relationships query all the instances a user is involved with
How can I retrieve all the instances a user is part of in a Many to Many relationship in SQL. (PostgreSQL) I have the following table using django: models.py ... from django.contrib.auth import get_user_model ... User = get_user_model() class Member(models.Model): ... member = models.ManyToManyField(User, related_name="membership") status = models.CharField(max_length=20, choices=STATUS) created = models.DateTimeField(auto_now_add=True) query user = User.objects.get(id=1) user.membership.all() # result => give me all instances where user 1 is associated in Member table What would be the equivalent in sql of the above django query? Any help would be much appreciated -
How to get rid of "%20Profile" in URL Pattern
First, I will search up the user, and then it takes me to a page of a list of users to click onto. After that, when I choose a user I want to click on to check out their profile, it should take me to users page I want to see, but that is where I have a problem. The URL pattern should be, for example /user/MatthewRond/, but instead, I get /user/MatthewRond%20Profile/, which prevents me from seeing Matthew's page because %20Profile was never intended to be in the URL. If I can figure out how to get rid of the %20Profile, my problem should be solved. I read up on what %20 was and what I got from it: it has to do with using and dealing with alphanumeric characters. Regardless none of it helped me figure out how to remove it. As for the code part of it, I am grabbing the default username from the database then grabbing the custom profile I made from that default user. After that, I set the username to the custom profile model I made. I don't believe it is an error with my views, maybe my templates or URLs. views.py def profile_view(request, … -
graphene.Field() with filter() and graphene.List() with get() return errors (Graphene Django)
<Case 1> I used "graphene.Field()" with "get()" and "graphene.List()" with "filter()" to get one specific object. "graphene.Field()" with "get()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") all_categories = graphene.Field(CategoryType, id=graphene.Int()) # graphene.Field() def resolve_all_categories(root, info, id): return Category.objects.get(pk=id) # get() schema = graphene.Schema(query=Query) "graphene.List()" with "filter()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") all_categories = graphene.List(CategoryType, id=graphene.Int()) # graphene.List() def resolve_all_categories(root, info, id): return Category.objects.filter(pk=id) # filter() schema = graphene.Schema(query=Query) Then, I queried "allCategories" for both code in schema.py above one by one: query { allCategories(id:1) { id name } } Finally, I got this result without error for "graphene.Field()" with "get()" in schema.py: { "data": { "allCategories": { "id": "1", "name": "category1" } } } And this result without error for "graphene.List()" with "filter()" in schema.py: { "data": { "allCategories": [ { "id": "1", "name": "category1" } ] } } <Case 2> Next, I used "graphene.Field()" with "filter()" and "graphene.List()" with "get()" to get one specific object. "graphene.Field()" with "filter()" in schema.py: import graphene from graphene_django import DjangoObjectType from … -
Django serializer how to serialize a foreign key field
This is my models.py class AuthorModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host = models.CharField(max_length=200, default=settings.HOST_URL) displayName = models.CharField(max_length=200) github = models.CharField(max_length=200) profileImage = models.CharField(max_length=200) class PostModel(models.Model): title = models.CharField(max_length=200) id = models.CharField(max_length=200, primary_key=True) source = models.CharField(max_length=200, blank=True) origin = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200) contentType = models.CharField(max_length=200) content = models.CharField(max_length=2000) author = models.ForeignKey(AuthorModel, related_name=("post"), on_delete=models.CASCADE, null=True) categories = models.CharField(max_length=200) count = models.IntegerField(blank=True, null=True) comments = models.CharField(max_length=200, blank=True) published = models.DateTimeField(auto_now=True) visibility = models.CharField(max_length=200) unlisted = models.BooleanField() This is my views.py @api_view(['POST']) def create_post(request): """ Create a new Post """ if request.method == 'POST': serializer = PostSerializer(data=request.data) print("api received request data: ",request.data) if serializer.is_valid(raise_exception=True): author_object = AuthorModel.objects.get(id=request.data['author']) serializer.author = author_object serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = AuthorModel fields = ['id', 'host', 'displayName', 'github', 'profileImage'] class PostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=True, read_only=True) class Meta: # TODO commentsSrc model = PostModel fields = ['title', 'id', 'source', 'origin', 'description', 'contentType','content','author','categories','count','comments','published','visibility','unlisted'] and finally my html {% extends 'base.html' %} {% block title %} Create Post {% endblock %} {% block content %} <div class="card" style="margin:10px"> <h2 style="margin: 10px 10px 0">Create A New Post</h2> <form action="{% url 'createpost' %}" method="post" id="post_form"> {% … -
Why does my Django query from Postgres database return the query set in reverse order
I have a model called "Step" that is connected to a learning guide through a foreign key. In my views.py file I am simply querying the steps using this learning_guides_steps = learning_guide.step_set.all() and in the templates I am just looping through the steps using a for loop and displaying the title of the steps like this {%for step in learning_guides_steps%} <div class="entire_step"> <!-- Displaying the title of the step with an angle down button beside the title --> <div class = "btn-group step" > <a href = "#" class = "btn stepname" role = "button" style = "font-size: 18px;"> {{forloop.counter}}. {{step.title}}</a> </div> </div> However when I display it in website its printing in reversed order. Can anyone explain why this is happening and how I can fix this? I am new to Django and Postgres, so any help would be appreciate it. Thank you. My Step model and the views is given below class Step(models.Model): title = models.CharField(max_length=200, null=False) step_description = models.TextField(max_length=1000, null=False) # enforces one-to-many relationship between LearningGuide and Step. # Deleting a LearningGuide deletes all the associated steps (CASCADE delete) learning_guide = models.ForeignKey(LearningGuide, on_delete=models.CASCADE) My views.py file: learning_guide = LearningGuide.objects.get(pk=learning_guide_id) learning_guides_indicators = learning_guide.indicators.all() indicators = Indicator.objects.all() learning_guides_steps = … -
Foreign key columns and parent model
I have a model like this class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) In the product model, I save the price of that product, but from time to time the price may change. I want when the order is completed and I want to change the product price of that sold product not update the price of the product that is sold in that order. So, the price change should be affected only new orders. Thanks in advance! -
nginx deployment issues on aws alb host not found
error am getting in my web server container 2022-02-26 23:02:312022/02/26 22:02:31 [notice] 22#22: exiting 2022-02-26 23:00:432022/02/26 22:00:43 [error] 23#23: *13 django_web could not be resolved (3: Host not found), client: 10.0.1.89, server: enum-ops-staging.enum.africa, request: "GET / HTTP/1.1", host: "10.0.1.68" 2022-02-26 23:00:4310.0.1.89 - - [26/Feb/2022:22:00:43 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" 2022-02-26 23:00:432022/02/26 22:00:43 [error] 23#23: *12 django_web could not be resolved (3: Host not found), client: 10.0.0.59, server: enum-ops-staging.enum.africa, request: "GET / HTTP/1.1", host: "10.0.1.68" 2022-02-26 23:00:4310.0.0.59 - - [26/Feb/2022:22:00:43 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" my nginx.conf file server { listen 80; server_name enum-ops-staging.enum.africa; location / { resolver 10.0.0.2 valid=300s; set $backend http://django_web:8000; proxy_pass $backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { alias /usr/src/app/enumops/static; } location /media { alias /usr/src/app/enumops/media; } } tried a lot of suggestions but none seems to be working. Please any suggestions or help, thanks in advance?? -
How to access an object's fields and manipulate them when using pre_delete?
I have a foreign key in the model and I want to change a field's value in that object when pre_delete is called. I'm new to this concept and just found out that you use a pre delete signal like this: @receiver(pre_delete, sender=MyModel) def bid_deletion(sender, instance, using, **kwargs): pass What should I write to use the foreign key object's field? -
Django annotate() is not adding up the number of entries but is instead repeating them
Background: The Amazon Kindle PaperWhite stores the words we lookup while reading into a sqlite3 database called vocab.db. I am working on a small kindle companion app that takes this db file and imports it into a django table for various processing. I have done this step already. What I would like to do: I would like to query my table KindleLookups for my most difficult words (ex: how many times have I looked up a specific word). I would ultimately like to present this data in a table ordered by highest count. Desired Result: Word Lookup Count Reverberated 3 Troubadour 1 Corrugated 1 My result (undesired): Here Reverberated is being repeated three times each with a lookup count of one, instead of one time with three lookup count. Word Lookup Count Reverberated 1 Reverberated 1 Reverberated 1 Troubadour 1 Corrugated 1 Model: class KindleLookups(TimeStampedModel): book = models.ForeignKey(KindleBookInfo, on_delete=models.CASCADE) word = models.ForeignKey(KindleWords, on_delete=models.CASCADE) ... class KindleWords(TimeStampedModel): word_key = models.CharField(max_length=255, unique=True) word = models.CharField(max_length=255) ... I am trying to accomplish this using annotate(), but this is repeating the rows instead of adding them up for some reason. context['lookup_counts'] = KindleLookups.objects.annotate(word_count=Count("word")) I then thought that I needed to annotate on the actual … -
creating models using foreign key relationships
I have a user model that looks like this class User(AbstractUser): email = models.EmailField(verbose_name='E-mail', max_length=255, unique=True) first_name = models.CharField(verbose_name='First Name', max_length=255) last_name = models.CharField(verbose_name='Last Name', max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) username = None teacher = models.OneToOneField(Teacher, on_delete=models.CASCADE, related_name='teacher') student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name='student') objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): return self.first_name + " " + self.last_name def get_short_name(self): return self.first_name def __str__(self): return self.email My User Manager class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not password: raise ValueError("Users must have a password") user = self.model( email=self.normalize_email(email), ) user.first_name = first_name user.last_name = last_name user.set_password(password) user.is_staff = False user.is_superuser = False user.is_active = True user.teacher = Teacher.objects.create() user.student = Student.objects.create() user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") if not first_name: raise ValueError("User must have a first name") if not last_name: … -
Django - User info not going to the database (e-commerce website)
I am trying to make an e-commerce website using Django where "AnonymousUser" or Guest user can also order and check out products without the need to login. The Guest user just need to provide their name, email, and address. But I want to get the name and email that was entered in the checkout form to the database: Customer table. I tried to use this as an alternative because when I check the info in the daatabase there's an error that says "__str__ returned non-string (type NoneType)": class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name or 'AnonymousUser' When I remove the or 'AnonymousUser' the error keeps on showing. Here's my checkout.html file: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> </div> <div id="shipping-info"> <hr> <p>Shipping Information:</p> <hr> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <div class="form-field"> <input class="form-control" type="text" name="state" placeholder="State.."> </div> <div class="form-field"> <input class="form-control" type="text" … -
when sent via email the <a> tab is unclickable
<tr style="border: 0 none; border-collapse: separate;"> <td class="c-rdekwa" style="border: 0 none; border-collapse: separate; vertical-align: middle; padding-top: 38px;" valign="middle"><a href="reset-password.html" target="_blank" style="color: #000000; -webkit-border-radius: 4px; font-family: &quot; HelveticaNeueMedium&quot;,&quot;HelveticaNeue-Medium&quot;,&quot;HelveticaNeueMedium&quot;,&quot;HelveticaNeue&quot;,&quot;HelveticaNeue&quot;,sans-serif;font-weight: 500; font-size: 13.63636px; line-height: 15px; display: inline-block; letter-spacing: .7px; text-decoration: none; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; background-color: green; color: #ffffff; padding: 12px 24px;">Recover my password</a> </td> </tr> the above code is the area that is of concern. the recover email link is working locally but once it is sent via email it doesn't work in the sense that it doest redirect nor take you anywhere its if its unclickanle <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office"> this code is what I have at the top I removed it and used only <head> still didn't work please I need help -
Django Importing Random Libraries?
Sometimes when I recompile or rerun my Django application, Django will import libraries at random that it then can't find. ie from cgi import test from distutils.command.clean import clean from winreg import SetValue 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 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/pweyand/NEST/lightchan/lightchan/backend/lightchan/lightone/urls.py", line 3, in <module> from . import views File "/home/pweyand/NEST/lightchan/lightchan/backend/lightchan/lightone/views.py", line 3, in <module> from winreg import SetValue ModuleNotFoundError: No module named 'winreg' What gives? Is there any way to turn this off? -
localhost: A server error occurred. Please contact the administrator
I am learning to run local hosts using Django with the help of https://www.dj4e.com/. I am currently trying to run the local server using the following: python manage.py runserver When I run this, the output given in terminal is the following: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). February 26, 2022 - 15:21:09 Django version 3.2.5, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. I clicked into 127.0.0.1:8000, but the server outputs the error in the title, A server error occurred. Please contact the administrator. My terminal also outputs the following error: Traceback (most recent call last): File "C:\Python\Python310\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) File "C:\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) TypeError: get_wsgi_application() takes 0 positional arguments but 2 were given [26/Feb/2022 15:13:30] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "C:\Python\Python310\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) File "C:\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 76, in __call__ return self.application(environ, start_response) TypeError: get_wsgi_application() takes 0 positional arguments but 2 were given [26/Feb/2022 … -
Ubuntu: Trying startserver in Django and i get core exception update sqlite3. How can i update it. I am not strong in terminal commands
File "/usr/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17) -
Cannot assign "<User: Euler>": "Article.authorr" must be a "User" instance
what is problem? def change_names_of_field(apps, schema_editor): Article = apps.get_model('blog', 'Article') article = Article.objects.all() for s in article: s.authorr = User.objects.get(username=s.author) if Category.objects.filter(title=s.category).values_list("title", flat=True) == []: Category.objects.create(title=s.category) s.categoryy = Category.objects.filter(title=s.category) s.update = s.created s.published = s.created s.status = "p" s.save() -
how to store number of occurance of tags in post in django by creating custome table?
i am using spacy to generate tags for my posts by getting the words with maximum occurrence . and i have tag model and post model and i want to generate count model for storing tag with post with occurrence of tag in that post. class Occurrence(models.Model): number = models.IntegerField(unique=True) def __str__(self): return str(self.number) class TagPostOccurrenceLength(models.Model): number = models.ForeignKey( Occurrence, on_delete=models.CASCADE, related_name='numbers' ) tag = models.ForeignKey( MyCustomTag, on_delete=models.CASCADE, related_name='post_occurrence' ) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='posts_occuraces' ) def __str__(self): return f'[{self.number} X {self.tag}] in: {self.post}' -
Django - store.models.Customer.MultipleObjectsReturned: get() returned more than one Customer -- it returned 2"
I am trying to make an e-commerce website where "AnonymousUser" or Guest user can order and check out products by providing their name, email, and address. But after clicking the "Make Payment" button, my terminal was having an error that says "store.models.Customer.MultipleObjectsReturned: get() returned more than one Customer -- it returned 2!" When I try to login and do the process for an authenticated user, it doesn't have an error. It just happen to AnonymousUsers. Here's my checkout.html: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> </div> <div id="shipping-info"> <hr> <p>Shipping Information:</p> <hr> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <div class="form-field"> <input class="form-control" type="text" name="state" placeholder="State.."> </div> <div class="form-field"> <input class="form-control" type="text" name="zip" placeholder="zip code.."> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make Payment</button> </div> </div> <div class="col-lg-6"> <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'cart' %}">&#x2190; Back to Cart</a> <hr> <h3>Order Summary</h3> <hr> … -
django mock sms send
I have a method that sends sms to your phone, how can I mock it? services.py def send_msg(phone_number): url = settings.SMS_API_URL params = { ... } resp = requests.get(url, params) status_code = resp.json().get('status_code') return status_code tests.py @pytest.mark.django_db // mock it def test_sms_send(api_client): data = { 'phone_number': 'some_valid_phone_number' } response = api_client.post(reverse('phone_verify'), data=data) assert response.status_code == status.HTTP_200_OK -
how to calculate elo efficiently in django?
I'm managing ORM to update ELO rating, but this is hard for me. This is ELO model table. If I insert data between those instances, what will happen? id| league | match_date | player | rating --+--------+------------+---------+-------- 1| 1| 2022-01-01| AAA| 1015.0 (winner) 2| 1| 2022-01-01| BBB| 985.0 (loser) 3| 1| 2022-01-03| CCC| 1016.4 ... 4| 1| 2022-01-03| AAA| 999.4 ... 5| 2| 2022-01-05| AAA| 1015.0 6| 2| 2022-01-05| BBB| 985.0 7| 2| 2022-01-07| CCC| 1015.0 8| 2| 2022-01-07| BBB| 985.0 ... ... data to be inserted => ( league = 1, match_date = 2022-01-02, player = [AAA, CCC] (first is winner) ) Ordering of table is league ASC, match_date ASC. So data will be inserted to between second row and third row. However, rating values what after inserted data isn't currect. What I searching is how to update rating efficiently? Do I run for loop for update all ratings? In my opinion this will be create lots of Hits to DB. I've already created ORM using Subquery, but Subquery doesn't calculate based on calculated data, instead of data from table. It is deprecated because I inserted data. Is there any method using ORM to solve this problem, reply to … -
How to make login in django through a different table than auth_users?
Not sure what I am doing wrong I will leave below my files. The register method works perfectly but when I am doing the login, everytime the output is user is none. Does anyone know what I did wrong? I read the documentation of authentication with django but I cannot spot the problem. I saw that there were some questions about this problem, but I couldn't solve mine. settings.py AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', views.registerMethod, name="register"), path('login/', views.loginMethod, name="login"), path('', include("main.urls")), path('', include("django.contrib.auth.urls")), ] views.py def registerMethod(request): if request.method=='POST': if request.POST.get('email') and request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('password'): user = NewUser() user.first_name = request.POST.get('firstname') user.last_name = request.POST.get('lastname') user.password = request.POST.get('password') user.email = request.POST.get('email') password = user.password.encode('utf-8') # Hash the ecoded password and generate a salt: hashedPassword = bcrypt.hashpw(password, bcrypt.gensalt(10)) user.password = str(hashedPassword) user.first_name = CleanString(user.first_name) user.last_name = CleanString(user.last_name) user.email = CleanString(user.email) message = None if UserExistsByEmail(user.email): message = 'You are already registered!' return render(request, 'register/register.html', {"message":message}) else: user.save() message = 'You have succesfully created an account!' return render(request, 'registration/login.html', {"message":message}) else: return render(request, 'register/register.html') else: return render(request, 'register/register.html') def loginMethod(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate( email=email, password=password) if …