Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can't edit in my template by use django form
I have two models child and parent models by which a child model is a foreign key of parent model,i have a template that have child id on it and django-form tag to edit parent records but when i render that template i can't see edit fields on it that will help me to edit my records. Here is child model class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstname here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname'] here is my views.py file def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) if request.method=="POST": form=ParentForm(request.POST,instance=child) if form.is_valid(): form.save() return redirect('more_details',pk=pk) else: form=ParentForm(instance=child) context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) and here is my template file <div class="card-body"> <form action="" method="post" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </div> -
HTML image not found (django)
I've been facing this problem, where i get error telling me image not found, and i get cracked picture on the website. I will attach the code including the directory and also the terminal where I get the error. -
How to delete "<QuerySet[]>" from the json response "<QuerySet [data]>"?
I'm sending data in json but the output is like this: { "ids": "<QuerySet [dafa1, lnvq2]>" } and I want it just like this: { "ids": "dafa1, lnvq2" } here's the code I'm using: from upload.models import Images from django.http import JsonResponse def list(request): ids = Images.objects.filter(allowed=True).values_list('id', flat=True) data = { 'ids': str(ids), } return JsonResponse(data) -
Django - User Registration and Profile Settings
So, I managed to create the registration and login for the users. I created two kind of groups, one with restrictions and one with no restrictions. Basically the one with restrictions will managed by me in the admin panel,I will add personally the users in some group instead of another, so no issue here. My issue is that when a new user does the registration in my admin panel it will goes only on my "Users" section and it will not be automatically linked to the Model "user profile" I have created. So I will have to manually add the user into the "Model". How can I make the user automatically be associated with that class in order to make him/her sets up his/her profile picture and so on? accounts/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class FormRegistrazione(UserCreationForm): email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] accounts/models.py from django.db import models from django.contrib.auth.models import User # from django.db.models.signals import post_save # from django.dispatch import receiver class UserProfile(models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) CV = models.FileField(null= True, blank=True) school = models.CharField(max_length=200, null=True) profile_photo = … -
Alter uploaded image before saving with Django admin models
I have a Django model which saves an image. However before I save the model I want to check the width and height and create a md5 hash of the image to check for duplicate uploads. I'm not using any custom forms I'm just trying to upload some images using the admin backend. I'm using Django==3.0.5 and Python 3.8.2 This is my model: from django.db import models from hashlib import md5 from PIL import Image from io import BytesIO class UploadedImage(models.Model): """An image upload Arguments: models {[type]} -- [description] """ name = models.CharField(max_length=255, default='') pub_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='images/') height = models.IntegerField(default=0) width = models.IntegerField(default=0) extension = models.CharField(max_length=20, null=False, default='') hash = models.CharField(max_length=50, null=False, unique=True, db_column='hash', default='') def __str__(self): return self.name @staticmethod def hash_exists(hash): return UploadedImage.objects.exists(hash=hash) def generate_name(self): img_id = UploadedImage.objects.values('id').order_by('-id').first()['id'] + 1 self.name = "%s_%s" % (img_id, self.hash[-4:]) def save(self, *args, **kwargs): # get the actual image??????? # img = self.request.FILES['image'] ???? if img: self.hash = md5(img).hexdigest() try: if hash_exists(self.hash): raise ValueError("image hash already exists, duplicate image!") except ValueError as err: print(err.args) return err img = Image.open(BytesIO(img)) self.width, self.height = img.size self.extension = img.format.lower() self.generate_name() else: print("no image") return "" super(UploadedImage, self).save(*args, **kwargs) However I cannot find anywhere … -
Django 3 returns ModuleNotFound error after renaming the project
I renamed a django project and now I cannot start the WSGI server anymore. It is looking for an old name, but I have changed the name everywhere. Where is the server looking for the old name? The traceback is not helpful. I tried removing all __pycache__ folders. omics_server>python server.py Traceback (most recent call last): File "server.py", line 3, in <module> from omics_server.wsgi import application File "/home/ubuntu/workspace/omics_server/omics_server/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/ubuntu/miniconda3/envs/omics/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'omics' manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'omics_server.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() omics_server/wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'omics_server.settings') … -
What is the good practice to keep multiple html having the same style and components but different in certain body content
new to web dev here. I am wondering what is the common practice to have multiple pages with the same components (header, sidebar, footer) but only different in the content. I looked around there are suggestion about using php include and other about html import. Say I have a basic.html with <head> fixed stuff </head> <body> <div> sidebar here </div> <!-- Here will be different content other each page --> <footer> fixed stuff </footer> <!-- common scripts here --> </body> Then I will have another 2 pages, say price.html, blog.html. How can price.html recycle basic.html but just with different main contents in the body. I don't know how I can use include here. because the content is in the middle. -
packages aren't install in project's virtual enviroment
i installed django-ckeditor with pip but it goes to the "/home/def-dev/.local/lib/python3.8/site-packages" path when i'm trying to create venv manually. but when i create project with pycharm it goes to the "./venv/lib/python3.8/site-packages" path that this path belong's to internal project's venv . and this make's unknown for pycharm . what should i do to make pycharm find packages from "/home/def-dev/.local/lib/python3.8/site-packages" or when i'm creating venv manually pip save's packages into "./venv/lib/python3.8/site-packages" path. when i create venv manually $ pip3 install django-ckeditor Requirement already satisfied: django-ckeditor in /home/def-dev/.local/lib/python3.8/site- packages (5.9.0) Requirement already satisfied: django-js-asset>=1.2.2 in /home/def- dev/.local/lib/python3.8/site-packages (from django-ckeditor) (1.2.2) when i create venv with pycharm $ pip3 install django-ckeditor Requirement already satisfied: django-ckeditor in ./venv/lib/python3.8/site-packages (5.9.0) Requirement already satisfied: django-js-asset>=1.2.2 in ./venv/lib/python3.8/site-packages (from django-ckeditor) (1.2.2) -
How to create intermediate class in django
I hav this models from django.db import models from embed_video.fields import EmbedVideoField # Create your models here. class Video(models.Model): video_author = models.CharField(default='Bongo Media', max_length=20) video_title = models.CharField(max_length=100) video_file = models.FileField(blank=True) video_image = models.ImageField(default='image.png') video_embed_link = EmbedVideoField(blank=True) video_descriptions = models.TextField(max_length=100, blank=True) video_pubdate = models.DateTimeField(auto_now=True) is_recommended = models.BooleanField(default=False) def __str__(self): return self.video_title class Artist(models.Model): artist_picture = models.ImageField(upload_to='media') artist_name = models.CharField(max_length=100) artist_songs = models.ManyToManyField(Video) def __str__(self): return self.artist_name In database i have a lot of videos and artists. in views.py how can i query so that when i click to the artist name i can see only he is videos, or is there any mistake in my models? Or is the intermediate class needed?, if so, how can i create the intermediate class and how to query data with intermediate class so that i can filter all videos belonging to one artist -
djangocms - cannot import name 'NamespaceAlreadyRegistered'
I have developed a simple project with DjangoCMS(3.7.2) and it works great in the local. I 'm gonna run it on a ubuntu server, which I have another Django project run on it with no issues. Both of my projects are built using python 3.6 & MySQL database. I took these steps to run my new project: Cloned the project on the server via git and updated the settings.py file Created an empty database on the server Installed a virtualenv on server by python3 -m venv venv Activated the venv and upgraded pip Installed requirements successfully using pip install -r requirements.txt Tried to Migrate by python3 manage.py migrate But I got this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/www/pishbiny/myenv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked … -
Django models - autocountable field
Welcome! I have a question and i can't find answer. I made model consisting of 3 fields: hours to maintenance, current hours and remaining hours. Is it possible using django admin to have this remaining hours field to be auto countable? ( substracting hours to maintenance and current hours typed by user). This rm field in django admin should be autofilled by substracting hours to maintenance and remaining hours. Regards and thank u for help models.py from django.db import models # Create your models here. class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.IntegerField(help_text = "test", null = True) #current hours ch = models.IntegerField(help_text = "test", null = True) #hours remaining #rm = models.TimeField(auto_now = False) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) -
How to update model field using django signals when updating object in m2m field?
I'm trying to update the order total on updating quantity on OrderItem. For that i'm using django signal m2m change with post_add or post_remove action. Here's my model: class Item(models.Model): name = models.CharField(max_length=20, unique=True) price = models.DecimalField(max_digits=8, decimal_places=2) class Order(models.Model): order_item = models.ManyToManyField('OrderItem') total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() total = models.DecimalField(max_digits=8, decimal_places=2, default=0.0) m2m changes signal def m2m_changed_order_item_receiver(sender, instance, action, *args, **kwargs): """Receiver for updating total of Order through OrderItem""" if action in ["post_add", "post_remove"]: order_items = instance.order_item.all() total = 0 for order_item in order_items: total += order_item.item.price * order_item.quantity instance.total = total instance.save() m2m_changed.connect(m2m_changed_order_item_receiver, sender=Order.order_item.through) Testcase: def test_updating_order_item_quantity_in_order(self): order_item1, order_item1_data = create_sample_order_item( item=self.item1, quantity=2, data_only=False ) order_item2, order_item2_data = create_sample_order_item( item=self.item2, quantity=2, data_only=False ) order, _ = create_sample_order( order_items=[order_item1_data, order_item2_data], data_only=False ) order_items = order.order_item.all() for order_item in order_items: if order_item == order_item2: order_item2.quantity = 10 order_item2.save() order.save() # update order_item2_total = order_item2.item.price * 10 # works completly fine but i'm searching for alternative method using signal # order.order_item.remove(order_item2) # order.order_item.add(order_item2) order.refresh_from_db() order_item1.refresh_from_db() order_item2.refresh_from_db() # check weather OrderItem total is updated or not self.assertEqual(order_item2.total, order_item2_total) # fails here self.assertEqual(order.total, order_item1.total + order_item2.total) It works completly fine when i first remove … -
How do you save a foreikey in the django of an n: m relationship?
views.py `@login_required def add_arquivo(request, id): if str(request.user) != 'AnonymousUser': if str(request.method) == "POST": form_arq = ArquivoForm(request.POST, request.FILES) if form_arq.is_valid(): form_arq.save() arquivo = Arquivo.objects.create(arq_pro_id = id, arq_usu_id = request.user, arq_desc = form_arq.arq_desc, arq_nome = form_arq.arq_nome, arq_imagem = form_arq.arq_imagem, arq_localizacao_documento = form_arq.arq_localizacao_documento) return redirect('/inicio_projeto/')# rediredionando para lista else: form_arq = ArquivoForm() return render(request, 'arquivos/add_arquivo.html', {'form_arq' : form_arq }) else: return redirect('/')` I don't know how I can save this data arq_pro_id and arq_usu_id together with the others. class Arquivo(models.Model): arq_pro_id = models.ForeignKey(Projetos, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Projetos arq_usu_id = models.ForeignKey(Pessoa, on_delete=models.CASCADE, null=True) # Pegando o id da tabela Usuarios arq_desc = models.TextField('Descrição:') arq_nome = models.CharField('Nome:', max_length=100, null=True) arq_imagem = StdImageField('Imagem:', upload_to='imagem_projeto_arq', null=True) arq_localizacao_documento = models.FileField(upload_to='arquivos_projeto', null=True, max_length=1000) this Arquivos table can have several arquivos linked to a project. class Projetos(models.Model): FINANCIAMENTO_CHOICES = ( ("S", "Sim"), ("N", "Não") ) # pro_titulo = models.CharField('Título do projeto:', max_length=100) pro_imagem = StdImageField('Imagem:', upload_to='imagem_projeto', null=True) # pro_autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) pro_desc = models.TextField('Descrição:') pro_financiamento = models.CharField('Financiamento:', max_length=1, choices=FINANCIAMENTO_CHOICES, blank=False, null=False) pro_financiadora = models.CharField('Instituição financiadora:', max_length=100) pro_datetime = models.DateTimeField('Data de publicação:', blank=True, null=True) pro_inst = models.ForeignKey(Instituicao, on_delete=models.CASCADE, null=True) pro_usuarios = models.ManyToManyField( Pessoa, through='ProjetosDosUsuarios', through_fields=('pdu_projetos', 'pdu_usuarios'), # ) def publicar(self): self.pro_datetime = timezone.now() self.save() … -
Django - Signals are not getting called from User model while creating a new user
I am working on simple hands-on project, and using signals to save the Profile which is part of User model. Seems the signals are not getting called. Though i did not encounter any errors so could not trace what is the issue or what config i am missing. I tried using print statement, and got to know that the signals is not even called. Any pointer how i can check what is causing the issue. Please help... Below is the code i am using. #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default = 'images/default.jpg', upload_to = 'images/profile_pic') def __str__(self): return f'{self.user.username} Profile' #signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print('inside signals') if created: print('inside signals ------------------------> create method is called') Profile.objects.create(user = instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() # modified the app.py to include the method ready(). from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals -
How can i include a foreign key field in the "fields" tuple to make it appear on detail view page in Django Admin
Models: I have a model like this class TestModel1(models.Model): bookingid = models.ForeignKey(paymenttable) // foreign key name = models.CharField(max_length=100, null=False, db_index=True) // I want this to be displayed in both the list view and detail view @property def custom_field(self): return self.bookingid.username Admin.py class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin): // this works and i get custom_field in list view list_display = ('custom_field', 'name') readonly = ('custom_field', 'name') // this dosent work and gives error fields = ('custom_field', 'name') Error: Unknown field(s) custom_field. Check fields/fieldsets/exclude attributes of MyAdmin class -
Convert a Pillow image to a Django Imagefield
I have an imagefield called thumbnail and another called thumbnail_low which is a 320 * 200 version of thumbnail. when the user uploads an image from the thumbnail imagefield I internally create a 320 * 200 version that is assigned to thumbnail_low. that's the way I do it (see the code below). the problem is that the image is correctly assigned to thumbnail_low except that the browser indicates waiting for localhost until my machine crashes which is weird is that after restarting I find that the post has been created correctly. class Post(models.Model): thumbnail = models.ImageField(upload_to=post_directory_path) thumbnail_low = models.ImageField(upload_to=post_directory_path, null=True, blank=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): obj = super(Post, self).save(force_insert, force_update, using, update_fields) if self.thumbnail: img = Image.open(self.thumbnail.path) img = img.convert("RGB") img.save(self.thumbnail.path, format="JPEG", optimized=True) stream = BytesIO() copy = img.copy() copy.thumbnail((320, 200), Image.ANTIALIAS) copy.save(fp=stream, format="JPEG") thumbnail_name = "low" + get_random_string(length=4) + str(self.id) + ".jpeg" content = stream.getvalue() self.thumbnail_low.save(thumbnail_name, ContentFile(content)) return obj -
URL safety in Django E-commerce
I'm working with my own e-commerce in Django and the payments are handled like this: I have a checkout view with a slug (since I'm working with only two products) where the user sumbits their shipping data. Then they are redirected to the payment URL, that is guided by a Primary Key. It looks like this: http://....../payment/24 The problem that worries me is the simplicity of the id, it's just a number that anyone can access with the URL. Is there any way to make this safer? I was thinking about hashing the URL, but didn't find any tool for that. note: It's a guest checkout, so I'm not dealing with registered users. Thanks in advance! -
Alternative Windows/bash command 'workon [insert virtualenv name]' for Mac Terminal
I've seen you can activate virtualenv on Windows bash by typing 'workon [virtualenv name]' is there a similar command for the Mac Terminal which does the same thing? I want to avoid the long way of activating the virtualenv, which is by going into the sub folder that contains 'bin' and then using 'source bin/activate'. -
How can execute two functions respectively in Django?
I have used the code prepared in https://www.pythoncircle.com/ to import and export an excel file using Django. This code is provided below: from Django.shortcuts import render import openpyxl views.py file: def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) worksheet = wb["Sheet1"] print(worksheet) excel_data = list() for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) import xlwt from django.http import HttpResponse def download_excel_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet("sheet1") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Column 1', 'Column 2', 'Column 3', 'Column 4', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() wb.save(response) return response urls.py file: from django.urls import path from django.http import HttpResponse from . import views app_name = "myapp" urlpatterns = [ path('', views.index, name='index'), path('', views.download_excel_data, name='download_excel_data'), ] When I run the described code, only the index function is executed. while when I change the urlpatterns to: urlpatterns = [ path('', views.download_excel_data, name='download_excel_data'), path('', views.index, name='index'), ] the download_excel_data function is executed. How can I execute both functions respectively? Thanks … -
django admin view image file not found
i am new here in django, I have uploaded image file, i can see file is uploaded under my app myapp/mysite/uploads/testimonial/image.jpg file is there, so it is correct, but now when i open that testimonial module in admin, and when i edit that testimonial and click on that view image link it is showing that as this link http://127.0.0.1:8000/uploads/uploads/testimonial/image.jpg, but that is not visible, can anyone please help me why that image is not showing, i am using python version 3.6, here i have mention whole my code, can anyone please look into it and help me to resolve this issue ? models.py class Testimonial(models.Model): def __str__(self): return self.title TESTIMONIAL_STATUS = ((1, 'Active'), (0, 'Inactive')) title = models.CharField(max_length=255) description = HTMLField() image = models.ImageField(upload_to='uploads/testimonial') status = models.PositiveSmallIntegerField(choices=TESTIMONIAL_STATUS, default=1) published_date = models.DateTimeField(auto_now_add=True, blank=True) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/') MEDIA_URL = '/uploads/' urls.py urlpatterns = [ path('', views.index, name='index'), ] -
Filtering with django model object list using dynamic path
I want to do something like this. path = "pk__in" resources = resource_model.objects.filter(path=resource_ids) I would want resources to be a list of objects from resource_model. How can I achieve filtering with dynamic path? -
django registeration verification of email not working
I followed blog https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef for email verification but it adding a user before verification of link. -
Why doesn't my toggle work correctly when I use staticflies?
I am studying Django and found the following problem when using staticsfiles, the toggler that appears when the screen is reduced does not extend my bootstrap navbar, I did not find the error. NOTE: the rest works, dropdown, navbar (css / js) NOTE1: when I use CDN everything works, including the toggler here are the excerpts that I call staticsfiles and the link to the complete project on github settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) scripts.html {% load static %} <script src="{% static 'jquery/dist/jquery.js' %}"></script> <script src="{% static 'popper.js/dist/umd/popper.js'%}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> Projeto no Github -
Which is better - django login or jQuery AJAX?
Django's indigenous login system is a lot confusing, I really don't know whether its even an AJAX call or simple form registration plus the security concerns with it is not really specified anywhere on the internet. I used jQuery AJAX for all form submissions till yesterday and now that this Django feature of login is an integrated Django feature I'm using it. Is this login methodology better over the AJAX calls? -
Django - How do I had a "points" field to my User model
I'm making an online quizz but when I add a "points" field to my User model, I have an error (I added the app in INSTALLED_APPS). So, I created a UserPoints model in my models.py : from django.db import models from django.contrib.auth.models import User class UserPoints(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) def AddPoints(self, amount): self.amount = amount self.points += amount self.save() Then I resgistered it in admin.py : from django.contrib import admin from .models import UserPoints admin.site.register(UserPoints) But when I type python manage.py makemigrations I have this error : You are trying to add a non-nullable field 'id' to pointsutilisateur without a default; we can't do that (the database needs something to populate existing rows)