Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly fork django-taggit?
I want to make a small tweak to django-taggit - I want to add an added_by field on the Tag model as a ForeignKey to User, so I can list all tags added by a particular user. So, I cloned the repo into the folder where all the apps are and made the changes to the code, however I'm getting an error: /home/alex/.repos/codelib/github/hawk/src/hawk/hawk/settings.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/alex/.repos/codelib/github/hawk/env/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) 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 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'taggit' ...as a fix, I tried to … -
Django Stripe Fake Card Causes TemplateDoesNotExist Error
When a person types in a fake credit card into my Stripe payment form, I get an error page saying "TemplateDoesNotExist at /memberships/payment/ followed by membership/membership_payment.html". The following lines of code get executed: views.py: https://dpaste.de/8EUX#L77,78,79,80,81,82,83,84,85 html files: https://dpaste.de/2Y37 I need a way to not show that error page and redirect the user back to /memberships/ and display a card decline message instead. However, if a user types in a valid card, that redirect is correct. Otherwise maybe I need a way to validate the card is able to be charged to see if it is a real one before being able to submit the form. Traceback has been included in the dpaste link. I am using this github project as a baseline so all files are mostly the same (except for my dpaste code updates): https://github.com/danialbagheri/video-membership Any help would be greatly appreciated. -
Customers app and model in their own app away from staff users in django
i want to create app for my own customers and create custom user model for him i searched for make this and i reached an AbstractBaseUser,BaseUserManager class them contain all kind of main website users admin (staff users) with customers users in one model in customers app i want make an customers app and customers model on their own and staff users in their own app -
'NoneType' object has no attribute 'set_password' in django registration and login
I am entirely new to django. Trying to create login and registration system. User registers successfully, saved in database but I get this error after registering. "'NoneType' object has no attribute 'set_password'" views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) form.save() username = form.cleaned_data.get('username') fullname = form.cleaned_data.get('fullname') password = form.cleaned_data.get('password1') user = authenticate(request, username=username, password=password) messages.success(request, f'Welcome to blaza {fullname}') user.set_password(password) user.save() if user is not None: login(request, user) return redirect(reverse('home')) else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) When I remove "user.set_password" it works but registered users can not login with their credentials even when the username and password is correct, It says incorrect username and password. (only admin account, superuser can login). So I researched and had to add the user.set_password and user = form.save (I get warning that local variable user value is not used) forms.py class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50) fullname = forms.CharField(max_length=200) email = forms.EmailField(max_length=200) password2 = None class Meta: model = User fields = ('username', 'fullname', 'email', 'password1') def clean_password1(self): password1 = self.cleaned_data.get('password1') try: password_validation.validate_password(password1, self.instance) except forms.ValidationError as error: self.add_error('password1', error) return password1 Models.py class CustomUser(AbstractUser): class Meta: db_table = 'users' fullname = models.CharField(max_length=200) email … -
ml model on django and html
I have index.html <p>input an image</p> <p> <form> <input type="file" name="pic" accept="image/.jpg" onchange="loadFile(event)"></input> <img id="output"/> <script> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> </form> </p> <p> <form> <input type="submit" value="result"></input> </form> </p> views.py def test(request): if request.POST: d = request.POST.dict() img = d.get("pic") a=image_array(img) # convert image to array use to test model r=model(a) # return render(request, "./index.html",r) else: return render(request, "./index.html") how can I show the result of predict below the test button? -
Having both username and email but using email to authenticate users in django-rest-auth
With most tutorials, I see people use either email or username. I want to have both fields but using only the email to authenticate users with Django-rest-auth, as the email will be verified and is very important. but the username also has its importance in my app. models.py class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) fullname = fullname user = self.model( email=email, fullname=fullname, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, fullname, password, **extra_fields): return self._create_user(email, fullname, password, False, False, **extra_fields) def create_superuser(self, email, fullname, password, **extra_fields): user=self._create_user(email, fullname, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() def __str__(self): return self.email serializers.py class CustomRegisterSerializer(RegisterSerializer): ''' a custom serializer that overides the default rest-auth, and for the user to register himself ''' username = None email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) fullname = serializers.CharField(required=True) def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return … -
login isn't calling inactive json response
I am writting a signup based confirmation ,but after it log in it works, however it doesnt login at all . the issue isnt raising return JsonResponse({"message": "error"}) instead of return JsonResponse({"message": "inactive"}) , So I can response that over ajax, and tell the user in a fancy way to activate it def post(self, request): email= request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: if user.is_active: #request.session.set_expiry(60) login(request, user) return JsonResponse({'message': 'success'}) else: return JsonResponse({"message": "inactive"}) else: return JsonResponse({"message": "error"}) signup def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): with transaction.atomic(): user = form.save(commit=False) user.is_active = False user.save() email_subject = 'Next Step: Activate Your Account' current_site = get_current_site(request) html_message = render_to_string('email/activate.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail = EmailMessage(email_subject, html_message, to=[form.cleaned_data.get('email')]) mail.content_subtype = "html" mail.send() return JsonResponse({'message': 'success'}) else: return JsonResponse({"message":form.errors}) -
defautl image in the field "ImageField" - Django
I try to put an image in an ImageField by default. But I can't solve the problem. My first attempt at solution was the following: from django.contrib.staticfiles import finders result = finders.find('img/image.png') models.ImageField(upload_to = user_model_custom_upload, default = result) My second attempt at solution was the following: from django.conf import settings import os DEFAULT_AVATAR_PATH = os.path.join(settings.MEDIA_ROOT, 'images/no-avatar.png') models.ImageField(upload_to = user_model_custom_upload, default = DEFAULT_AVATAR_PATH) neither solution worked But something curious happens with the second method, is that at the time that Django searches for the image, the image path for Django is as follows: Not Found: /media/home/lcteen/Documents/Programming/Frameworks/Django/ibme_project/media/images/no-avatar.png I don't know what is currently happening, it's like the structure of my directories is in the media folder or something ... but my media folder doesn't change at all. Any solution? -
HTML5 video elements loading time
I just want to figure out why my website is serving video files without coherence. First of all, I have created my website on ODROID-XU4 and OS is Ubuntu. Also, using Django and Apache2 as Framework Anyway, here is my problem. Videos won’t start instantly when I click the play button But, funny thing is some video files with big size do play instantly. For example, when I upload 3GB of video(mkv) and click play button, it plays instantly. However, another video file which is only 1.8GB uploaded won’t be played before fully loaded. Please, I am waiting for answer from someone who had similar experience -
How do I create a Django admin section for managing content on an individual page, such as homepage?
I would like to allow an admin to edit content sections on a homepage, about page, or contact page. A content section with a changeable background image, or a content section with changeable text. Is there a built-in Django package that addresses this? If not, would you recommend another third-party Django integration? I have searched using similar questions and have found that there are very few related answers. -
Display Foreign Key linked models in Django rest framework
I have three models I would like to display with in a treeview Event Market Runner Runner Runner Market Runner Runner Event can have multiple markets and markets can have multiple runners. I would like to be able to get fetch these models from one api request to view and delete old events if necessary. I've tried to create a combined serialiser but I get an error saying url name not valid with Runner. I don't think it's right referencing Runner model in the combined serializer as the Runner url has changed to the same name as combined. { "events": "http://localhost:8000/api/events/", "markets": "http://localhost:8000/api/markets/", "runners": "http://localhost:8000/api/combined/", "balance": "http://localhost:8000/api/balance/", "combined": "http://localhost:8000/api/combined/" } What is the best way to go about this? class Event(models.Model): sport_id = models.CharField(max_length=15) event_id = models.BigIntegerField(unique=True) event_name = models.CharField(max_length=200) start_time = models.DateTimeField(null=True) status = models.CharField(max_length=13) class Market(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) market_id = models.BigIntegerField(unique=True) market_name = models.CharField(max_length=35) status = models.CharField(max_length=10) volume = models.FloatField(null=True) class Runner(models.Model): event = models.ForeignKey(Event, null=True, default=None, on_delete=models.CASCADE) market = models.ForeignKey(Market, null=True, default=None, on_delete=models.CASCADE) runner_id = models.BigIntegerField(unique=True) name = models.CharField(max_length=500) back_odds = models.FloatField(null=True) lay_odds = models.FloatField(null=True) class CombinedSerializer(serializers.ModelSerializer): event = EventSerializer() market = MarketSerializer() class Meta: model = Runner fields = ('id','runner_name','runner_id', 'name', 'event' ,'market') class … -
Django serializer show all fields for retrieve but hide fields from list
I have a Product model which I'm using to retrieve all products and single products. I need to have all columns returned when I query a single record but only some columns returned when I query all. # models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.CharField(max_length=150, blank=True, null=True) image_2 = models.CharField(max_length=150, blank=True, null=True) thumbnail = models.CharField(max_length=150, blank=True, null=True) display = models.SmallIntegerField() class Meta: managed = False db_table = 'product' # serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('product_id', 'name', 'description', 'price', 'discounted_price', 'image', 'thumbnail') # products.py import logging from django.db.models import F from django.contrib.auth.models import AnonymousUser from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.filters import SearchFilter from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from api import errors from api.models import Category, Product, Review, ProductCategory from api.serializers import ProductSerializer, ReviewSerializer logger = logging.getLogger(__name__) class ProductSetPagination(PageNumberPagination): page_size = 20 page_query_description = 'Inform the page. Starting with 1. Default: 1' page_size_query_param = 'limit' page_size_query_description = 'Limit per page, Default: 20.' max_page_size = 200 class ProductViewSet(viewsets.ReadOnlyModelViewSet): """ list: Return a list of products retrieve: Return … -
Daphne NotImplementedError after upgrade to Python 3.8
We upgraded an existing project from Python 3.7.2 to Python 3.8 and now we are facing an issue when starting the server with python manage.py runserver. I tried reinstalling the venv, reinstalling Python, updating PIP, recloning the project, restarting the PC (..). Our requirements are as follows: Django channels channels_redis daphne This is the full error traceback after the runserver command: Traceback (most recent call last): File "MYAPPDATAPATH\appdata\local\programs\python\python38\Lib\threading.py", line 932, in _bootstrap_inner self.run() File "MYAPPDATAPATH\appdata\local\programs\python\python38\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "MYPROJECTPATH\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "MYPROJECTPATH\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "MYPROJECTPATH\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "MYPROJECTPATH\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "MYPROJECTPATH\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "MYPROJECTPATH\env\lib\importlib\__init__.py", line 127, in import_module 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 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "MYPROJECTPATH\env\lib\site-packages\channels\apps.py", line 6, … -
how can I avoid getting duplicates: account?
I am trying to install pip3 install django-allauth to prevent login before email confirmation , but at moment to setup settings.py. I got the following error, but I dont want to rename all the project name, because it gonna affect the complete project. is there a way to achieve this without too much changes? xxxxxx@xxxxxx:~/Documents/blackowl$ python3 manage.py makemigrations account 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 "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_com mand_line utility.execute() File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/xxxxxx/.local/lib/python3.6/site-packages/django/apps/registry.py", line 95, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth' , 'allauth.account' , 'allauth.socialaccount' , 'allauth.socialaccount.providers.github' , 'apps.website', 'apps.account' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blackowl.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) -
UnboundLocalError - local variable 'ret' referenced before assignment
I did a simple method to calculate the division between two values: def porc_pago_ct(self, *args, **kwargs): for contrato in self.contrato.all(): if contrato.nr_contrato != None: ret = (float(contrato.total_pago_brl)/float(self.valor_total_brl))*100 else: ret = 0 return ret Everything works well until I put this conditional statements. After this I tried many ways, but everytime I got: UnboundLocalError at /lista/2/ local variable 'ret' referenced before assignment What I`m missing here? -
Django database tables created under wrong schema
I created a Django application and connected it to SQL Server with a trusted connection. When I migrate, Django is creating a new schema name (trusted connection username) in the database and adding this on all tables as prefix. By my IT department convention, all tables should be created with the 'dbo' prefix. The most interesting part is: When I access the database from SQL management studio (also with trusted connection), and create a new database, I do not have this issue, it creates as 'dbo.table_name'. Does anybody knows how can I fix it? See below better example and some code. Summary: Django is creating: 'my_username.table_name' I need: 'dbo.table_name' My django settigs.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dabase_name', 'HOST': 'database_host', 'USER': '', 'OPTIONS': { 'driver': "ODBC Driver 17 for SQL Server", 'Trusted_Connection' : 'Yes', } } } One of my models (table) as example: class Sap_module(models.Model): sap_module = models.CharField(max_length=2, unique=True) available = models.BooleanField(default=True) def __str__(self): return self.sap_module -
Django cursor dictfetchall is not returning the dictionary correctly
I'm using the dictfetchall from the Django documentation in order to return a dictionary for use in AJAX GET. def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] In this function: def UserData(request): cursor = connection.cursor() cursor.execute("SELECT user_id, email FROM users_user LIMIT 2") row = dictfetchall(cursor) return HttpResponse(row) And supposedly it should be returning this: [{'user_id': 4, 'email': 'ewoif@rjhior.com'}, {'user_id': 25, 'email': 'efweew@ferfr.com'}] But it is returning this: {'user_id': 4, 'email': 'ewoif@rjhior.com'}{'user_id': 25, 'email': 'efweew@ferfr.com'} No [ ] and no comas , Why? -
Django `get_or_build` similar to `get_or_create`?
I'm curious if there's a way to do something conceptually like a "get_or_build" for an object, without saving it (yet), so you can reference itself to set a field before saving. Similar to Ruby's find_or_create_by or find_or_initialize_by with a block. For instance, given the following model: class User(models.Model): unique_id = models.UUIDField(default=uuid4) first_name = models.CharField() last_name = models.CharField() meta = models.CharField() and an example of creating a User user, created = User.objects.get_or_create(first_name="Jane", last_name="Doe") let's say I wanted to also set the meta column to whatever the default value for unique_id is in this situation, on initialization. I would have to do something like this, since it would be available when initializing the object: user = User.objects.filter(first_name="Jane", last_name="Doe") if not user: user = User(first_name="Jane", last_name="Doe") user.meta = user.unique_id user.save() is there anything like: user, built = User.objects.get_or_build(first_name="Jane", last_name="Doe") if built: user.meta = user.uuid user.save or a way to reference from within get_or_create: user = User.objects.get_or_create(first_name="Jane", last_name="Doe", meta=self.unique_id) -
Django join unmanaged tables
I have a four models which each contains their own data. The models are: Category (contains department_id foreign key) Department (contains data, no foreign key) ProductCategory (join table containing only product_id and category_id) Product (contains data with no foreign key) # models.py (excluded the rest for brevity) from django.db import models class Department(models.Model): department_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'department' class Category(models.Model): category_id = models.AutoField(primary_key=True) #department_id = models.IntegerField() department = models.ForeignKey(Department, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'category' class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.CharField(max_length=150, blank=True, null=True) image_2 = models.CharField(max_length=150, blank=True, null=True) thumbnail = models.CharField(max_length=150, blank=True, null=True) display = models.SmallIntegerField() class Meta: managed = False db_table = 'product' class ProductCategory(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: managed = False db_table = 'product_category' unique_together = (('product', 'category'),) From my endpoint, I need to get all products in a department and return the response in the following format: "rows": [ { "product_id": integer, "name": string, "description": string, "price": string, "discounted_price": … -
Why multiple ajax requests in each other do not execute?
I have multiple ajax functions inside each other, but only the first ajax request is executed and I do not know why! I have added some alert fields to see how far it gets. I am using django environment for this. So for example when the bidnow-BTN is clicked this jquery should execute, but for some reason the after the first ajax request the page actually refreshes and adds something like /?bidPrice=100001 to the end of the url of the page. This should not happen. $("#bidnow-BTN").click(function(){ var varurl = document.URL var itemId = varurl.split(/\//)[4] $.ajax({ url : "{% url 'User ID' %} ", method : "GET", success : function (data) { var varurl = document.URL var itemId = varurl.split(/\//)[4] var username = data.username alert("Got here: " + username) $.ajax({ url : "{% url 'Bidding ID' %} ", method : "GET", success : function (data) { alert("Does NOT reach this point") for(var i = 0;i<data.users.length;i++){ if(data.users[i].username==username) { var id = data.users[i].id } else{ } } $.ajax({ // kinda checked url : "{% url 'List Items' %} ", method : "GET", success : function (data) { var varurl = document.URL var itemId = varurl.split(/\//)[4] for (var i = 0 ; i<data.items.length;i++){ if(itemId … -
Calculating fields with filters in Django
I am extremely new to Django and kinda new to python and programming in general, so i may be asking a dumb question. I am trying to track medications in our inventory at work. Here is my model for the inventory in our safe class Safe(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date_created = models.DateTimeField(auto_now=True) drug_name = models.ForeignKey('components.Drug', related_name='drug_remove', on_delete=models.PROTECT, default=0) amount_removed = models.IntegerField(blank=True, null=True) amount_added = models.IntegerField(blank=True, null=True) incident_number = models.CharField(max_length=20, default=0, blank=True) patient_name = models.CharField(max_length=20, default=0, blank=True) medic_unit = models.ForeignKey('components.MedicUnit', related_name='medic_unit', on_delete=models.PROTECT, blank=True) free_text = models.CharField(max_length=1000, default=0, blank =True) drug_total = computed_property.ComputedIntegerField(compute_from='add_drug') I would like to store the medication total for each drug in the database. I understand from researching this that storing totals isn't best practice in most cases but I believe this is one exception. Obviously the calculated integer field isn't the answer, but none of my research has gotten me any closer to the answer. My guess is that I first need to filter by 'drug_name' and then calculate the added or subtracted drugs from the previous total in a function within my model. Thanks ahead of time for any help. -
Changing model field value to True after expiration time
I am in the process of creating a simple car rental project in Django. I have a view in which the user must enter the value for how many days he wants to rent a car and press the "Rent" button. In this situation the "is_car_available" field of the "Car" model gets False value and it is not possible to rent. @login_required def rent(request, pk): car_to_rent = Car.objects.get(pk=pk) if request.method == 'POST': form = RentingForm(request.POST) if form.is_valid(): days = form.cleaned_data['days'] total_price = car_to_rent.car_price * days reservation = Reservation.objects.create(how_many_days=days, car=car_to_rent, booker=request.user, total_price=total_price) car_to_rent.is_car_availible = False car_to_rent.save() content_for_frontend = { 'car_to_rent': car_to_rent, 'form': form, } return render(request, 'rental/rent.html', content_for_frontend) else: return HttpResponseRedirect('/') The Reservation model has the "expiration_date" method, which is calculated after adding the rental date to the number of days. I would like to see "is_car_available" change to True at the end of the rental. Any ideas how to solve it? -
how can I prevent users login before email confirmation?
I am new in django , and I am trying to configure login based on email confirmation, but however when I use my signup , and I tried to login , then I found a issue that I can login without email confirmation , how can I fix this ? I also modify the models to login with email instead of username. I want to prevent users login before email confirmation . my settings looks like this , and email confirmation uses TLS LOGIN_REDIRECT_URL = '/account/profile' LOGOUT_REDIRECT_URL = '/' DEFAULT_EMAIL_FROM = EMAIL_HOST_USER models.py class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have … -
PDF generation not working after upgrading from Django 1.8 to 2.2
After upgrading Django from 1.8 to 2.2, trying to generate a pdf now sends me to a page that says This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access denied</Message> </Error> Log files show that it requests information from SQL, but other than that no messages are generated at all. My config/base.py file sets the url like this: REPORTS_PATH = '/company/{}/reports/' The code that produces the document is this: from celery import shared_task import os import tempfile import pytz import json import subprocess import datetime from django.conf import settings @shared_task(default_retry_delay=1000, max_retries=10) def create_required_document(company_id, incident_id, document_id): import django django.setup() from core.utils import S3Uploader, download_file_from_s3 from .models import Incident, RequiredDocumentType, CompanyRequiredDocumentType, RequiredDocumentSubmissionEvent, IncidentSentToClinicEvent from company.models import Company company = Company.objects.get(id=company_id) incident = Incident.objects.get(id=incident_id) document = RequiredDocumentSubmissionEvent.objects.get(id=document_id) required_doc_type = document.type company_required_doc_type = \ CompanyRequiredDocumentType.objects.filter(company=company, report_type=required_doc_type)[0] with tempfile.NamedTemporaryFile( mode='w') as config_file, tempfile.NamedTemporaryFile() as input_text_file, tempfile.NamedTemporaryFile() as output_file: template_text = company_required_doc_type.template_text try: input_text_file.write(bytes(template_text, 'UTF-8')) input_text_file.seek(0) except Exception as e: raise e if document.signature_url is not None: signature_file_name = download_file_from_s3(url=document.signature_url) params['signatureFilePath'] = signature_file_name try: json.dump(params, config_file, indent=4, sort_keys=True) config_file.seek(0) except Exception as e: raise e cmd = 'java -jar /home/ec2-user/wim/jPDF/FormTextToPDF.jar {}'.format(config_file.name) process … -
How to insert an image or video in html?
I have a django page that shows me a video loaded from a directory. I have a form with a drop-down list: <form name="formulario" enctype="multipart/form-data" method="POST" action="" name="formulario"> {% csrf_token %} {{ form.as_p }} <select name="type" id="type"> <option selected>Select the type of file</option> <option>Video</option> <option>Picture</option> <option>Gif</option> </select> <br><br> <input type="submit" class="btn btn-success" value="Upload"/> <a href="{% url 'fileupload:delete' %}" onclick="confirm('Are you sure you want to delete the files?')" class="btn btn-success">Delete Files</a> What I intend to do is that if the drop-down list selects video, I will insert a video and if I select a picture, I will insert an image. For example: {% if valor == video %} <video src='{{videofile.videofile.url}}' width="640" height="480" controls autoplay></video> {% endif %} {% if valor == picture %} <img src='{{videofile.videofile.url}}' width="640" height="480" controls autoplay></video> {% endif %} In the project I have a static folder where the files are stored, either images or videos, so the user searches for the image or video, this is saved in the folder and is displayed on the page. How could I do this? Regards.