Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ideas on how to build a function in python django for cellulating hours interval
I am Total beginner starting a project in Django a payroll calculator app, in it my user has a workhours with dates form. the function required should calculate(dates, in hour, out hour) and output the value to another(total hours) field. the restrictions are: value must be an integer value can be crossday meaning: giving a worker crossday shift 07.01.2021,08.01.2021/dates, 22:00:00pm/hour in, 06:00:00am/hour out function must work with Django .models / .datetime as far as i got 'def HoursTotalConf(in_time, out_time): start_dt = dt.datetime.strptime(in_time, "%H:%M:%S") end_dt = dt.datetime.strptime(out_time, "%H:%M:%S") return relativedelta(end_dt, start_dt) ' -
./manage.py runserver in MACBOOK M1 throws 'illegal hardware instruction ./manage.py runserver'
runnung server: ./manage.py runserver /Users/ashwin/dmango_entrayn/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) /Users/ashwin/dmango_entrayn/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) Performing system checks... System check identified no issues (0 silenced). zsh: illegal hardware instruction ./manage.py runserver requirements.txt: aenum==1.4.5 alabaster==0.7.10 amqp==2.3.2 # via kombu appnope==0.1.0 asn1crypto==0.24.0 # via cryptography authy==2.2.0 babel==2.5.0 backports-abc==0.5 bcrypt==3.1.6 # via paramiko beautifulsoup4==4.6.3 billiard==3.5.0.4 # via celery bleach==2.0.0 boto3==1.6.3 botocore==1.9.3 bs4==0.0.1 cachecontrol==0.12.5 # via firebase-admin cached-property==1.4.0 cachetools==2.1.0 # via google-auth celery==4.1.1 certifi==2018.1.18 cffi==1.12.3 # via bcrypt, cryptography, pynacl chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 coverage==4.5.1 # cryptography==2.6.1 # via paramiko decorator==4.1.2 django-cors-headers==2.2.0 django-extensions==2.0.0 django-filter==2.0.0 django-health-check==3.10.1 django-polymorphic==2.0.2 django-rest-polymorphic==0.1.8 django-rest-swagger==2.1.2 django-s3-storage==0.12.4 django-storages==1.6.6 django-treebeard==4.3 django-url-filter==0.3.5 django==2.0.2 djangorestframework-bulk==0.2.1 djangorestframework-simplejwt==3.2.3 djangorestframework==3.7.7 docutils==0.14 drf-dynamic-fields==0.3.1 dry-rest-permissions==0.1.10 entrypoints==0.2.3 enum-compat==0.0.2 fabric3==1.14.post1 factory-boy==2.11.1 faker==0.9.0 # via factory-boy firebase-admin==2.11.0 flake8==3.5.0 geoip2==2.9.0 google-api-core[grpc]==1.2.1 # via google-cloud-core, google-cloud-firestore, google-cloud-storage google-api-python-client==1.7.4 google-auth-httplib2==0.0.3 # via google-api-python-client google-auth-oauthlib==0.2.0 google-auth==1.5.1 # via firebase-admin, google-api-core, google-api-python-client, google-auth-httplib2, google-auth-oauthlib google-cloud-core==0.28.1 # via google-cloud-firestore, google-cloud-storage google-cloud-firestore==0.29.0 # via firebase-admin google-cloud-storage==1.10.0 # via firebase-admin google-resumable-media==0.3.1 # via … -
Place a text on top of an image
I want to place an image in the center of my white page and add a title over it (the title would be larger than the image || also the title center must be the image center). The problem is that the title won't go on top of the image. I use Django and bootstrap ^^ Here is the code : HTML : <div class="col-md-7 white nopadding text-center"> <div class="brand"> Brand </div> <div class="heading"> <img src="{% static '/eyemeet/hero.jpg' %}" class="hero"> <div class="title ctr">Title</div> </div> CSS: .hero { width: 65%; height: auto; } .title { position: absolute; background-color: cadetblue; top: 50%; left: 50%; } .ctr { position: absolute; transform: translate(-50%, -50%); } What happens currently : -
Django making 2 request instead of 1
Initial I thought 2 django process was started. So i have added a print statement in the settings.py. But it was printing only one time. My problem is, whenever I am making a request, I can see two entries in the django console. Entires in Database is added twice. (Often getting UNIQUE constrain error in db because of double request). I have added print('hi'). It is printing only one time. Also i tried --noreload. No luck. -
Django Can i fill automatically list_display
I'm trying fill automatically my list_display on my admin Django, apparently the code works correctly, but it doesn't show nothing. This is my code Model class Pacient(models.Model): name = models.CharField( max_length=50 ) last_name = models.CharField( max_length=50 ) id_identification = models.IntegerField() age= models.PositiveSmallIntegerField() gender = models.ForeignKey( Gender, on_delete=models.CASCADE ) blood_type = models.ForeignKey( BloodType, on_delete=models.CASCADE ) def __str__(self): return self.name Admin.py from django.contrib import admin from .models import Pacient class PacientAdmin(admin.ModelAdmin): list_display=() x = Pacient.objects.values() def some(self): for k in self.x: k = k.keys() self.list_display=(tuple(k)) print (self.list_display) return self.list_display admin.site.register(Pacient,PacientAdmin) -
how to send "order is confirmed emails to customer" in django
I am trying to make an e-commerce website in Django and react. but I am not able to find a way for this scenario. whenever a user purchases something a confirmation email should go to the user and one to the admin that a user buy something. can we do this just by code or we have to use something like Mailchimp?i want to do it by writing code. -
Django dev server view handler very slow, but only when logged in
My django dev server view handler takes over 1 minute. I've narrowed it down to when the request.user is logged in. E.g. the below handler is <1 second when logged out, but >1 second when logged in (i.e. request.user.is_authenticated() == True). def test_handler(request): return HttpResponse("OK") Similarly, this handler is very fast def test_handler(request): logout(request) return HttpResponse("OK") -
Reason for receiving swapStyle is not defined
I am new to Javascript, I am currently learning to debug errors that I am receiving in the Console. In my project I am adding a theme choosing option for each user logging into the website. I have created an app in my Django Project and everything is as covered in the tutorial I am following except that in the console I am receving errors: Uncaught ReferenceError: swapStyle is not defined at HTMLButtonElement.onclick (VM58:202) swapStyle('css/app-light.css') To start here is the base.html <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyle('css/app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyle('css/app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile + … -
why am i getting Incorrect type. Expected pk value, received str (many to many field)
models.py import uuid import os from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from django.conf import settings def recipe_image_file_path(instance, filename): """Generate file path for new recipe image""" ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/recipe/', filename) class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that suppors using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' class Tag(models.Model): """Tag to be used for a recipe""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name class Ingredient(models.Model): """Ingredient to be used in a recipe""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.name class Recipe(models.Model): """Recipe object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=255) time_minutes = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) link = models.CharField(max_length=255, blank=True) ingredients = models.ManyToManyField('Ingredient') tags = models.ManyToManyField('Tag') … -
Multiple types of the same type of relationship in django
I have a requirement for models with a pk relationship where one of the models can be multiple types of a similar object. for instance I have three different ways in which a requisition can be made and these three ways have distinct attributes which are different from each other. How can I make the model so as to connect the three different requisition types with a single order model? Any help is much appreciated. Thank you very much. -
How to use Spyne+Django with parameters on url?
on django urls.py url(r'soap/<str:user_id>/', DjangoView.as_view(application=provider)), on views.py @ rpc(_returns=AnyDict) def super_test_dict(self, one, two): user_id = 1 #here need to receive the user_id res = {"user_id":user_id} return res on tests.py self.soap_client = DjangoTestClient( f'/soap/{org.str:user_id}/', provider) res = self.soap_client.service.super_test_dict() The problem is when i send parameter str:user_id dont work, but if not sent anything work fine, im need to send same parameters as request but also need to send str:user_id on url. -
Django admin stuck on loading page after correct credentials
I recently started facing an issue which when I try to log in into the admin interface, after putting the correct credentials, it gets stuck on the login page, and does not redirect to the admin interface, I was wondering what has suddenly cause this issue? When I put the wrong credentials, it does redirect me to the admin and shows an error message, however, then I put the correct credentials, it gets stuck on the page. I am using Django version 3 and python version 3.8 and I didn't have this issue before, until recently it happened. -
A User can be a Teacher or a Admin, or a Parent, or a Student. How to achieve this using Django models?
I have a table called User. And there are other tables Admin, Teacher, Parent and Student. Now, a User can be a Teacher or a Admin, or a Parent, or a Student. How to implement this using Django models? -
How could I access multidimensional dictionary in Django template?
Let's suppose I have a dict with data like this: questions = {5: [<InterestAnswer: Cat>, <InterestAnswer: Dog>, <InterestAnswer: Parrot>], 6: [<InterestAnswer: Cinema>, <InterestAnswer: Netflix>]} How could I print out data using a for loop in a template? I thought something like this would work but it didn't. {% for answer in questions %} <input type="checkbox"> <div class="answer"> {{answer.answer}} </div> {% endfor %} -
How to count new data before executing a function again
I have this function that do automatic execution of send_sms function when certain conditions are met. That it will execute if the count for specific levels are detected. I'm using celery to automatically execute it when needed. But my problem now is like this. if the responses.count() >= 50: then it will execute send_sms function. but when it reaches 51 after the first execution it is still executing and it must not. I want it to recount again another NEW 50 for another execution. How can I do it? Thanks! def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=3), ) if responses.count() >= 50: send_sms(request) return HttpResponse(200) -
Auth0 on Heroku: Infinite redirect loop on login
I am attempting to set up a django app on heroku that uses auth0. Previously I have not had an issue with any of these things and it all worked fine locally. However they seem to have come together to make a perfect storm of an issue. Upon submitting a login with auth0 using the google oauth, the page redirects back to the login. This is an infinite loop. Previously when it was remembering the user it would do this infinitely. If it is not remembering it will simply take you back to the initial login page at domain.com/login/auth0. Here is how the server handles it locally, and here is the loop on heroku. Everything on the django end is boilerplate, and as mentioned, works fine locally. The auth0 redirects are set up properly, as is the google-oauth setup with auth0. Independently all these things work fine, but for some reason they are breaking down on heroku. It is worth mentioning that when the user was being remembered and the infinite loop cycled through, eventually it hit an error page that mentioned this may be caused by disabling or refusing cookies. It is also worth noting that the auth0 site … -
Get JS notification when django form fails client-side validation
I have a django template showing a form. I added a "loading" image when hitting the submit: <input type="submit" value="Search" name="search" onclick="show_loading();"/> In case of a validation error (like not choosing any option in a multi-choice field), since the form does client-side validations, I see the loading AND the error tooltip, but the page is disabled (that's what my show_loading function does). How can I get a feedback from the form that there is a validation error, so I can remove the loading image? -
How to load a file from code instead of form field
As I don't have much experience with python and django I would like to ask about loading a file into a variable from code. Here is my scenario: User sends the data to my django backend with POST with some parameters like this: { templateName: exampleTemplate.html filename: instanceFileFromTemplate.pdf } The purpose of that request is to select appropiate html template and generate output pdf file with some specific data inside. So My Django backend function selects desired exampleTemplate.html template and with weasyprint generates a instanceFileFromTemplate.pdf file. Then I should prepare (programatically) a POST body/Form, where I will attach my newly generated file and save an instance into my Model { fileName: instanceFileFromTemplate.pdf, file: -here should be a file-, creationDate: 2020-01-07 } How to do load my file into a file variable ? When I print an example body, prepared in a POSTMAN it looks like this: {'filename': ['instanceFileFromTemplate.pdf'], 'creationDate': ['2020-01-07'], file': [<InMemoryUploadedFile: instanceFileFromTemplate.pdf (application/pdf)>]}> So basically I know i need to prepare Dict variable, but how to load into my Dist a file ? -
Can't save new objects in Django full-text search with PostgreSQL
I'm following this post on how to add full-text functionality to my Django app. I have the following model: class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) class Author(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) name = models.CharField(max_length = 250) alternative_names = ArrayField(models.CharField(max_length = 250),blank=True,null=True) name_norm = models.CharField(max_length = 250,blank=True,null = True) slug = models.CharField(max_length = 250,unique = True) photo = models.ImageField(upload_to = 'imgs/users/%Y/%m/%d',blank = True) search_vector = SearchVectorField(null=True) def save(self, *args, **kwargs): self.search_vector = (SearchVector('name', weight='A') ) super().save(*args, **kwargs)`enter code here` And when I try to save a new author with save: autor = Author(user = utilizador,name = author_name,alternative_names = alternative_names,name_norm = name_norm,slug = slug) autor.save() I get the error: Traceback (most recent call last): File "populate_v2.py", line 140, in <module> autor.save() File "/home/mwon/NewArquivoOpiniao/webapp/colunadeopiniao/accounts/models.py", line 57, in save super().save(*args, **kwargs) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 748, in save self.save_base(using=using, force_insert=force_insert, File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 785, in save_base updated = self._save_table( File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 890, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 927, in _do_insert return manager._insert( File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1393, in execute_sql for sql, params in self.as_sql(): File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1336, … -
How to order queryset by using SerializerMethodField?
How to order queryset by using SerializerMethodField? i need to sort by using serializermethodfields such as submissions, effectiveness. #models.py class Vendor(CreateModificationDateMixin): user = models.OneToOneField(User_Profile, on_delete=models.CASCADE, primary_key=True) job_title = models.CharField(max_length=100, default=None) phone_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") is_prefered = models.BooleanField(default=False, editable=False, blank=True) number_of_employees = models.CharField(max_length=255, blank=True) company_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="company number must be entered in the format: '+999999999'. Up to 15 digits allowed.") company_phone_number = models.CharField(validators=[company_regex], max_length=17, blank=True, null=True) fax_regex = RegexValidator(regex=r'^+?1?\d{9,15}$', message="fax number must be entered in the format: '+999999999'. Up to 15 digits allowed.") fax_number = models.CharField(validators=[fax_regex], max_length=17, blank=True, null=True) def __str__(self): return self.user.username class Meta: verbose_name_plural = "vendors" db_table = 'vendor' #serializers class AllVendors(DjongoModelSerializer): user = UserProfileSerilaizer(required=True) is_prefered = SerializerMethodField() submissions = SerializerMethodField(read_only=True) effectiveness = SerializerMethodField(read_only=True) hotlist_count = SerializerMethodField(read_only=True) lastupdated_at = SerializerMethodField(read_only=True) class Meta: model = Vendor fields = '__all__' depth = 1 def get_lastupdated_at(self,obj): candidate = list(CandidateList.objects.filter(vendor_id=obj.user_id).order_by('-modification').values_list('modification',flat=True)) if candidate: return candidate[0] else: return '' def get_hotlist_count(self,instance): return CandidateList.objects.filter(vendor_id=instance.user.id).filter(candidate_status='Candidate Available').count() def get_is_prefered(self, obj): try: client_id = self.context['request'].user.id is_prefered = PreferredVendors.objects.filter(user_id=client_id).filter(vendor_id=obj.user.id).values('is_prefered') if len(is_prefered)>0: return is_prefered else: return [{'is_prefered':False}] except: return [{'is_prefered':False}] def get_submissions(self,obj): return SubmittedCandidate.objects.filter(vendor=obj.user.id).count() def get_effectiveness(self,obj): confirm_candidates = SubmittedCandidate.objects.filter(vendor=obj.user.id).filter(interview_status='Selected Final').count() total_submissions = SubmittedCandidate.objects.filter(vendor=obj.user.id).count() onboarding = SubmittedCandidate.objects.filter(vendor=obj.user.id).filter(interview_status='OnBoarding').count() starts … -
How to make Searching functionality for whole database in django/DRF using single API?
How to make Search in whole database using django/DRF single API? For example we can do this for single model search using django/DRF API:- `class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['category', 'in_stock']` You can see the whole example in this:- https://www.django-rest-framework.org/api-guide/filtering/ Thank you in ADVANCE. -
Django Rest Framework: Connection not showing queries from custom permission class
I am using Django's Rest Framework, and am trying to assert the number of queries for an endpoint in a test case. I am using django.db.connection.queries to get the queries, but it doesn't include the queries from the permission_classes. I am using a custom permission class that implements has_object_permission. Is this expected behavior? Is the only way around this to test the has_object_permission function directly? -
Force maximum number of records with attribute in Django
In Django, is there a "Djangonic" way to ensure a model doesn't have more than n records with a certain value for an attribute? For instance, how to ensure on the example below that no more of two records for MyModel have my_attribute set to True? class MyModel(models.Model): my_attribute= models.BooleanField(default=False) -
Django Admin method returns multiple instances instead of one
I have a very simple model: class Product(models.Model): name = models.CharField("name", max_length = 128) def __str__(self): return self.name class Store(models.Model): store_id = models.PositiveIntegerField(unique = True) product = models.ForeignKey(Product, on_delete = models.CASCADE, null = True, blank = True) which is displayed in the admin by: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name", "get_stores"] def get_stores(self, obj): s = [s.store_id for s in Store.objects.filter(product = obj)] if s: print("store/product:", s, obj) return s and leads to the error, that I see every product in the list of products as often as I have stores for it. Output: store/product: [457, 1179383, 1179384] Cake store/product: [457, 1179383, 1179384] Cake store/product: [457, 1179383, 1179384] Cake (exactly the same in the admin product list). How can I avoid multiple appearances? -
Default User Model OneToOneField Attribute Error
I am trying to connect the default Django User model with another one I made to store extra info. but even after following all the proper steps, I am getting an error. I have spent way to much time trying to figure it out, hopefully, you guys can figure it out and help me. (you probably will you all are much smarter than me) here is the import command : from django.contrib.auth.models import User here is the integration with the premade model: class User_Info(models.Model): user = models.OneToOneField(User,null = True, on_delete = models.CASCADE) here is the view I am using : def userPage(request): _user_ = request.user.User_Info.all() trades = request.user.User_Info.trade_set.all() total_trades = trades.count() context = {"_user_" : _user_,"trades" : trades, "total_trades" : total_trades} return render(request, "accounts/user.html", context) This is the error I am getting: AttributeError at /user/ 'User' object has no attribute 'User_Info' Request Method:GET Request URL:http://127.0.0.1:8000/user/ Django Version:3.1.2Exception Type:AttributeError Exception Value:'User' object has no attribute 'User_Info' if you need any more information let me know I will be more than happy to help! Thank you for your time! :)