Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading images/file in Django in production mode
I am a noob in Django and I am about to deploy my first site in Django. I have a Profile model in my models.py file which has profile_pic attribute which will store the profile pic of the user. It is working well when upload the image in the development mode,ie, when DEBUG=True. But what changes do I have to make in the urls.py so that users can easily upload their profile picture even after deploying my site. Any code snippetor examples or some link would be very helpful. -
How can I insert forms in the Infowindow to save the markers?
I'm trying to set the html template as the infowindow content. I want to save map markers to the database through the infowindow. I try to make the infowindow as a html form and get the markers information to the database. How can I set the form as the infowindow content? btw I'm using sqlite3 database. Here's my code part of the maps.js: function addmarker() { var geocoder = new google.maps.Geocoder(); var infowindow = new google.maps.InfoWindow(); var myLatLng = map.getCenter(); var marker = new google.maps.Marker({ position: myLatLng, title: 'new marker', draggable: true, map: map }); markers.push(marker); geocoder.geocode({'latLng': myLatLng }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { $('#latitude,#longitude').show(); $('#address').val(results[0].formatted_address); $('#latitude').val(marker.getPosition().lat()); $('#longitude').val(marker.getPosition().lng()); var html = "<form method='post'>"+ "{% csrf_token %}{{ mks }}"+ "<button type='submit'>Submit!</button>"+ "</form>"; infowindow.setContent(html); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } } }); } google.maps.event.addDomListener(window, 'load', initialize); Views.py: from .models import Markers from .forms import AddMarkersInfo from django.http import HttpResponse def index(request): if request.method == 'POST': mks = AddMarkersInfo(request.POST) if mks.is_valid(): submit = mks.save(commit=False) submit.user = request.user submit.save() name = mks.cleaned_data['name'] address = mks.cleaned_data['address'] description = mks.cleaned_data['description'] mktype = mks.cleaned_data['mktype'] lat = mks.cleaned_data['lat'] lng = mks.cleaned_data['lng'] Markers.objects.get_or_create(name=name, address=address, description=description, mktype=mktype, lat=lat, lng=lng) return redirect('home.html') else: mks … -
Delete unused parent models
I have these two models: Parent(models.Model): name=models.CharField(max_length=10) Child(models.Model): parent=models.ForeignKey(Parent) name=models.CharField(max_length=10) I am looking for an efficient way to remove parent's with no children. Currently, I am doing it with RAW SQL: from django.db import connection SQL="DELETE FROM app_parent WHERE app_parent.id NOT IN (SELECT id FROM app_child" Which is running two queries and I still want to use Django ORM. With ORM, as well, I am first getting list of children first then check if parent id exists there or not. Is there a faster way of doing that? -
how to create a twitter web client with text classifiers?
where to start ? I want to create a twitter client (website) that you can login and it shows you all of the tweets in your page with text / image classifications (such as business / tech / Religion … so). How do I create a twitter client. is there a way? and how ? cause I think I can't use the stream API for logging into accounts. for starters leave the text / image classifications out. -
Django template tags: using forloop.first tag within conditional tag
This is a continuation of this post. Let's see a customer orders an item on June 3rd. How can I retrieve the latest price of that item before June 3rd, which is $2? I have the following django template tags, but it returns $4. {% for cartitem_ in object.model_customercartitem_set.all %} {% for pricerow_ in cart_item.item_name.model_itemprice_set.all %} {% if price_row.timestamp|date:"U" <= object.timestamp|date:"U" %} {% if forloop.first %} {{ price_row.item_price }} {% endif %} {% endfor %} {% endfor %} Perhaps I have used forloop.first tag incorrectly, so what should the right tag be? Any other solution besides template tag works too. Thanks -
I am trying to update a model using a model form widget. All fields except forms.DateField is available to edit in HTML form
I am trying to update a model using a model form widget. Django form input field not filling the existing datetime value which is saved in the model, but all other fields are available to edit in their respective input fields. The particular form field is given below, publish = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'})) Screenshot of whole form is here, The html form output display is here. It is working without using a widget in another model form, giving the previous date time value filled for edit. Field defined below without widget is below. birth_date = forms.DateField(label='Change date of birth', help_text='(Enter date of birth in "yyyy-mm-dd" format, like 1980-12-31)') Screenshot attached, enter image description here What should i do to bring the previous datetime value saved in the model for edit/update from the html form field, with using a widget. I hope my question is clear. Any solution will be appreciated. Thanks in advance. Regards, Vivek -
getting the pk of other model from one model
models.py class Customer(models.Model): customer_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) class Sell(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) total = models.IntegerField() vat = models.IntegerField() How do get the customer id from Sell model/object? like Sell.objects.get(pk=..) -
Django, Twitter Bootstrap.min.js not loading
I am building a django app using Twitter Bootstrap, my app has been functioning well and all of sudden my app's bootstrap.min.js stops to load and causing drop down menu bar and carousel not to work again. This is the error i get [11/Jun/2018 00:03:35] "GET /static/blog/js/bootstrap.min.js HTTP/1.1" 404 1696 -
Django rest framework jwt token permission
Now I made some api with django rest-framework. And I used JWT for token authentication. In this moment, I have some question about token permission. How can I detect token permission in Django? For example, There is user A and user B. When user A wrote article "test", article "test" can only be edited or deleted by user A. But How can I detect permission about article "test"? Token will be change every time when user login. So detect by Token is not a correct way. I searching google few hours, there is any solution about this. Is there any way to determine user permission by token? Thanks. -
How get data array from JSON object in python?
I have a jquery POST function like this : $.post(data_send_url, { all_letters:["A","B","C"] }, function(data, status){ alert(data); }); In the server side when I access it using request.data in a Django view function I get <QueryDict: {'all_letters[]': ['e', 'r', 'p']}>. How can I get a Python list like all_letters = ['e','r','p'] ? -
Django: request POST value from a ul-li structure
I'm currently working on a select field that is converted via jquery to a ul-li structure so that I can add images to it. (followed this guide: Adding Image To Select List With Cross Browser Compatibility) Everything works fine but now after selecting a fabric/value and the jquery script coming into place, I can't read it out anymore through my view and get the error: File "C:\Users\OEM\AppData\Local\conda\conda\envs\myvir\lib\site-packages\django\db\models\query.py", line 379, in get self.model._meta.object_name cloth.models.DoesNotExist: Fabric matching query does not exist. Template: <form class="form-product-ajax" id="form-product-ajax" method="POST" action="{% url 'carts:update' %}" data-endpoint="{% url 'carts:update' %}"> {% csrf_token %} <!-- Product ID --> <input type="hidden" name="product_id" value="{{ product.id }}"> <!-- Quantity --> <label><u><b>Quantity:</b></u></label> <input name="quantity-field" value="1" min="1" max="9" type="number"> <!-- Fabric --> <label><u><b>Fabric:</b></u></label> <div class="drop-down"> <select name="options"> <option>Select Fabric...</option> {% for item in fabric %} <option value="{{item.name}}" style="background-image:url({{item.fabric_cover.url}});">{{item.name}}</option> {% endfor %} </select> </div><br><br> <span class="submit-span"> <br> <button class="btn btn-success btn-add"type="submit">Add to cart</button> </span> </form> Parts from views.py: def cart_update(request): fabric_form = request.POST.get('fabric-field') quantity_form = request.POST.get('quantity-field') product_id = request.POST.get('product_id') if fabric_form != "Select Fabric...": fabric_obj = Fabric.objects.get(name=fabric_form) ... Jquery: jQuery().ready(function() { /* Custom select design */ jQuery('.drop-down').append('<div class="button"></div>'); jQuery('.drop-down').append('<ul class="select-list"></ul>'); jQuery('.drop-down select option').each(function() { var bg = jQuery(this).css('background-image'); jQuery('.select-list').append('<li class="clsAnchor"><span value="' + jQuery(this).val() + '" … -
Django - 'AnonymousUser' object is not iterable as i used user filter in context processors
I'm passing some kind of filter into the whole project using context_processorts.py but it only works when a user is logged in when there is no user logged in it returns an error. here are my files : context_processors.py def include_user_favs(request, user_favs=None): if request.user.is_anonymous: pass else: user_favs = Favorite.objects.filter(user=request.user) context = { 'user_favs': user_favs, } return (context) and then included in settings.py like : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'fostania.context_processors.include_name_list', 'fostania.context_processors.include_current_user', 'fostania.context_processors.include_dress_need', 'fostania.context_processors.include_all_ads', 'fostania.context_processors.include_new_messages', 'fostania.context_processors.include_user_favs', 'django.contrib.messages.context_processors.messages', ], }, }, ] then that's how i used in my HTML home.html {% if user_favs %} {% for item in user_favs %} {% if item.item == dress %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star-yes.png' %}" title="مسح من الفساتين المفضلة"></a> {% else %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a> {% endif %} {% endfor %} {% else %} <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/star_no.png' %}" title="إضافة إلى الفساتين المفضلة"></a> {% endif %} and here is the error and traceback : 'AnonymousUser' object is not iterable Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django … -
How to set function search_click() more than two request_url(Javascript/jQuery)
I want to know how to set function search_click() more than two request_url, I have a function search_click as below, and we have three user types with different request_url function search_click(){ var type = $('#jsSelectOption').attr('data-value'), keywords = $('#search_keywords').val(), request_url = ''; if(keywords == ""){ return } if(type == "test"){ request_url = "/admin?keywords="+keywords }else if(type == "user"){ request_url = "/admin/user?keywords="+keywords } I tried to change code above with this, but it doesn't work😢 function search_click(){ var type = $('#jsSelectOption').attr('data-value'), keywords = $('#search_keywords').val(), request_url = ''; if(keywords == ""){ return } if(type == "test"){ request_url = "/admin?keywords="+keywords request_url = "/admin_a?keywords="+keywords request_url = "/admin_b?keywords="+keywords }else if(type == "user"){ request_url = "/admin/user?keywords="+keywords request_url = "/admin_a/user?keywords="+keywords request_url = "/admin_b/user?keywords="+keywords } Thanks so much for any advice and assistance. -
In Django, combine User and Group to make one set of auth choices
I have a Django app where I'd like to create a page where an admin user can grant access to something either via a User or a Group. All the results from a search form would combine User and Group results, kind of similar to AD. I'd like all the results to be on one page instead of having separate "Add user" and "Add Group" pages. Then the backend just stores this entity the same way whether it's a user or a group. Has anyone taken a specific approach to this? I've considered: writing a custom Manager of some sort on either User or Group to combine results. I feel this could make it easier to reference for authorization later creating a proxy model of sorts, where each row will contain a user ID or a group id, but not both, though that feels very redundant just keeping them separate models and combining in UI, though that seems like it could get messy Also I would like this to work well with django-guardian which means being able to easily separate them back out to check obj perms for either User or Group. Anyone done this? What approach did you take? -
Django migration model in wrong app
I have two apps, clients and connectors. Connectors has a model file with the models: SessionModel,EntityModel,VersionModel,DjangoSession,UpdateStateModel clients has a model file with the models: ClientModel When I migrate connectors gets the models: SessionModel,EntityModel,VersionModel,DjangoSession, And client gets the models: UpdateStateModel,ClientModel Why is UpdateState migrated to the client. Is there a known bug that could cause this? I have no imports of UpdateState in the clients app. -
form with ModelMultipleChoiceField give only 'object name' even with __unicode__ and __str__
Here is my code : from django.db import models class Stock(models.Model): name = models.CharField(null=True,blank=True,max_length=20) code = models.CharField(null=True, blank=True, max_length=20) def ___str__(self): return self.name def __unicode__(self): return self.name Here is my form : class SubEventForm(forms.Form): name = forms.CharField(max_length=100,label="Name") note = forms.CharField(max_length=200, label="Global Note") stock = forms.ModelMultipleChoiceField(queryset=Stock.objects.all(),label="Stock") Here is the render : i've put __str__ and __unicode__ and the admin vision is correct : So any idea why it's not working ? Regards and thanks -
load javascript in views
I am new to django. Is there any way to load javascript in .py files? I need to access a json, defined in one of my .js files in the middle of one of my functions in a .py file. How is that possible? tnx -
Django save() method not saving
I am using a signal to update fields in the profile table when a new investment is made. Having used a number of print statements inside the update_users_investments function I can see that the function is being called and it is doing the right calculation. However, it is not saving to the database and there is no error. Can you see why it's not saving? And is there a better way to debug the save method? I have looked around and can't see anything, and not knowing why it isn't saving is very frustrating. Elsewhere in my code I use similar signals to save to other tables that appear to work fine. The signal @receiver(post_save, sender=Investment) def update_users_investments(sender, instance, created, **kwargs): user = Profile.objects.get(user=instance.user.user) total_investments = user.total_invested investment = instance.transaction_type * instance.price * instance.number_shares user.total_invested = total_investments + investment user.save() The model to be saving to: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_invested = models.DecimalField(max_digits=5, decimal_places=2) cash_avaliable = models.DecimalField(max_digits=5, decimal_places=2, null=True) The investment model (which is where the signal is coming from): class Investment(models.Model): """Model representing each investment made by users""" user = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) team_code = models.ForeignKey(Team, on_delete=models.DO_NOTHING) transaction_type = models.IntegerField(choices=((-1, "Sell"), (1, "Buy")), help_text="Show whether transaction\ was a … -
I have TemplateDoesNotExist at Django + AWS EB
I make my app with djamgo + aws EB. But I got error message. TemplateDoesNotExist at /item/wish_list/ That works in my development env for now. But that doesn't work in my production env after deploying to EB. What should I do? -
How can I use Django intcomma in integerfield
I'd like to separate numerical values in the form with a comma in my Django project. Then I found the documentation below: https://docs.djangoproject.com/en/2.0/ref/contrib/humanize/ So I added "django.contrib.humanize" to my INSTALLED_APPS setting. And put {% load humanize %} in a template. When I use 'intcomma' like below, it worked. {{ 999999|intcomma }} # 999,999 But It did not work for integer form like below: {{ form.numbers|intcomma }} # did not work. A code was displayed to html instead of numbers like this: <input type="number" name="int_sample" value="100000" id="id_int_sample" My Django version is 2.0.1. -
How to use Factory boy when two foreign keys are pointing to the same table
I am trying to link two Django models using Factory Boy, but I couldn't find a trivial solution to this issue. These are my tables: class Currency(models.Model): id = models.CharField(max_length=3, primary_key=True) class ConversionRate(models.Model): currency = models.ForeignKey(Currency, null=False, on_delete=models.CASCADE) quote = models.ForeignKey(Currency, null=False, on_delete=models.CASCADE) This is the default content of the tables: +--------+ +--------------------------+ |Currency| | ConversionRate | +--------+ +----------+--------+------+ | id | | currency | quote | rate | +--------+ +----------+--------+------+ | EUR | | USD | EUR | 1.2 | +--------+ +----------+--------+------+ | USD | +--------+ I have tried using the following factories: class CurrencyFactory(factory.django.DjangoModelFactory): class Meta: model = Currency id = factory.Sequence(lambda n: ['EUR', 'USD'][n%2]) conversion_rate = factory.RelatedFactory('my_app.factories.ConversionRateFactory', 'currency') class ConversionRateFactory(factory.django.DjangoModelFactory): class Meta: model = ConversionRate currency = factory.SubFactory(CurrencyFactory) quote = factory.SubFactory(CurrencyFactory, id='EUR') rate = 1.2 But when creating building the factory it will throw a integrity error: CurrencyFactory.create() # Error: UNIQUE constraint failed: Currency.id I have also tried adding django_get_or_create = ('id',) within the CurrencyFactory "Meta" section, but that creates an infinite loop. Has somebody faced an issue like this in the past? any suggestion? -
How to see Django logging in production
I'm deploying a Django project in production with, obviously, DEBUG=False. How can I see all Django logs like in development environment? I've configured a logger but I'm only able to see custom logs in a file. Where are the default ones? -
Django - Cannot save new entry to database using view function
here is the view function I am using views.py def favorite_item (request, pk): favitem = get_object_or_404(Item, pk=pk) userfav = Favorite.objects.filter(user=request.user) for items in userfav: if items.item == favitem: items.delete() else: new_entry = Favorite(item=favitem, user=request.user) new_entry.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) the part of deleting already exists row working perfectly : if items.item == favitem: items.delete() but i think the problem is where i try to add a new row , just returns nothing not even raising an error ! else: new_entry = Favorite(item=favitem, user=request.user) new_entry.save() -
How to concatenate model field values in pre_save Django
I don't know how to ask this question so please bear with me. Here is my problem: I have two models Foo and Bar. Following is it's models.py, class Foo(models.Model): foo_code = CharField(max_length=12, blank=True, null=True) class Bar(models.Model): bar_code = CharField(max_length=12, blank=True, null=True) Now, foo_code is let say 123456 then I when I am creating new Bar instance I want bar_code to be {{foo_code}}-{{id of Bar}}, i.e. 123456-01. I am not able get my way around. I thought of using pre_save/post_save but can't think of logic. Please help! -
Creating an AWS deployment package for Python
I'm trying to follow AWS's tutorial: Create a Deployment Package (Python) so I can execute my Lambda function but I'm having trouble understanding the steps. Here are the steps listed from the tutorial: 1 - Open a text editor, and copy the following code: ... 2 - Save the file as CreateThumbnail.py. So I save the file as CreateThumbnail.py - but where do I save the file? In my project directory? 3 - If your source code is on a local host, copy it over. scp -i key.pem /path/to/my_code.py ec2-user@public-ip-address:~/CreateThumbnail.py What is /path/to/my_code.py supposed to point to? A .py file in my project directory? Which file? What is ec2-user@public-ip-address? What do I substitue ec2-user and public-ip-address for? Is public-ip-address the IP address of my website? Any advice appreciated.