Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Obscure fields from django GET request
I am fetching the relatedfiles_set in my ControlsSerializer, but I would like to obscure the uploaded_by_user_id and organization_id for security purposes. I still need those fields in the RelatedFileSerializer for when I create new relatedfiles, but I don't want them to show during GET requests. Is there any way I can hide these fields without creating separate serializers for these two types of requests? class RelatedFileSerializer(serializers.ModelSerializer): class Meta: model = RelatedFiles fields = ('control', 'file', 'uploaded_by_user_id', 'organization_id', 'note', 'uploaded_at') class ControlsSerializer(serializers.ModelSerializer): relatedfiles_set = RelatedFileSerializer(many=True, read_only=True) class Meta: model = Controls fields = ('relatedfiles_set', 'id', 'sorting_id', 'requirement', 'requirement_section', 'requirement_subsection',) -
How to insert list of integers into a string for a database query - Python 3
I am trying to use the cursor execute to make a query in a django application, but when I pass the list into the query string it comes with quotation marks and returns the following error: psycopg2.DataError: invalid input syntax for integer: "139,212,933,2303,2613" LINE 1: ...ados_ibge.sociodemografia_rmc sd WHERE sd.gid IN ('139,212,9... This is the code ive been working on so far.. if gids: with connection.cursor() as cursor: g = ','.join(gids) cursor.execute("SELECT * FROM poi.farmacias_rmc f, dados_ibge.sociodemografia_rmc sd WHERE sd.gid IN (%s) AND ST_Intersects(sd.geom, f.geom) = true", [g]) rows = cursor.fetchall() -
Django: unique constraint with a DESC order index
I'm trying to add a unique constraint with a desc index. I can create a desc index on two fields like that : class Meta: indexes = [ models.Index(fields=['some_field', '-date']), ] And I can create a unique constraint like this : class Meta: constraints = [ models.UniqueConstraint( fields=('some_field', 'date',), name='core_message_uniq_mmsi_time' ) ] This will create a unique index, but the order won't be the good one and for some reason using a '-date' in the UniqueConstraint does not seem to do the trick. Is there something I'm missing, or is it required to have two indexes, one with the unique constraint and another one with the correct order ? Thanks ! -
How to get user current location with react native and django
need your helps guys how get user current location with react native and django. Sample code if possible -
Is there any ORM for finding latest output for component and environment
Unable to get the value correctly while i am trying annotate in Django ORM query.Please can anybody help with the correct ORM? I am creating a deployment matrix Dashboard using django. Here this is a dashboard for deployment detail for deployment happens in some environment through jenkins the input to the models will be given manually but we need a output in html that env name - componens(as per environmnt) details of the deployment according to the env and compoment below i have showed you what output i need for my project Please help dtls = deploy_dtl.objects.values('env','comp','deploy_version').annotate(max_date=Max('updated_dt')).order_by('env','comp')``` This the table data under which i am querying here 1 env can have multiple comp and i component can have multiple deployment but we want to get the latest 'updated_dt' regarding the group of components. +----+--------+---------+----------------+---------------+--------------------+----------------------------+--------------+--------------+ | id | env_id | comp_id | deploy_version | deploy_status | deploy_reqster_nme | updated_dt | updated_by | remarks | +----+--------+---------+----------------+---------------+--------------------+----------------------------+--------------+--------------+ | 2 | 1 | 1 | 1.00024 | Deployed | Arun sahoo | 2019-09-03 12:50:41.934499 | Amit Samanta | NIL | | 1 | 1 | 1 | 1.00023 | Deployed | Arun Sahoo | 2019-09-03 10:56:52.472392 | Amit samanta | Amit samanta | | … -
Laravel and Python Integration
I want to integrate a web application built in PHP framework Laravel to a desktop raw Python Code. I am working for my University project i.e., Student Attendance Management System using Face Recognition. I've already created School Management System that contain Attendance Module in it. Now when I created Python desktop based Facial Recognition Attendance System so I want to link both of these system in a way that when face is recognised by the Python system it'll mark attendance in the database and on Laravel System ID-CARD of Student will popup as this student is checked in the school or university. I tried it by connecting both systems to same database, and used pusher, echo, and axios to make it realtime. But problem is Student ID-CARD only pops-up when attendace is marked from the web app (laravel app). When python system marks attendace it only displays when web-app is refreshed. NOTE: Reason of doing such complicated thing is, I can only code in these two languages. Raw Python and Laravel... Please Help Me Out :( -
Where to up django app startup code that must interact with the database?
I have some django code that needs to run once when my app is loaded. This code also needs to write to the database. This SO question "Where to put Django startups code?" recommends using AppConfig.ready for startup code. However, the docs for the ready function clearly warn against interacting with the database: Although you can access model classes as described above, avoid interacting with the database in your ready() implementation. This includes model methods that execute queries (save(), delete(), manager methods etc.), and also raw SQL queries via django.db.connection. Your ready() method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test would still execute some queries against your production database! Is there some later startup hook I should use for code that does need to update the database? -
TypeError: cannot unpack non-iterable NoneType object --> But object exists?
I am going mad over some code. Executing a program that is made to generate product suggestions randomly always yields to the error TypeError: cannot unpack non-iterable NoneType object Yet I cant seem to see, where a NoneType object is returned. All print statements clearly indicate that I return an object and a Boolean. Unfortunately, it's quite a bit of code and I can't seem to reproduce the error with less code. @staticmethod def generate_random_product(variation): product_options = Product.objects.all() if not product_options: raise ValidationError( 'PRODUCT CREATION FAILED HARD COULD NOT ' 'GENERATE RANDOM PRODUCT FOR: ' + variation.name + '... PLEASE DELETE' 'ALL DELIVERIES THAT WERE CREATED TODAY' ) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], True def generate_random_product_from_category(self, variation, count): if count >= 10: return self.generate_random_product(variation, count) category = variation.package.category product_options = category.product_set.all() if not product_options: return self.generate_random_product(variation) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], True def generate_random_product_from_variation(self, variation, count): if count >= 5: return self.generate_random_product_from_category(variation, count) product_options = variation.product_set.all() if not product_options: return self.generate_random_product_from_category(variation) random_int = random.randint(0, (product_options.count() - 1)) return product_options[random_int], False def turn_variation_into_product(self, variation, delivery, count): if count < 15: # STEP 1: generate a random product random_product, failed_auto = self.generate_random_product_from_variation(variation, count) print(random_product) try: self.turn_variation_into_product(variation, … -
Docker+Django+SECRET_KEY: regenerate?
Imagine you create a docker-compose.yml with Django and a bunch of code and use an environment variable to configure the SECRET_KEY in settings.py. If you distribute that Docker image you won't share the SECRET_KEY. What SECRET_KEY should someone use when they deploy your Docker image? They can't make up their own SECRET_KEY right? According to the documentation, changing the secret key will invalidate: All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash(). All messages if you are using CookieStorage or FallbackStorage. All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided. What's the best way to 'renerate' a secret key after deploying a Docker container with a bunch of code that you created? (I have searched and searched but feel like I'm searching for the wrong things or completely missed something :-) -
How to set up the Django model architecture for unknown properties?
I have a Person model. class Person(models.Model): name_first = models.CharField(max_length=100) name_middle = models.CharField(max_length=100, null=True, blank=True) name_last = models.CharField(max_length=100) date_birth = models.DateField(null=True, blank=True) date_death = models.DateField(null=True, blank=True) I'm trying to extend it to different roles in the music world: a composer, a performer, and a patron. A person can be one, two or all three roles. If a person is a performer, I also need to assign one or more instrument for that person. You may not know if a person is a performer at the time of instantiation. Or their roles can change over time. I want to be able to search and display that a person is a composer, pianist and a patron, if he's all three. For example: Beethoven is a conductor, composer, and pianist. My initial thought on implementation is to inherit the Person class. class Composer(Person): pass class Performer(Person): instrument = models.CharField(max_length=100, blank=True) performer_type = models.CharField(max_length=100, blank=True) //conductor, performer class Patron(Person): pass Question 1: should I use some sort of abstract model instead? If so, how would I go about it? Question 2: how can I search for a person and know whether they are a composer, patron and/or performer and the kind of performer they … -
How do I not show delete confirmation in Django admin unless conditions are met
I overrode the delete_queryset method to add a condition before being able to delete a model. It looks like this: def delete_queryset(self, request, queryset): if condition_is_not_met: self.message_user(request, 'Error', level=messages.ERROR) return super().delete_queryset(request, queryset) This DOES prevent the deletion but it shows that error message and below it says, Successfully deleted 'x' objects (Again, not deleted so success message should not be there). I don't want to display that error message and what would be even better is if the confirmation page did not even show up if the condition is not met (This is a bonus though). Any suggestions? -
DRF Serializer Error: AttributeError: 'FeedPostSerializer' object has no attribute 'auth_user'
I´m creating a newsfeed in an APP. A user is logged in and sees the posting of other users. Therefore I need two user models (user + auth_users) Now I want to add a boolean field that shows if a post is already liked or not. I already looked at the documentation and other posts here but I can´t find a solution. The auth_user is shown in the response but I can´t included it in the "get_already_liked" function class NewsPostSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(read_only=True) auth_user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) attachments = AttachmentSerializer(read_only=True, many=True) already_liked = serializers.SerializerMethodField() def get_already_liked(self, request): liking_kwargs = { 'post_id': request.id, 'user_id': self.auth_user } if LikePost.objects.filter(**liking_kwargs).exists(): return True else: return False class Meta: model = Post read_only_fields = ( 'id', "user", 'creation_time_stamp', 'auth_user', 'ready_liked', ) fields = ( 'id', 'user', 'creation_time_stamp', 'last_update_time_stamp', 'description', 'attachments', 'already_liked', 'auth_user', ) -
Render JSON in HTML Table with Django/JavaScript
Friends, I need your help! I am new to Python / Django and I am doing this project with the knowledge I get from day to day studying. I have a function in my views.py that communicates with an API and returns a result in Json. The result is basically this: [ { "_id": "5d6f28ec02523e0012a4eae6", "pass": false, "renderSatisfaction": false, "botTimeOut": false, "ignore": false, "exit": false, "errorslog": [], "chaterroslog": [], "Historic": [], "userID": "5b43b8a48b769470363b58909a9049", "user_key": "ABCD", "username": "Igor Miranda", "Created_at": "2019-09-04T03: 01: 00.716Z", "__v": 0 } { "_id": "5d6f291d55d3f500402d338e", "pass": false, "renderSatisfaction": false, "botTimeOut": false, "ignore": false, "exit": false, "errorslog": [], "chaterroslog": [], "Historic": [], "userID": "577a55a043aab2a6aa78586b2520392", "user_key": "ABCD", "username": "Igor Miranda", "Created_at": "2019-09-04T03: 01: 49.484Z", "__v": 0 } ] I need to render this result inside a table in an HTML page with Django, where I have the result of the fields "username", "username_key" and "history". I've read a lot of topics here on StackOverFlow, but I still can't solve my need. Follows my views.py, ConsumimirApi.html files and the result on the page. views.py def ConsumirApi(request): url = 'http://urlapi.test.com.br' body = {"start": "2019-09-04 19:30:00", "end": "2019-09-04 23:59:59"} response = orders.post (url, auth = HTTPBasicAuth ('123456', 'password1234'), headers = {'Content-Type': 'application … -
How can i possibly make a dynamic REST API link of a Model that changes by id of another Model?
What i currently have setted up with django rest is : MODEL NAME : Animes /api/ <- root /api/animes/ <- lists all animes available in my db /api/animes/id/ <- returns the anime instance that has id=id MODEL NAME : Episodes /api/ <- root /api/episodes/ <- lists all episodes of all animes available in my db /api/episodes/id/ <- returns the episode instance that has id=id So basically im trying to achieve is : if i request api/episodes/{anime_name}/ i get that specific anime's Episodes listed . how can i do that ? EpisodesSerializer class EpisodesSerializer(serializers.ModelSerializer): class Meta: model = Episodes fields = '__all__' Router router = routers.DefaultRouter() router.register('animes', AnimesViewSet, 'animes') router.register('episodes', EpisodesViewSet, 'episodes') urlpatterns = router.urls EpisodesViewSet class EpisodesViewSet(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] MainModel = Episodes queryset = Episodes.objects.all() serializer_class = EpisodesSerializer -
How can I add a class automatically in Django?
I would like that every time I create a form with django the tag input includes a specific css class (form-control), to do this I have to write in form.py the following code, adding lines for each field: class InsertItem(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'form-control'}) self.fields['price'].widget.attrs.update({'class': 'form-control'}) Is there a way to force Django to include the css class that I need in every form, without having to write that things for each from and each line? -
Django save method is overwriting field values
I have a model that is overwriting a field value during the save opperation, I don't know if that happens during the communication with the database or its a pure Django problem. My bugged model: class Classificacao(models.Model): item = models.ForeignKey(Item, verbose_name="Item", db_index=True, on_delete=models.CASCADE, db_column='seq_prod') is_valid = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In order to identify the bug I overwrited the save method: def save(self, *args, **kwargs): print(self.is_valid) super(Classificacao, self).save(*args, **kwargs) print(self.is_valid) When I created an instance of the class by the following code the overwrited 'save' prints the above: classificacao_nova = Classificacao.objects.create( item=item, created_at=datetime.datetime.now() ) Output: True False The problem gets worst: in other parts of the code the output is True True. Any ideas of what is going on? PS.: The database default for the is_valid column is 1. -
Nested JSON and HyperlinkedModelSerializer problem
I'm working on a tweet App. I have 2 main models : Tweets and Comments. I'm using HyperlinkedModelSerializer to get absolute url for my comments instances with the "url" added in the field. But when It comes to display the comments inside my tweet JSON format, i have this error : `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. This error is gone when I remove the url from the field. Here is my Comment Model : class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id) return qs class Comment(models.Model): content = models.TextField(max_length=150) author = models.ForeignKey( User, on_delete = models.CASCADE ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(blank=True) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey( "self", on_delete = models.CASCADE, blank=True, null=True ) datestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.content[:30]) def save(self): self.object_id = self.parent.id super(Comment, self).save() def children(self): return Comment.objects.filter(parent=self) @property def is_parent(self): if self.parent is None: return False return True Here is my comment serializer : class CommentSerializer(serializers.HyperlinkedModelSerializer): children = serializers.SerializerMethodField() datestamp = serializers.SerializerMethodField() def get_datestamp(self, obj): return obj.datestamp.date() def get_children(self, obj): qs = obj.children() return ChildrenCommentSerializer(qs, many=True).data class Meta: model = … -
Django Post Request to Detail Page (Id)
I want to make a Django post request to specific url with a pk. So I have a list of projects and inside every project there are tasks. I want to add a task to that specific project. This is the View function to create a normal project: @login_required def create_project(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) usernames = request.POST.getlist('Studyplan-Canview') users = User.objects.filter(username__in=usernames) userprofiles = UserProfile.objects.filter(user__in=users) project = Project(name=name, description=description, parent_assignment=parent_assignment) project.save() project.canview.set(userprofiles) project.members.set(userprofiles) return redirect('allProjects') This is the project: When I tap this I get a detail page with a lot of tasks: This is a task: So as you can see every project has multiple tasks: This is my attempt at doing a post request to tasks. My problem is that the task is not connected to the id of the project: @login_required def create_task(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') usernames = request.POST.getlist('Studyplan-Canview') users = User.objects.filter(username__in=usernames) userprofiles = UserProfile.objects.filter(user__in=users) task = Task(name=name, description=description, state="new") task.save() task.canview.set(userprofiles) task.workers.set(userprofiles) return redirect('allaStudieplaner') So this is aa picture from the admin page. I am inside the project and I want the task to be selected here: -
Setted attribute with setattr is different type than given value in Python (Django)
Since ArrayField does not work with FileField in Django, I'm trying to fix it. However, I came up to a line of code, where I don't understand, how it happens, that setted attribute using setattr becomes different type than given value. To be exact - if I add print lines to code: print(data) setattr(instance, self.name, data or '') # line 317 print(getattr(instance, self.name) Here's what I get when I save a Model with FileField: <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> <class 'django.db.models.fields.files.FieldFile'> What happens here? -
Google Vision API error when I push on Heroku
I have the following problem: I performed all the configuration as per Google Cloud documentation The credentials are validated and I can read the images by their url normally. It works fine, but only when it is on localhost, when it goes into production (heroku) does it simply stop working, returning error 503 - service unavailable. It makes no sense because in localhost it works perfectly. Do I need to set up something in my Google Cloud account or something? I really don't know what to do anymore. -
django create count subquery without groupby
I want to use a query thatn could be used as qubquery. But I noticed that query like this: x = Deal.all_objects.filter(state='created').values('id').annotate(cnt=Count('id')).values('cnt') produces SELECT COUNT("deals_deal"."id") AS "cnt" FROM "deals_deal" WHERE "deals_deal"."state" = created GROUP BY "deals_deal"."id" I dont need the GROUP BY, I jost want to count offers that match filter. I dont want to use .count() because It would not let me to write a query like this: Deal.all_objects.filter( Q(creator=OuterRef('pk')) | Q(taker=OuterRef('pk'), state='completed') ).annotate(cnt=Count('pk')).values('cnt') How to modify above query so that it count without GROUP BY? -
How we can auto generate reciept number using python django and that reciept number into json object
i have JSONField instalment_1 . I have to calculate reciept for each instalment. please help me here -
How change urls dynamically based on chosen language prefix
I have 2 languages in Django project. Base is site/pl/ and 2nd is site/en. There are also 2 buttons in header.html to switch language (add prefix to url). String translation works fine. My problems are: 1. When I switch(click button) between languages I want to load home page because right know it works only when I am at home page - so if I move to any subpage and click to language button it reload same page (not home). 2. When I switch between languages I want to change also subpages urls to right names. I try some weird way to made this: <li><a href="{{baseurl}}">PL</a></li> <li><a href="{{en_url}}">EN</a></li> and then in views: def index(request, *args, **kwargs): baseurl = '/' en_url = baseurl + 'en' return render(request, 'home.html', {'baseurl': baseurl, 'en_url': en_url}) But I assume it's bad. Here my code: views.py def index(request, *args, **kwargs): return render(request, 'home.html') def about(request, *arg, **kwargs): return render(request, 'about.html') def offer(request, *arg, **kwargs): return render(request, 'offer.html') def contact(request, *arg, **kwargs): return render(request, 'contact.html') app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('o-nas', views.about, name='about'), path('oferta', views.offer, name='offer'), path('kontakt', views.contact, name='contact'), ] in header.html <li><a href="{% url 'index' %}">PL</a></li> … -
How to get compact html code in page source? Django, html
I am sorry if the title is not very precise but I don't know how to define it correctly. I use many tags in my template, so my code after previewing the page has a lot of empty spaces. How can I get the code compact like on the example below (examplefor google browser): [...] startsWith",function(a){return a?a:function(e,c){if(null==this)throw new TypeError("The 'this' value for String.prototype.startsWith must not be null or undefined");if(e instanceof RegExp)throw new TypeError("First argument to String.prototype.startsWith must not be a regular expression");var b=this+"";e+="";for(var f=b.length,d=e.length,h=Math.max(0,Math.min(c|0,b.length)),g=0;g<d&&h<f;)if(b[h++]!=e[g++])return!1;return g>=d}});google.arwt=function(a){a.href=document.getElementById(a.id.substring(a.id.startsWith("vcs")?3:1)).href;return!0};(function(){var g=function(a,b){this.g=a===e&&b||"";this.i=f};g.prototype.l=!0;g.prototype.j=function(){return this.g.toString()};var h=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i,f={},e={};var l=/^((market|itms|intent|itms-appss):\/\/)/i,m=function(a){var b;a instanceof g||!l.te [...] The code after choosing the view page source option does not contain any spaces. Why does Google and many other websites use this solution and what is its proper name? -
Field name `username` is not valid for model `User` django rest-auth
i am trying to use django rest_auth login with email : serializers.py: from rest_framework import serializers from users.models import User from rest_auth.serializers import LoginSerializer class CustomLoginSerializer(LoginSerializer): username = None email = serializers.EmailField(required = True) password1 = serializers.CharField(write_only = True) class Meta: model = User fields = ('email','password') imported the loginview: from rest_auth.views import LoginView class CustomLoginView(LoginView): queryset = User.objects.all() i have created custom user modal with email so as the error shows username is valid but how can i remove from login. when i run the localhost:8000/rest-auth/login i am getting email and password view but after login it showing this: Field name `username` is not valid for model `User`