Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django testing: TypeError: 'int' object is not callable
I have written some test case in django, facing a type-error, def setUp(self): self.mobile_number = 9876543210 def test_obj_count(self): result = self.get_obj(self.mobile_number) self.assertEqual(result, 3) def get_obj(self, mobile_number): return Tolls.objects.filter().count()(toll__request__driver__profile__mobile_number=mobile_number) Here this line is throwing error result = self.get_obj(self.mobile_number) TypeError: 'int' object is not callable However it is working fine if I am using this function like as follow- def get_obj(self, mobile_number): toll = Tolls.objects.filter().count()(toll__request__driver__profile__mobile_number=mobile_number) return toll.count() -
How to set up a APIView in Django-Restframework?
I have a problem with the Django-Restframe work. I order to fill the charts of my website with stock prices I chose to set up a django rest framework based api. I am new to Django and watched a tutorial on youtube which i now of course do not find again. On local host the entire application works but once I want to publish the application on digital ocean I get errors like: AttributeError at / 'module' object has no attribute ‚JSONField' /usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py in ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField I think that I ignored major steps when setting up the rest-framework. Is here someone who knows how to set this up appropriately. I have spent quite some time into the entire application and API and would appreciate if someone could point me at some documentation where I could find an example of an similar case. Below I have attached all the code used for this case. I would appreciate very much if you could help me. The application is called TechnicalAnalysis btw. Application Files I have not jet made any changes to the Admin.py, Apps.py or Models.py files. I am especially concerned about not registering any models. But only found information about … -
Using get_queryset() in ViewSets, can't access the Detail Views. Error: Cannot use None as a query value
When I do a DELETE request to 127.0.0.1:8000/tasks/10/, I get the error that Cannot use None as a query value. views.py class TaskViewSet(viewsets.ModelViewSet): def get_queryset(self): p1 = self.request.query_params.get('parameter') queryset = Task.objects.nearby(p1) return queryset serializer_class = TaskSerializer urls.py task_list = views.TaskViewSet.as_view({ 'get': 'list', 'post': 'create' }) task_detail = views.TaskViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) # The API URLs are now determined automatically by the router. urlpatterns = [ url(r'^', include(router.urls)), url(r'^tasks/$', task_list, name='task-list'), url(r'^tasks/(?P<pk>[0-9]+)/$', task_detail, name='task-detail'), ] Everything works fine for list e.g. all requests to 127.0.0.1:8000/tasks/. However, none of the request work for the detail views. I'm assuming it's something to do with the get_queryset(). -
Uploading image to django ImageField using jdbc
I am trying to upload image file to a django Image field. All the fields get populated except image. My model is as follows: class ImageModel(models.Model): image_title = models.CharField(max_length=50, null=False, blank=False) uploader = models.CharField(max_length=50, null=False, blank=False) image = models.ImageField(upload_to='imgs/', null=True, blank=True) And here's the Java code snippet for inserting data: String query = "INSERT INTO testcaseconfiguration_Screenshots (image_title , uploader , image) VALUES(?, ?, ?)"; File file = new File("Image location goes here"); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte [] buffer = new byte[1024]; for(int readNum; (readNum = fis.read(buffer)) != -1; ){ bos.write(buffer, 0, readNum); System.out.println("Read " + readNum + " bytes..."); } byte [] image = bos.toByteArray(); PreparedStatement ps = connection.prepareStatement(query); ps.setString(1, "Some Title"); ps.setString(2, "Uploader Name goes here"); ps.setBytes(3, image); ps.executeUpdate(); }catch (Exception e) { e.printStackTrace(); } I know ImageField in django won't behave as I am expecting here but don't know how to proceed with the issue. Please someone help me. -
How do you add a custom django inline data table?
I have a model called "Stock", I want to create a admin view where when you go into the detail you can see a table of all the relevant stock amounts underneath as a InlineAdmin. I could do this with a custom template but I would want it to automatically page increment. Is there something that already does this or will I have to create custom views with a custom UI outside the admin to make this happen? -
Dynamically create workflow in viewflow using xml
Is it possible to create flow dynamically by defining the flow in xml and then parsing it. -
Django- Migrating an app from production to my local uat session - throwing appregistrynotready - Apps aren't loaded
I have a prod version of a project (made by someone else) that I am trying to deploy on my laptop. I have installed python through Anaconda 3. I have the necessary paths registered. And the code is working in the production environment without any issues. I have PostGreSQL installed and have it configured it like the prod environment. The command I am running is C:\sites\myanalysis>python manage.py makemigrations The result ends with the following exception: File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\db\models\base.py", line 90, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\apps\registry.py", line 244, in get_containing_app_con fig self.check_apps_ready() File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Googling the possible issue - I have the following installed apps within the settings.py file # Application definition INSTALLED_APPS = [ 'project.apps.ProjectConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] The settings.py file already has the following imported import psycopg2 import os Anyone can please help as to what else I can try? -
django override auth login method
I want to override login function in __init__.py of django.contrib.auth I did steps: urls.py url(r'^login/$', 'my_login'), views.py from django.contrib import auth def login(request, user, backend=None): # do some stuff settings.py INSTALLED_APPS = [ #'django.contrib.auth', 'my_auth_app' ] But i feel, its wrong way. Actually i want to get default conrtib.auth with overided login method -
building apps with kivy to intract with Django Restframework
so I have a project that developed with django ,Django Restframework. I had planned for UI handling. Reactjs and Reatnative for UI .but I searched and found Kivy project that comes with Cross Platforms for making Apps and games.my project doesn't involve any game stuff just regular web site. is it good using kivy for handling UI for Android and IOs? I also checked kivy supports fully Url request for interact with Rest APIs. https://kivy.org/docs/api-kivy.network.urlrequest.html -
Django inlineformset will not submit
My application has two models, Recipe and RecipeIngredient, related by foreign key. Each Recipe may have many different RecipeIngredients (and different number of associated ingredients for each recipe). So using a dynamic formset to assign ingredients to a recipe seems to be the best approach. I have a simple form that has a user enter a quantity and select a unit and ingredient from a dropdown. As a standalone form it works fine. Unfortunately, I cannot get any formset incorporating it to submit. I have searched many of the different formset Q&As here on StackOverflow but cannot see where the problem is. When I click 'submit', the form blinks and refreshes in place, with the entered values still in the form. No objects are created. No errors report to the console nor to the browser. The related code: The models: class RecipeBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) creation_date = models.DateField("Record creation date",auto_now_add=True) creation_user = models.CharField("Record creation user",max_length=150) lastupdated_date = models.DateField(auto_now=True) lastupdated_user = models.CharField(max_length=150) category = models.ForeignKey(RecipeCategory,on_delete=models.CASCADE,related_name='recipes') subcategory = models.ForeignKey(RecipeSubcategory,on_delete=models.CASCADE,related_name='recipes') def __str__(self): return str(self.name) class RecipeIngredient(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) quantity = models.DecimalField(max_digits=8,decimal_places=3,null=False) referenced_unit = models.ForeignKey(UnitDetail,on_delete=models.CASCADE) referenced_ingredient = models.ForeignKey(Ingredient,on_delete=models.CASCADE) parent_recipe = models.ForeignKey(RecipeBase,on_delete=models.CASCADE,related_name='ingredients') def __str__(self): return str(self.id)[:8] The call to enter ingredients: … -
best database design?
A table of user profile with 40 columns or 4 tables with 10 columns of user profile - divided into education,job,family. I require to filter to user profile on different fields given. -
Issues with image.path being reported wrong causing failing of a Celery task
I have the following model: class Image(models.Model): image = models.ImageField(upload_to=file_upload_to) I have a dynamic file_upload function: def file_upload_to(instance, filename): base = 'placeholder' .... base = '_'.join([str(instance.item.pk), instance.item.slug]) return os.path.join('accounts', base, 'item', base_2, 'images', filename) and in a modelform: class ImageModelForm(ModelForm) def save(self, commit=True): image_obj = super().save(commit=commit) # print(image_obj.image.path, image_obj.image.name,image_obj.product_id ) ..... product_image__task.delay(image_obj.image.path, image_obj.image.name, image_obj.product_id) return image_obj The file is saved properly in a path like: media/account/12_blue/images/image_name.jpeg The problem is that image_obj.image.path is not reporting the correct path, but this path: media/image_name.jpeg I use the image path, further passing it as an argument to a task, but because I received the wrong path, it will fail. How can I fix this, and receive the correct path ? (I thought of using a delay after save, but this not that good, because we don't know prior the time needed) -
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.