Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL doesn't have a redirection to https
I have applications in Django 2.2 on the server where nginx is. My application can work under several subdomains, but it is the user who chooses what domain it will be, for example: first.mydomain.com test.mydomain.com city.mydomain.com My problem is that these subdomains work under https but only when I type in the whole address: https://test.mydomain.com. However, it does not work when I type in the address itself: test.mydomain.com - here I got nginx page with "Welcome to nginx!" I tried with nginx and redirects - no result. My nginx settings server { listen 80; server_name ~^(?<subdomain>.+)\.mydomain\.com$; return 301 https://$subdomain.mydomin.com$request_uri; } How can I get a redirection to https after typing only test.mydomain.com? -
Use DRF permissions in django view
I have several DRF permission classes for my rest api like this: class CanAccessImage(permissions.BasePermission): message = _("You don't have permission for this action.") def has_object_permission(self, request, view, obj): if obj.user == request.user: return True else: return False Can I use this permissions in Django views? -
Django - The 'image' attribute has no file associated with it
I had to change the save method so that a user can register without a profile image. Now I get this same error that no file was associated with the login. As per traceback it validates the form and tries to saves the image? It should not check for the image. Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in dispatch 90. return super(LoginView, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in form_valid 119. auth_login(self.request, … -
Travis CI test fail as if no database
I have tested my software, which is a Django app, locally using nose. Running python manage.py test works as expected, but uploading my app onto travis fails. dist: xenial # required for Python >= 3.7 language: python python: - "3.7" env: - CM_DATABASE_NAME='cm_db.sqlite3' CM_DATABASE_USERS_NAME='messenger_users_db.sqlite3' CM_DATABASE_ENGINE='django.db.backends.sqlite3' CM_DATABASE_USER='' CM_DATABASE_PASSWORD='' \ CM_DATABASE_HOST='' CM_DATABASE_PORT='' CM_DATABASE_USERS_ENGINE='django.db.backends.sqlite3' install: - pip install -r requirements.txt - pip install . # command to run tests script: - python manage.py makemigrations && python manage.py migrate auth && python manage.py migrate --database=default && python manage.py migrate --database=messenger_users_db && python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminpass')" && python manage.py test --keepdb # https://stackoverflow.com/questions/6244382/how-to-automate-createsuperuser-on-django # Push the results back to codecov after_success: - codecov The branch in specific is tester. https://travis-ci.com/afinidata2019/afinidata-content-manager -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/$']
I've been all day struggling with this issue in my starting Django Course. I'm getting this error: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/$'] Below you can see my code. I wish someone could give me a hand on this. Thanks a lot. views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from django.http import Http404 from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} print ("esto es CONTEXT: ") print (context) print(request) print ("FIN DE CONTEXT") return render(request, 'polls/index.html', context) # Create your views here. def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] index.html `<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> ` -
Using Django sqlite in web application any security precautions
I've hidden the secret key/admin location/security precautions for superuser. Any security precautions for the securing the base sqlite DB in Django web application? Any general DB Django security tips? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Can you do additional math on an aggregate value in a Django queryset
I am trying to avoid repeat aggregating on a value I have already calculated. I am already getting an annual total, but I also want a quarterly total What would work: props_obj = PropertiesUsers.objects\ .aggregate(returns_coc_a=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))), returns_coc_q=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))) / Value(4)) What I am trying to find out if/how I can do (reuse the annual amount): props_obj = PropertiesUsers.objects\ .aggregate(returns_coc_a=Sum(F('subscribe_amount') * (F('deal_coc') / Value(100))), returns_coc_q=returns_coc_a / Value(4)) -
How can I make an immutable created_at field in MySQL
I'm trying to have an immutable field(created_at) and be able to update it(updated_at) without altering the original created_at field. This is a django project if that matters -
Django: How to prevent duplicates when using "Signals" with "dispatch_uid"?
Hello i am testing Django User/ AUTH nesting with other models. i made a simple model for my User called MyProfil. Everytime a new User is registered a new MyProfil object will created automatically and linked to the specific User. models.py #-- create a MyProfil.object for new user @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_myprofil(sender, instance, created, **kwargs): if created: MyProfil.objects.create(owner=instance) class MyProfil(models.Model): # --- head id = models.UUIDField(primary_key=True, default=uuid4, editable=False) oblink = models.UUIDField(unique=True, default=uuid4, editable=False) owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # --- body aboutme = models.TextField(max_length=300, blank=True) city = models.TextField(max_length=300, blank=True) Question The Django Doc mentioned to usedispatch_uid to prevent that maybe duplicates will send. Unfortunately i don´t really understand how to apply dispatch_uid so ended up with this approach for receiver. models.py <...> from django.core.signals import request_finished #-- create a MyProfil.object for new user @receiver(post_save, sender=settings.AUTH_USER_MODEL, dispatch_uid="my_unique_identifier") def create_myprofil(sender, instance, created, **kwargs): if created: MyProfil.objects.create(owner=instance) request_finished.connect(create_myprofil, dispatch_uid="my_unique_identifier") <...> So my question is if this the right way to apply dispatch_uid ? -
Attach a callback to a newly created <select>
I'm trying to implement chained dependent dropdown combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears to select a subcategory, and so on until the innermost (most specific) category is selected. The code I have currently only works for one subcategory (direct children), how can I make it work for other levels too? So, I need to attach an onChange callback to a newly created <select> somehow. This is jQuery code in my Django template: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("select").change(function () { var url = $("#productForm").attr("data-products-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { $("#productForm").append(data); } }); }); </script> {% endblock %} Here is my view: def load_categories(request): category_id = request.GET.get('category') subcategories = Category.objects.get(id=category_id).get_children() return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) products/category_dropdown_list_options.html <select id="select_{{ subcategories.first.get_level }}"> <option value="">---------</option> {% for subcategory in subcategories %} <option value="{{ subcategory.pk }}">{{ subcategory.name }}</option> {% endfor %} </select> Here is my urls.py: app_name = 'products' urlpatterns = [ path('create/', product_create_view, name='product-create'), path('ajax/load-categories/', load_categories, name='ajax_load_categories') ] -
How to calculate a rank in a property decorator in Django model when the rank is based on another property decorator
I am newbie coder and very new to Django/Python. I am building an application that consolidates results for a rowing race. I have the following models in models.py. class Crew(models.Model): name = models.CharField(max_length=50) id = models.IntegerField(primary_key=True) composite_code = models.CharField(max_length=10, blank=True, null=True) club = models.ForeignKey(Club, related_name='crews', on_delete=models.CASCADE) rowing_CRI = models.IntegerField(blank=True, null=True) rowing_CRI_max = models.IntegerField(blank=True, null=True) sculling_CRI = models.IntegerField(blank=True, null=True) sculling_CRI_max = models.IntegerField(blank=True, null=True) event = models.ForeignKey(Event, related_name='crews', on_delete=models.CASCADE) status = models.CharField(max_length=20) penalty = models.IntegerField(default=0) handicap = models.IntegerField(default=0) manual_override_minutes = models.IntegerField(default=0) manual_override_seconds = models.IntegerField(default=0) manual_override_hundredths_seconds = models.IntegerField(default=0) bib_number = models.IntegerField(blank=True, null=True) band = models.ForeignKey(Band, related_name='bands', on_delete=models.CASCADE, blank=True, null=True) @property def raw_time(self): if len(self.times.filter(tap='Start')) > 1 or len(self.times.filter(tap='Finish')) > 1: return 0 start = self.times.get(tap='Start').time_tap end = self.times.get(tap='Finish').time_tap return end - start @property def race_time(self): # The race time can include the penalty as by default it is 0 return self.raw_time + self.penalty*1000 @property def event_band(self): if not self.band: return self.event.name return str(self.event.name) + ' ' + str(self.band.name) class RaceTime(models.Model): sequence = models.IntegerField() bib_number = models.IntegerField(blank=True, null=True,) tap = models.CharField(max_length=10) time_tap = models.BigIntegerField() crew = models.ForeignKey(Crew, related_name='times', on_delete=models.SET_NULL, blank=True, null=True,) I want to create two additional properties. One that will rank a crew by race_time across all crews and one that will rank … -
I get NoReverseMatch error when trying to pass data from a form to database in Django
I am new to Django and i wrote some code which is supposed to take some data from a form in orderr.html and pass it to the data base ( the app is called order) orderr.html <form action="{% url "order:createpost" %}" method="post"> **this is where i get the error** {% csrf_token %} First name: <input type="text" name="first_name"/><br/> Last name: <input type="text" name="last_name"/><br/> Address: <input type="text" name="address"/><br/> <input type="submit" value="Send"/> views.py @require_POST def createpost(request): if request.method == 'POST': if request.POST.get('first_name') and request.POST.get('last_name') and request.POST.get('address'): post = buyerData() post.first_name = request.POST.get('first_name') post.last_name = request.POST.get('last_name') post.address = request.POST.get('address') post.save() return render(request, 'order/orderr.html') else: return render(request, 'order/orderr.html') urls.py from django.conf.urls import url from order import views from django.urls import path app_name = 'order' urlpatterns = [ path('order_page/', views.OrderPage, name='order_page'), ] Do you have any idea why the error says that 'Reverse for 'createpost' not found' -
How to create a dict with two sub list?
I am trying to loop through two querysets with keys based on dates in the set. Each date has two types of items: Life events and work. The dict should look like this: Timeline['1980']['event'] = "He was born" Timeline['1992']['work'] = "Symphony No. 1" Timeline['1993']['event'] = "He was married" Timeline['1993']['work'] = "Symphony No. 2" How do I create this dictionary? -
Readonly don'y save on database - Django
I am creating a form with Django, and the result of one input I am putting in another input that is like "readonly". I added everything in models.py and forms.py, but it is not creating readonly columns in the database. To leave as readonly I used JavaScript by setting .readOnly to true. Does anyone know what the problem may be? -
MultipleObjectsReturned error in Django but I want multiple objects to be returned
Using Django REST framework I created an url which maps to a page with a JSON file containing all the objects in my database. I want to do the same but instead of showing all the objects I want only the objects that match a specific category (category is an attribute in my model). I have urls that show a JSON files with a single object in it (using the pk attribute) but when I try to do the same thing with category instead of pk I get a MultipleObjectsReturned error. I'm just sperimenting with the REST framework, I tried using different views and class based views solving nothing. Any hint or suggestion is really appreciated thanks. # models.py class Hardware(models.Model): name = models.CharField(max_length=25) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) def get_api_url(self): return api_reverse("category-api-postings:post-rud", kwargs={'category': self.category}) #views.py class HardwareListView(generics.ListCreateAPIView): pass lookup_field = 'pk' serializer_class = HardwareSerializer def get_queryset(self): query = self.request.GET.get("q") qs = Hardware.objects.all() if query is not None: qs = qs.filter(Q(title__icontains=query) | Q(content__icontains=query)).distinct() return qs class HardwareRudView(generics.RetrieveUpdateDestroyAPIView): pass lookup_field = 'category' serializer_class = HardwareSerializer def get_queryset(self): return Hardware.objects.all() #urls.py app_name = 'category-api-postings' urlpatterns = [ path('', exercise_view), path('list-api/', HardwareListView.as_view(), name='all'), path('list-api/<str:category>/', HardwareRudView.as_view(), name='post-rud') #serializer.py class HardwareSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) class Meta: … -
Django - Type Error: save() got an unexpected keyword argument 'force_insert'
I get this error when I try to register a new user. Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/home/django/django_project/accounts/views.py" in form_valid 34. new_user = User.objects.create(username=username, email=email) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 394. obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py" in save 80. super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save 808. force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 848. update_fields=update_fields, raw=raw, using=using, File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py" in send 193. for receiver in self._live_receivers(sender) File "/home/django/django_project/accounts/models.py" in post_save_user_receiver 150. new_profile = UserProfile.objects.get_or_create(user=instance) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create 466. return self._create_object_from_params(lookup, params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _create_object_from_params 500. obj = self.create(**params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 394. obj.save(force_insert=True, using=self.db) Exception Type: TypeError at /register/ Exception Value: save() got an unexpected keyword argument 'force_insert' I added a form for the user to upload profile picture and it worked but now I get this error accounts/models.py class UserProfile(models.Model): .... … -
Can a child template also use a child template in django?
My child template path is project/sales/templates/sales/table.html. It extends the another child template sale_summary_change_list.html. {% extends 'sale_summary_change_list.html' %} {% block result_list %} <div class="results"> <table> <thead> <tr> {% for header in table %} <th> <div class="text"> <a href="#">{{ header }}</a> </div> </th> {% endfor %} </tr> </thead> <tbody> {% for row in summary %} <tr class="{% cycle 'row1' 'row2'}"> <td> {{ row.color_pref }} </td> <td> {{ row.total | intcomma }} </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} The parent template is also located in the same folder. (project/sales/templates/sales/sale_summary_change_list.html) {% extends 'admin/change_list.html' %} {% load humanize %} {% block content_title %} <h1> Sales Summary </h1> {% endblock %} {% block result_list %} {% block table %} {% endblock %} {% endblock %} {% block pagination %}{% endblock %} My child template however is not appearing. What am I doing wrong? -
AJAX request duplicates entire page
I am trying to implement chained dependent dropdown combobox selection. I have a 'category' HTML combobox and once the value in there is changed, another combobox should appear to select a subcategory and so on until the innermost (most specific) category is selected. So, whenever the value in the combobox is changed I am firing an AJAX GET request which should reload only that bit of the page, however currently my code just duplicates entire page instead of just creating a new <select>. Here is my Django template with the jQuery code: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_category").change(function () { var url = $("#productForm").attr("data-product-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { $("#productForm").append(data); } }); }); </script> {% endblock %} Here is my view: def load_categories(request): category_id = request.GET.get('category') return render(request, 'products/category_dropdown_list_options.html', {'subcategories': subcategories}) Here is my urls.py: app_name = 'products' urlpatterns = [ path('create/', product_create_view, name='product-create'), path('ajax/load-categories/', load_categories, name='ajax_load_categories') ] and here is the tiny bit of HTML I am trying to create: <select> {% for subcategory in subcategories %} <option … -
Is that possible to run django nose test in different project?
Previously I wrote django nose test under app. Is that possible that creating a new project to test other projects? -
Template renders the same information for every user Django
My website has a feature where users can look at each other's profile pages, but at the moment, I have a problem where the currently logged in user's information is being displayed across all the profile pages. This is the code for the views.py view_profile def view_profile(request,pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user':user} return render(request,'mainapp/profile.html') And here are the urls.py path('profile/',views.view_profile,name='view_profile'), path('profile/<pk>/',views.view_profile,name='view_profile_with_pk'), And here is the UserProfileInfo model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) description = models.CharField(max_length=150) image = ProcessedImageField(upload_to='profile_pics', processors=[ResizeToFill(150, 150)], default='default.jpg', format='JPEG', options={'quality': 60}) joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField( default=False) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) I have tried all sorts of things including switching different things around etc. So for the rest of the code that is relevant to this problem, here is the actual template that is rendering this information {% extends 'mainapp/base.html' %} {% load static %} {% block content %} <p>{{ user }}</p> <p>{{ user.first_name }} {{ user.last_name }}</p><br> <p>{{ user.email }}</p><br> <p>{{ user.userprofileinfo.description }}</p><br> <img class="rounded-circle account-img" src="{{ user.userprofileinfo.image.url }}"> {% endblock %} The result that I wanted was for the user to be able … -
I am not able to access django inside virtual environment
If I install django on local system , then that django if I access in virtual environment Will that be accessible or I have to install django again in VirtualEnvironment? -
Impossible o order by time in django
I 've got a real problem that i can't fix. I'm trying to order a transaction by time but everything I do for ordering the queryset.... nothing work. here is my model class Transaction(models.Model): collocDonneur=models.ForeignKey(Person,related_name="collocDonneur",on_delete=models.SET_NULL,null=True, blank=True) collocReceveur=models.ForeignKey(Person,related_name="collocReceveur",on_delete=models.SET_NULL,null=True, blank=True) point=models.IntegerField(null=False) raison=models.TextField(null=True,blank=True) date=models.DateTimeField(default=timezone.now) class Meta: verbose_name="Transaction" and here is my view : def vote(request): person=Person.objects.all() transactions=Transaction.objects.all() transactions.order_by('date') return render(request,"liste.html",locals()) even if I replace 'date' by '-date', nothing work, even if i do a reverse() on the queryset... PLEASE HELP ME Thank you -
How to center tables in an html file?
I am trying to center some table in an Html file. Ive tried to add some style: "center" but it didnt work. I`ve converted those tables directly from word. Here is the code: https://jsfiddle.net/f90cg3oa/1/#&togetherjs=PDF3NnjNwb I would expect the table or any text to be shown in the middle of the html file. Would you have an idea on how to do this? Many Thanks, -
How can I make a QR-Code Verification in Django?
I'm attempting to create a website whereby people could buy tickets for an event, which we generate a QR-code. I want the QR-code to be scanned on the day of the event to verify the purchase when entering. I know that I could generate a QR code in in Django using Pypi, but I wasn't sure as to how this would be handled in the backend - especially which data to store in the QR code to verify the purchase. -
Security Concerns with Login and Register Django HTML Template and Views.py
Do you have any security concerns with what I've done being implemented in a production web app? Either in the Django HTML Template or my views logic? I would prefer to have the form in actual html rather than using {{ form }}. Is it ok to allow the user to implement very basic passwords? views.py is: from django.shortcuts import render, redirect from django.contrib.auth import get_user_model User = get_user_model() from django.contrib.auth import authenticate, login as auth_login from django.contrib import auth from memberships.models import UserMembership from django.contrib.auth.decorators import login_required from companies.models import Profile # Create your views here. def register(request): if request.method == "POST": # User has info and wants an account now! if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(email=request.POST['email']) return render(request, 'accounts/register.html', {'error': 'Email has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['email'], password=request.POST['password1']) auth.login(request, user) company = Profile() company.businessperson = request.user company.first_name = request.POST['firstname'] company.last_name = request.POST['lastname'] company.company_name = request.POST['companyname'] company.phone_number = request.POST['phonenum'] company.save() return redirect('memberships:payment') else: return render(request, 'accounts/register.html', {'error': 'Passwords must match'}) # User wants to enter info return render(request, 'accounts/register.html') def login(request): if request.method == "POST": user = authenticate(email=request.POST["email"], password=request.POST["password"]) if user is not None: # Our backend authenticated the credentials auth_login(request, user) return redirect('dashboard') …