Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django have the ability to login with phone or email
I want to create a django custom user model such that i can have my users login with either phone or email. This is my proposed solution class ExtendedUser(AbstractBaseUser, PermissionsMixin): phonenumber = PhoneNumberField(unique=True, null=True ..) email = EmailField(unique=True, null=True ..) ... USERNAME_FIELD = 'pk' so now while login, i can do something like this if cleaned_data['phonenumber']: u = User.objects.get(phonenumber=cleaned_data['phonenumber']) authenticate(username=u.pk, password=cleaned_data['password']) ... elif cleaned_data['email']: ... I am not sure whether it is possible to put USERNAME_FIELD as pk. We can easily put a UUIDField if that's not possible. Is the proposed solution fine? -
Spanning multiple relations with conditional expresessions in Django 2.0
Consider the following models (in pseudo code) in Django 2.0: class m_Discussion(models.Model): ... class m_Comment(models.Model): fk_discussion = models.ForeignKey('m_Discussion', related_name='comments') class m_Tag(models.Model): fk_comment = models.ForeignKey('m_Comment', related_name='tags') I would like to get the all Discussions which have at least 50% (arbitrary) comments which are tagged (i.e. have at least one tag) My current solution looks like this: m_Discussion.objects.annotate( ratio_tagged_comments=Cast( Sum( Case( When( comments__tags__isnull=False, then=1.0 ), default=0.0, output_field=FloatField() ) ) / F('count_comments'), output_field=FloatField() ) ).filter( ratio_tagged_comments__gte=0.5, ) I'm worried about the line comments__tags__isnull=False. Is this how it works? I found nothing about using conditional expressions while spanning multiple relations. The SQL looks approximately like this: SELECT "corpus_m_discussion"."id_discussion", "corpus_m_discussion"."title" FROM "corpus_m_discussion" LEFT OUTER JOIN "corpus_m_comment" ON ( "corpus_m_discussion"."id" = "corpus_m_comment"."fk_discussion_id" ) LEFT OUTER JOIN "corpus_m_tag" ON ( "corpus_m_comment"."id" = "corpus_m_tag"."fk_comment_id" ) GROUP BY "corpus_m_discussion"."id" HAVING ( COUNT("corpus_m_comment"."id") >= 5 AND ( SUM( CASE WHEN ("corpus_m_tag"."id" IS NOT NULL) THEN 1.0 ELSE 0.0 END ) / ( COUNT("corpus_m_comment"."id") -1 ) ):: double precision >= 0.7 ) Which row in the 'corpus_m_tag' table is compared here: CASE WHEN ("corpus_m_tag"."id" IS NOT NULL) THEN 1.0 ELSE 0.0 END. To me this seems odd but I'm not that experienced with 'having', 'count', 'case', ... clauses in SQL. Any … -
There are no csrf protections for searchfield in Django Admin by default
Our company has some strict rules about security policies. They are doing pentesting for all apps with the vulnerability scanners like Netsparker, Acunetix etc... Django adds csrf protection for all forms except the search form. It considered by the security team as a vulnerability. Is there a way to add a hidden field or activating csrf protection for the search form? -
How to handle calculated models in django?
From a model called Suggestion, I need to calculate another model that is called Task. Task objects doesn't need to store anything in the database since it is totally calculated using Suggestion fields. An exemple would be a task of approving a suggestion using fields : approver state approving_deadline Is their a standard way in django to handle this kind of models that doesn't need to store any information but are fully calculated using other models ? -
How can i approve users profile The right way
Basically i want my app users to signup using "User model" basic fields, then he/she can complete his profile info , and after they will be satisfied with their info because i want to ask for some docs to be uploaded,so then at any time they can submit their profiles for approval . and so far i tried the following : models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') approved = models.BooleanField(default=False) # Attributes @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile_for_new_user(sender, created, instance, **kwargs): if created: profile = UserProfile(user=instance, date_joined=datetime.date.today()) profile.save() PROFILE_STATUS = ( (0, 'Pending'), (1, 'Accepted'), (2, 'Rejected') ) class ProfileApproval(models.Model): profile_user = models.ForeignKey(User) approved_by = models.ForeignKey(User, related_name="approver") status = models.IntegerField(default=0, choices=PROFILE_STATUS) uuid = models.CharField(max_length=32, default='', blank=True) def __str__(self): return str(self.from_user) def save(self, *args, **kwargs): if not self.pk: self.uuid = uuid.uuid4().hex super(ProfileApproval, self).save(*args, **kwargs) @receiver(post_save, sender=ProfileApproval) def approve_profile(sender, instance, created, **kwargs): if not created: if instance.status ==1: # i am not sure about the following line instance.profile_user.approved = True views.py def makeApprovalModelInstance(request, pk): if pk: # here i want to query the user using the pk from the based through the template and eventually get his profile, but i know i missed . user = User.objects.get(pk=pk) ProfileApproval.objects.create( from_user=user, approved_by=request.user) return HttpResponseRedirect('home') # … -
Error "Reverse for 'django.contrib.auth.views.login' not found"
I am getting the below error message and I couldn't see a way to fix this stuff. Any help would be appreciated. NoReverseMatch at /login/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/login/?next=/ Django Version: 2.0.1 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\gokul\Desktop\TESTING\data\Scripts\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\gokul\\Desktop\\TESTING\\data\\tagent', 'C:\\Users\\gokul\\Desktop\\TESTING\\data\\Scripts\\python35.zip', 'C:\\Users\\gokul\\Desktop\\TESTING\\data\\DLLs', 'C:\\Users\\gokul\\Desktop\\TESTING\\data\\lib', 'C:\\Users\\gokul\\Desktop\\TESTING\\data\\Scripts', 'c:\\program files\\python35\\Lib', 'c:\\program files\\python35\\DLLs', 'C:\\Users\\gokul\\Desktop\\TESTING\\data', 'C:\\Users\\gokul\\Desktop\\TESTING\\data\\lib\\site-packages'] > python manage.py runserver Performing system checks... System check identified no issues (0 silenced). January 17, 2018 - 17:21:56 Django version 2.0.1, using settings 'tagent.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [17/Jan/2018 17:22:03] "GET / HTTP/1.1" 302 0 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\core\handlers\base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response response = response.render() File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\template\response.py", line 83, in rendered_content content = template.render(context, self._request) File "C:\Users\gokul\Desktop\TESTING\data\lib\site-packages\django\template\backends\django.py", line 61, in render return … -
Django : cannot access to annotation after values()
I a Django (1.11) project with a ReadingSession model as follows: class ReadingSession(.Model): user = models.ForeignKey(User) started_at = models.DateTimeField() ended_at = models.DateTimeField() And I want to display the sum of the reading sessions durations for each of some given users, in one database request. Among other attempts, I've tried : usernames = ['user1', 'user2',] q = ReadingSession.objects.filter(user__username__in=usernames)\ .annotate(duration=Func(F('ended_at'), F('started_at'), function='age'))\ .order_by().values('user') \ .annotate(total_duration=Sum('duration'))\ .values('user', 'total_duration') print q but it fails with : Traceback (most recent call last): File ".../misc_queries.py", line 74, in <module> test_query() File ".../misc_queries.py", line 51, in test_query .annotate(total_duration=Sum('duration')) File ".../lib/python2.7/site-packages/django/db/models/query.py", line 945, in annotate clone.query.add_annotation(annotation, alias, is_summary=False) File "/.../lib/python2.7/site-packages/django/db/models/sql/query.py", line 973, in add_annotation summarize=is_summary) File ".../lib/python2.7/site-packages/django/db/models/aggregates.py", line 19, in resolve_expression c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize) File ".../lib/python2.7/site-packages/django/db/models/expressions.py", line 548, in resolve_expression c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save) File "/.../lib/python2.7/site-packages/django/db/models/expressions.py", line 471, in resolve_expression return query.resolve_ref(self.name, allow_joins, reuse, summarize) File "..../local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1472, in resolve_ref return self.annotation_select[name] KeyError: 'duration' Which makes sense, as the "values('user')" statement filtered the fields returned by the 'filter()' statement. But on the other side, if I add 'duration' in the first 'values()' statement, the results are not groupped by user anymore. Do you see what I'm doing wrong here or … -
Convert raw SQL query to Django ORM with multiple joins
I have this raw query which I need to rewrite in Django's ORM: SELECT count(u.username) as user_count, l.id as level_id, l.name as level_name FROM users u JOIN user_levels ul ON ul.username = u.username JOIN sub_levels sl ON sl.id = ul.current_sub_level_id JOIN levels l ON l.id = sl.level_id WHERE u.created_at::DATE >= '2018-01-01' AND u.created_at::DATE <= '2018-01-17' AND u.type = 'u' GROUP BY l.id, l.name So far I have been able to write it in this way: Users.objects.select_related('user_levels', 'sub_levels', 'levels') .filter(created_at__date__gte='2018-01-01', created_at__date__lte='2018-01-17', type='u') .values('userlevel__current_sub_level_id__level_id', 'userlevel__current_sub_level_id__level__name') .annotate(user_count=Count('username')) The output has "userlevel__current_sub_level_id__level_id" and "userlevel__current_sub_level_id__level__name" columns. I need them aliased as "level_id" and "level_name". How can I do that? -
Django database ManyToManyField
Hello I'm starting with Django, I created simple database class Voter(models.Model): STATUS_INACTIVE = 0 STATUS_ACTIVE = 1 STATUS_DELETED = 2 Forename = models.CharField(max_length=50) Name = models.CharField(max_length=50) Degree = models.CharField(max_length=50, blank=True) Active = models.BooleanField(default=0) StatusChoices = ( (STATUS_INACTIVE, 'Inactive'), (STATUS_ACTIVE, 'Active'), (STATUS_DELETED, 'Deleted'), ) Status = models.IntegerField(choices=StatusChoices, default=STATUS_INACTIVE) ControllerId = models.OneToOneField( Controller, on_delete=models.CASCADE, blank=True ) def __str__(self): return "%s %s" % (self.Forename, self.Name) class AttendanceList(models.Model): Date = models.DateTimeField(null=True) Council = models.CharField(max_length=50) Attandence = models.ManyToManyField( Voter, through='Attendance', ) class Attendance(models.Model): ABSENT = 0 PRESENT = 1 Voter = models.ForeignKey(Voter, on_delete=models.CASCADE, db_index=True) AttendanceList = models.ForeignKey(AttendanceList, on_delete=models.CASCADE) Present = models.BooleanField(default=ABSENT) When I'm trying to get access to Attendance table trough admin site I'm getting exception: (1054, "Unknown column 'polls_attendance.Voter_id' in 'field list'") -
Dynamically create viewflow flow using xml configuration
Is it possible to create viewflow flow by parsing xml? I am with the case of creating the flow by parsing xml so any person with no knowledge of python can can write xml and flow is created on basis on xml. -
Django form twice clicking SAVE got twice identical entries
I have normal Django form. As I had a short server delay after pressing the "save" button of my form, I just clicked once more and Oops I have the entries twice in the database. So my question: I am wondering whether there exists an mechanism which by pressing the save button several times prevents that identical entries are created? Is a possible solution really hashing the entries like in this post: prevent a form to be submitted multiple times - django Thanks for your help. -
Disable uniqueness/fk constraints before django's loaddata for Postgresql 9.6/10
I am trying to migrate data from one db to another. Previous was on peewee ORM and new one on Django. I've ported schema code and successfully run dumpdata. Now I need to run loaddata to restore from it. Problem is that DB is pretty bad, there's a lot of uniqueness/fk violationss there for legacy reasons, and I don't really want to clean it before restore. I would like to be able to just disable all checks for some time and upload as is. I tried ALTER TABLE table_name DISABLE TRIGGER ALL but from the info on the Internet I think it only disables FK checks. Unfortunately I keep receiving IntegrityError's with uniqueness violations. How can I disable uniqueness check temporarily on Postgres? Or all at once, if possible. Thanks. Postgres 9.6/10, Django 1.11.9. -
Validating email in django query
How can I validate a email field and update another field based on that in a single 'django' query. Can I do it with Regex. -
Can we use algolia search with patameter, using instance.js
Can we use algolia search with parameters, using instance.js { "institute_type": "Private", "type": "Coaching", "approved_by": "NIIT", "name": "Supply Chain Management Training Program", "college_facilities": "Guided Assignments for hands-on learning", "established": "2018-01-15", "country": "India", "address": "Delhi", "course_": "", "slug": "supply-chain-management-training-program", "image": "images/supply-chain-520.jpg", "state": "Delhi", "cities": "New Delhi", "location_type": "Domestic", "objectID": "6" } search with "type": "Coaching", and "type": "College", -
Group By each date in Django 2
I have a model called Log which has a datetime field created_at. What I want to do is to calculate the number of Logs for each date. I tried to do this: from django.db.models.functions import TruncDate Log.objects.annotate(date=TruncDate('created_at')).values('date').annotate(c=Count('id')) This is giving me the following: {'date': datetime.date(2018, 1, 17), 'count': 1}, {'date': datetime.date(2018, 1, 17), 'count': 1}, {'date': datetime.date(2018, 1, 17), 'count': 2} That is, the date is not unique. The result I want would be this: {'date': datetime.date(2018, 1, 17), 'count': 4}, {'date': datetime.date(2018, 1, 18), 'count': 2} How could approach this problem? -
Django vs PyQt for developing a simple sqlite frontend
I have been using Python for a while as a scripting language, but I am looking to improve on my knowledge as I would like to write a program that I use to manage my productions (I am a filmmaker). The problem is, at the moment, I don't have enough time to devote to learning everything about Python, so I need to choose specifically what I want to pursue. Here is what I want the program to do: 1) Act as a database of the assets and scenes I am working on. 2) Manage my project directory enforcing naming conventions, creating folders based on the scene names and assets provided by the database. 3) Use sqlite for the database, as I would prefer to have the database as a file saved locally with each project, in case I want to move the project between computers. 4) Have a GUI, even a simple one, to make interaction with the program easier. Initially, I was looking into PyQt, but while searching around, I have seen someone suggesting a web interface instead (GUI interface for sqlite data entry in Python). The questions I have: 1) I know a web interface will work with … -
Reducing cost for searching in a SQL Database using Django query
I am making an app that will search for similar drugs using the logic and models that if a drug is in a particular set of classes then other drugs that are in those and only those classes only then it will return those drugs. Here is the relevant code and dummy data - views.py class GetSimilarDrugs(APIView): def get(self, request, format=None): #import pdb #pdb.set_trace() get_req = request.GET.get('drugid', '') simi_list = [] comp_class = DrugBankDrugEPClass.objects.filter(drug_bank_id = get_req).values_list('epc_id', flat=True).distinct() for drg_id in DrugBankDrugEPClass.objects.values_list('drug_bank_id', flat = True).distinct(): classtocomp = DrugBankDrugEPClass.objects.filter(drug_bank_id = str(drg_id)).values_list('epc_id', flat=True).distinct() complist = list(comp_class) tolist = list(classtocomp) if complist == tolist: simi_list.append(drg_id) return Response({'result':simi_list}) models.py class DrugBankDrugEPClass(models.Model): drug_bank = models.ForeignKey(DrugBankDrugs, on_delete=models.CASCADE) epc = models.ForeignKey(DrugBankEPClass, on_delete=models.CASCADE) Dummy SQL Data id | drug_bank_id | epc_id | +------+--------------+--------+ | 1 | DB12789 | 1 | | 2 | DB12788 | 2 | | 3 | DB00596 | 3 | | 4 | DB09161 | 4 | | 5 | DB01178 | 5 | | 6 | DB01177 | 6 | | 7 | DB01177 | 6 | | 8 | DB01174 | 7 | | 9 | DB01175 | 8 | | 10 | DB01172 | 9 | | 11 | DB01173 | 10 … -
Wagtail Embed objects get wrapped in the DIV having the inline style padding-bottom: 56.25%
Essentially given the following template: {% for slide in value.carousel %} <div> {% include_block slide.value %} </div> {% endfor %} Wagtail would render: <div> <div style="padding-bottom: 56.25%;" class="responsive-object"> <iframe>....</iframe> </div> </div> Does anyone know where has the style="padding-bottom: 56.25%;" come from? How to edit/remove it? I tested it with youtube and vimeo both of whitch had that weird padding-bottom attribute set. Also to ensure that browser nor javascript are playing games with me I've tested it with curl. Using: wagtail==1.13.1 -
What are migrations exactly?
I started learning Django, and I did not understand the concept of migrations and why are they needed? Could anyone explain it in detail and clearly? -
Django: how to render form field without double quotes
Here is what I'm trying to achieve. I want to replace 3 static html inputs (checkboxes) with django form fields (forms.Form). When I render this piece of django template (line 43 for example): 38 <button id="visitas-mes-opcoes" class="btn btn-default col-xs-12" type="button" data-toggle="popover" 39 title="<label class='text-info'>Opções</label>" 40 data-content=" 41 <div id='opcoes-checkbox' class='checkbox'> 42 <label> 43 {{ form_pesquisar_visitas.maquinas_usadas }} 44 <input id='maquinas-usadas' class='checkbox-option' name='maquinas-usadas' type='checkbox' value='1'> 45 Máquinas Usadas 46 </label> 47 <hr style='margin: 8px -10px 8px -30px; width: 180px;'/> 48 <label> 49 <input id='vendas-efetuadas' class='checkbox-option' name='vendas-efetuadas' type='checkbox' value='1'> 50 Vendas Efetuadas 51 </label> 52 <hr style='margin: 8px -10px 8px -30px; width: 180px;'/> 53 <label> 54 <input id='vendas-perdidas' class='checkbox-option' name='vendas-perdidas' type='checkbox' value='1'> 55 Vendas Perdidas 56 </label> 57 </div>"> 58 <span class="glyphicon glyphicon-collapse-down"></span> 59 </button> I get the following result: But I was expecting something as the original html: Seems to me django is introducing some double quotes during the field rendering. Anyone knows how to work around this? -
How to add limited number of images per model in django?
I am trying to create an model for a student profile where the student can enter images to show images for their achievements. But I want to restrict the student from entering more than 5 images and one image compulsorily . How do I do that in Django? -
Django cache_page get last refresh time
I am using @cache_page on a view like this: @cache_page(60 * 60 * 24) def my_view(request): # my code return render(request, 'template.html', context) I would like to show in the template the last time the view has been refreshed (basically the last time the view was loaded without cache), how can I do that? -
django F ceil divison
I'm making annotate expression, and I don't khow how to realize what I expect. The model has 3 integer fields "AA","BB","CC" and my goal is to calculate those 3 like int(math.ceil(float(AA) / (BB)) *CC) If AA=4,BB=2,CC=3, then the answer is 6. *case1 And AA=5,BB=2,CC=3, it takes 9. *case2 annotate(ans=F("AA")/F("BB")*("CC")) This is enough for case1 because AA/BB is not round off, but in case2, the answer takes 6. I looked up this solution and found some ways. But I couldn't make it... Anyone knows solutions? -
How do I make a multiplayer concurrent game in Django?
Noob here. I'm trying to create a multiplayer game, in each team there would be 3 people. Person B submits after Person A and Person C after Person B. How do I achieve this? Preferably in python (Django). -
Django Cookiecutter
I am trying to use Cookiecutter on a Digital Ocean server. (Not using Docker) I followed the direction to install on Ubuntu 16 with Django, Postgres and Gunicorn. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I can not get past the allowed host error. DisallowedHost at / Invalid HTTP_HOST header: '128.199.100.100:8000'. You may need to add '128.199.100.100' to ALLOWED_HOSTS I have the setting in production.py ALLOWED_HOSTS = env.list ( 'DJANGO_ALLOWED_HOSTS', default = [ '128.199.100.100' ] ) Do I need to change any setting to make it a production environment? The only documentation on the Cookiecutter site is for pythonAnywere and Docker. http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-pythonanywhere.html I just want a simple DO install. Can not find any documentation? Thank you.