Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot show the value in html
I cannot show the value in html. I wrote in views.py def score_test(request): results = TestScore.objects.filter(user=request.user).all() print(results) return render(request, 'score_test.html',{'results': results}) in score_test.html <div class="col-xs-12"> <h2 class="result_title">Test Score</h2> <h3>Your score is {% for result in results.all %} {% if result.score > 95 %} <h4 class="one"> {{ result.score }} </h4> {% else %} {% if result.score > 80 %} <h4 class="two"> {{ result.score }} </h4> {% else %} {% if result.score > 60 %} <h4 class="three"> {{ result.score }} </h4> {% else %} {% if result.score > 40 %} <h4 class="four"> {{ result.score }} </h4> {% else %} <h4 class="five"> {{ result.score }} </h4> {% endif %} {% endif %} {% endif %} {% endif %} {% endfor %} </h3> </div> in models.py class TestScore(models.Model): score = models.FloatField(null=True, blank=True, default=None) In print(results) of views.py,I got ,so I think I can get score of TestScore model in results.So,how can I fix this?Am I wrong to write if-else statement in template of score_test.html? -
Django - Use the given sql dump to create the other models and to populate the data
I am practising to develop a complex app, i have previously developed the same with PHP and have a sql file. i'd like to know how do i create new models and populate the data from the sql file. I have read tutorials about grabbing from JSON files, But is there any online resources for the same. -
Using ldap login information to login to secondary site with Django Rest Framework
The actual question At my organisation we are using LDAP authentication for our services. I am creating a Django Rest service (Service A), that needs information from a different REST service (Service B) written in Java. A user logged into Service A should have access to their own private information stored in Service B and therefore needs to log in to both services at the same time. Since we use LDAP, the credentials are the same for both services. My question is then: What is the most Pythonic (and secure) way to log in to Service B from Service A? My own suggestions: I have considered these two approaches so far: Using the user_logged_in signal from django.contrib.auth.signals import user_logged_in def login_to_service_b(sender, user, request, **kwargs): username = request._post['username'] password = request._post['password'] token = send_login_request_to_b(username, password) #...Save token and other things... The advantage here is that the code is encapsulated decently, but it also uses private fields on the request object. Wrapping the LDAP authentication backend from django_auth_ldap.backend import LDAPBackend class ServiceBBackend(LDAPBackend): def authenticate(self, request, username=None, password=None): # Log in to Service A try: user = super().authenticate(request, username, password) except Exception as e: raise e try: # Log in to Service B … -
Hiding ModelMultipleChoiceField on template for custom input
I want the user to select a number of elements belonging to a certain model. I don't want to use the default 'ctrl+click' input of django forms, but create a table of checkboxes myself. For that reason I hide the ModelMultipleChoiceField by defining the widget: field = forms.ModelMultipleChoiceField(..., widget=forms.MultipleHiddenInput()) Then I add the form element into the template as follows: <form method="POST" class="locklist-form" id="locklist-form">{% csrf_token %} {{ form.field }} </form> At this step, I expect the select-option elements to be added to HTML page (as hidden), so that I can reach to element options and modify them with javascript. However, it doesn't add anything to the HTML page. I use this approach with other type of form fieds. For a TextField HTML page have a hidden element as shown: Why doesn't it work with ModelMultipleChoiceField? How can I modify the choices of this field with Javascript? -
Vue Template not updating after data is changed
I am new to Vue, and I have played around with small vue applications, but this is the first project I've done using vue and webpack (vue-cli). I have a django rest API set up, for which I then use vue to consume the API and display the data. The issue i'm having is when I want to do anything the templates aren't updating. The data is loaded in correctly, but if I try and do a @click event and then a v-show (to toggle displaying an item) it doesn't change the view. Example, lets say I have a list of pubs that I consume from the API. I get them via axios, and store them in the data function in a array called pubs: <script> import axios from 'axios' export default { name: 'Pubs', data () { return { pubs: [ { pub_id:'', name:'', address:'', showPub: false, }, ] } }, created: function () { this.loadPubs(); }, methods: { loadPubs: function () { var vm = this; axios.get('http://127.0.0.1:8000/api/pubs/') .then(function (response) { vm.pubs = response.data; vm.pubs.forEach(function (pub) { pub.showPub = true; }); console.log("loaded"); }) .catch(function (error) { this.pubs = 'An error occured.' + error; }); }, togglePub: function (pub) { … -
calculation sum of a django model field
class Transaction: amount = models.FloatField() Now I calculate the sum of amount transactions = Transaction.objects.all() amount = 0 for transaction in transactions: balance = transaction.amount amount += balance I know it is calculate by using agreegate. But is this possible by this way or another way ? -
How to bypass manage.py in django? [duplicate]
This question already has an answer here: How to do database migration using python script? 1 answer I am following django tutorial at: https://docs.djangoproject.com/en/1.10/intro/tutorial02/ The page says: Bypassing manage.py If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable to mysite.settings, start a plain Python shell, and set up Django: >>> import django >>> django.setup() If this raises an AttributeError, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version. You must run python from the same directory manage.py is in, or ensure that directory is on the Python path, so that import mysite works. For more information on all of this, see the django-admin documentation. the resulting django-admin documentation is also silent how you can bypass the python admin.py My question is How to bypass the shell commands and do the python manage.py from python file itself. related question: How to do database migration using python script? -
Django ForeignKey to textfiled
I have one foreign key class Task(models.Model): task_relates = models.ForeignKey('Task',on_delete=models.SET_NULL) I am getting choice filed when I paint this on form but I want input from the user as in textfield and then manually I will check it to the id. how to print the same filed as textfield in form? I tried this task_relates = forms.CharField(max_length=30, required=False) -
M2M relationships to self with attribute.
I want to create cross selling product: class Product(models.Model): name = models.CharField(max_length=150, blank=True, default='') ... class CrossSellingProduct(models.Model) parent_product = models.ForeignKey(Product, related_name='cross_sellings') associate_product = models.ForeingKey(Product) double_sided = models.BooleanField(default=1) I want to call function cross_selling_products on product instance and see all products which are associated. If double_sided is True I can see associated product in bouth way, if False only parent -> associated_products. Is some smart way to implement this? Thank you. -
Django Error for property
We are to trying to run the below code however we are getting an error Exception Type: NoSectionError Exception Value: No section: 'credentials' can someone help me out please import configparser def populate_skillgroup(request): print("djangoo app") config = configparser.RawConfigParser() config.read('Supervisor.properties') user_name = config.get('credentials', 'db_credentials.user_name') password = config.get('credentials', 'db_credentials.password') db_name = config.get('credentials', 'db_credentials.database_name') -
Session api on django
I need to implement using api such behavior: App opening without registration If it's new user, then send signup request, and get new session If there is a session, then check it. So I think I need /signup method which creates session and returns a session token. And /check method which gets a token and returns check result. Could you please help me with implementing that? I'm new at Django. And I want to use Tastypie for api. -
pymssql INSERT won't auto increment ID
I am using pymssql in my django project to connect to a database. I'm trying to use execute() method to do an insert. However I get this error: Cannot insert the value NULL into column 'ID', table ITEMS the ID column is primary key and so it should be filled by the sql itself as I understand. here is my insert command: bill_id = execute(""" INSERT INTO ITEMS(COlUMN1,COlUMN2, COlUMN3,COlUMN4,COlUMN5) VALUES (%d, %d, %d, %d, %d); """, (1713, 6, 929, 1184, 25)) and none of these COLUMNs are ID. can anyone tell me what am doing wrong? -
Can not parse the remainder: '==0' from 'data.tab_nid==0'
I my template, I want to give a class active: <li>{% if data.tab_nid==0 %} class="active" {% endif %} </li> But when I run the page I get the bellow error: TemplateSyntaxError: Could not parse the remainder: '==0' from 'data.tab_nid==0' -
Chrome does not stream content from Django's StreamingHttpResponse
A year ago, I used Django's StreamingHttpResponse to stream a text file and Chrome immediately displayed every trunk of text that it received. Now, with the same code, Chrome only displays the text when it completely loads the text file, thus risks server timeout. This does not happen with Firefox. I created a simple test: # views.py import time from django.views import generic class TestEditView(generic.TemplateView): def generator(self): for _ in range(15): time.sleep(1) yield 'THIS IS {}\n'.format(_) print('LOG: THIS IS {}\n'.format(_)) def get(self, request, *args, **kwargs): return StreamingHttpResponse(self.generator(), content_type="text/plain; charset=utf-8") If I access that view in Firefox, that browser will print out 'THIS IS ....' each second for 15 seconds. But in Chrome, the browser will wait 15 seconds, then print out all of the 'THIS IS...', even though the development server log 'LOG: THIS IS...' once a second. I wonder if there is any subtlety in this problem that I missed. Thank you. Python: 3.6.2, django: 1.10.5 -
duplicate key value violates unique constraint itemstaticlabel_item_id_f9405967_uniq
I know, this problem happens because the code is trying to add an entry to the database with a combination of unique keys that already exist. But my question is: why and how can I prevent this? It doesn't make sense to me that this is happening, given my logic. I have this piece of code that basically stores some static label for an invoice. The idea is to create the label on the fly if it doesn't exist, instead of manually inserting it in a lot of places in the code. Whenever an Item is generated, an ItemInv is also created, and by saving the latter, I check if a static label exists. If it doesn't, a new one is created. The code to get (or create) the static label is also called when displaying an Invoice / Draft. The error seems to happen right there. The label doesn't exist, a new one is created, but somehow this happens twice? I mean, I really don't get why that code would try to add the same item two times. Could it be a thread issue? I am not using get_or_create because some attributes on ItemStaticInv (static_account_label, static_agreement_label...) can be updated … -
Create sql schema from django models or migrations
I created different models with django 1.8. Now, to enable other people to have a quickly comprehension, I would create a sql schema from the models or from the migration files (even only from the initial migration file). Someone knows how does it? -
Return Python Django model as a json object
I am trying to return an object created from a Django model as JSON to the rest framework after being created. I have tried many ways but they all don't seem to work. Here is my code; router.register(r'amazon/products/import/(?P<id>[-\w\d]+)', amazon_views.AmazonImportProductViewSet, base_name='import-amazon-product') ...routing to... class AmazonImportProductViewSet(viewsets.ViewSet): def list(self, request, id=None): product = simple_amazon.lookup(ItemId=id, ResponseGroup='ItemAttributes,Offers,Images,EditorialReview,Reviews') brand = get_object_or_404(AmazonBrand, name="microsoft") createdProduct = AmazonProduct.objects.create(title=product.title, brand=brand) #json_p = serializers.serialize("json", createdProduct) serializer = AmazonProductSerializer(createdProduct) return Response({'success': "true", 'message':'Imported successfully!', 'product':serializer.data}) I am trying to return just 1 object with it's OneToMany relationships. For example I would like brand returned as well. -
Angular 2 with Django
I am struggling to find a good tutorial or documentation that covers the integration of Django and Angular 2+. It is easy to find documentation for each individually but cannot find something suitable which takes you through both at the same time. For other languages such as C# there are many books on ASP.Net and Angular 2+ together. I find it strange as to why there is no documentation for Django (in Python). Does anyone know where I can learn how to connect these two popular technologies? -
Django - write model contents to new file
I have a Django model, and I want, when the user clicks on submit, the model not only saves the data in the database, but also writes them in a new file in this format: (structid,name,pos,long,type). I am new to Django and I am doing my internship in it. -
Django: HTTP status 400 response rolls back model save?
I have an API endpoint to trigger a payment request to a third party. The endpoint is called with some data in a POST request and goes something like the code below. Somehow when the payment request failed (payment.is_successful = False), no data was ever saved to the database, although the debug log showed SQL INSERTs being made, and no error was thrown. The data was just dropped silently. I figured that if I changed HTTP_400_BAD_REQUEST to HTTP_200_OK then my data is saved. Why is this happening (and where is the code responsible for it)? Is there a way to prevent it from happening (I want my data in the db for this view, no matter what) with some setting in Django/DRF? I've temporarily set the return code to 200, but it feels wrong as the request actually failed. What code would make more sense, that doesn't cause the data to disappear? view code ser = MySerializer(data=request.data) if ser.is_valid(): payment = ser.save() else: # do some non database stuff return Response(result, status=status.HTTP_400_BAD_REQUEST) if payment.is_successful: # some more processing return Response({'success': True}, status=status.HTTP_201_CREATED) else: return Response({'success': False}, status=status.HTTP_400_BAD_REQUEST) ## THIS LINE ## serializer code class MySerializer(serializers.ModelSerializer): def create(...): # call payment … -
Django <object> is not JSON serializable
I am using https://github.com/coderholic/django-cities and i wanted to add city and country to my serializer. This is my model: from cities.models import Country, City class Location(models.Model): name = models.CharField(max_length=200, blank=True, null=True, default=None) city = models.ForeignKey(City, blank=True, null=True, default=None, related_name='city_of_location') geolocation = map_fields.GeoLocationField(max_length=100, blank=True, default='') My views: class LocationsView(generics.ListAPIView): queryset = Location.objects.order_by('-id') serializer_class = LocationsSerializer serializers.py class LocationsSerializer(serializers.ModelSerializer): number_of_rooms = serializers.SerializerMethodField() country = serializers.ReadOnlyField(source='city.country') class Meta: model = Location fields = ['id', 'name', 'geolocation', 'city', 'country'] When i'm trying to see if it works i'm getting: <Country: Austria> is not JSON serializable -
my django can't generate models from oracle database
I am building django project upon oracle database, after i set my database in django settings, i use command python manage.py inspectdb to generate oracle tables, but there is an error: > Unicode DecodeError: 'utf-8 codec can't decode bytes in position > 82-83:invalid continuation byte what can i do ? the oracle is not install in my local pc. i tried to set local env path:NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK, it doesn't work. Thank you for your help! -
How to use request.META.HTTP_HOST inside Django models?
I'm trying to improve my app's SEO by having absolute URLs to my links (link for each world city). I managed to do so in the template by doing this: <a title="{{city.name}}" href="http://{{ request.META.HTTP_HOST }}/{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> However I'm trying to implement the same from the model in a way that I can simply do this: <a title="{{city.name}}" href="{{city.get_absolute_url}} " target="_blank">{{ city.name }} </a> This is my attempt: def get_absolute_url(self): return "http://" + self.request.META.HTTP_HOST + '/city/%s/' % self.slug But I get this: name 'request' is not defined How can I import the user request to use in a model? -
ajax is not working with django
i am creating a form that add a comment to a post, it is working without ajax, because ajax send the form data as None. the ajax: <script> $(function() { $("#myform").on("submit", function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: 'POST', data: $(this).serialize(), beforeSend: function() { $("#message").html("sending..."); }, success: function(data) { confirm('worked') } }); }); }); </script> the form: <form action="{% url 'newcom' Post.id%}" id="myform"> <div class="input-group"> <input type="text" name="comment_body" class="form-control" placeholder="Leave a comment"> <div class="input-group-btn"> <button class="btn btn-success" id="message" type="submit"> <i class="glyphicon glyphicon-send"></i> </button> </div> </div> <br> </form> the view: def new_comment(request, post_id): body = request.GET.get('comment_body') post = Post.objects.get(id=post_id) Nat.objects.create(fromUser=request.user.username, toUser=post.created_by, content="commented on your post") Comment.objects.create(post=post, created_by=request.user, created_at=timezone.localtime(timezone.now()), comment=body) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Shall I rename user uploaded files?
Django==1.11.6 There are file upload attacks. But modern Django seems well guarded against them. Django security guide is here: https://docs.djangoproject.com/en/1.11/topics/security/#user-uploaded-content Concerning user uploaded files it is much shorter than other security guides. In the Internet we can find this kind of advice: The application should not use the file name supplied by the user. Instead, the uploaded file should be renamed according to a predetermined convention. Well, I think that renaming is a good idea. Shall I rename user uploaded files or it is not dangerous in case of modern Django?