Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find ratio between specific and total value with annotation in Django and store it in each entity?
I am trying to calculate ratio between sales of each product and total sales. I want to store that ratio in every model entity. How can I do that? This is my attempt. It doesn't work. It throws "conversion from CombinedExpression to Decimal is not supported". count_products = Product.objects.count() # total value products = Product.objects.annotate(num_sales=Count('cartitem')).all().annotate(support=Value(F('num_sales') / count_products, output_field=DecimalField())) -
No module named 'allauth.socialaccount.providers.agave'
I want to use Django-Allauth, so I installed as following and it works perfectly in my laptop localhost; but when I pull it in my server, I encounter with the following error: No module named 'allauth.account.context_processors' -
Template tag inside template tag in Django Views
I have a template in which I need to display a specific object based on the loop counter, if the object was the third one, I'd do this: {{content.3.color}} But I need the number to be the loop counter so, how do I do that? I've tried tons of options... {{tags_colors.{{forloop.counter}}.color}} {{content}}.{{forloop.counter}}.{{color}} {{ {{tags_colors}}.{{forloop.counter}}.{{color}} }} Any other ideas? -
Heroku Postgres Django Manage.py Shell
I'm trying to get to the django shell so that I can set some superuser permissions for our staff accounts. We just moved over to heroku, and are using their auto-configured (read: automagical black box) module import django_heroku; django_heroku.settings(locals()) to set database settings. When I open the shell, those config settings aren't run, and I get an error saying that django.db.utils.OperationalError: no such table: user Basically, I can't get the shell instance to use Heroku's nice postgres configurer. Any ideas? Workarounds to manually query accounts and set some params? I've tried to import that same magical module from Heroku as part of the shell and instantiate it, but it only works when run in the settings.py file. I'm trying to not actually log into the postgres instance so that I don't have to open any IP ranges, etc. -
Django - Jinja Boolean Condition
I work with Django 2.0.5 and I'm trying to display on my HTML page a simple code, but it doesn't work. {% if formateur.form_referent == True %} <td scope="row"><span class="fui-check"></span></td> {% else %} <td scope="row"><span class="fui-cross"></span></td> {% endif %}` I also tried "== true", "is true", "is True" but nothing seems to work. When I write {{ formateur.form_referent }} it displays the right value but not inside the condition. It's going automatically to "else" and I don't understand the mistake. If someone can help me, I would really appreciate. Alexandre R. -
Django Postgresql JsonField traversal access
i have the following django models: class UnitOfMeasure(models.Model): unit_of_measure_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, verbose_name="Unit Of Measure") insert_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) class SmartDeviceMeasurement(models.Model): measurement_id = models.AutoField(primary_key=True) data = JSONField(null=False, blank=False) in the data JsonField field, i'll put a json dictionary like showed below: { "3": { "VLN1": 222, "VLN2": 222, "VLN3": 222 }, "4": { "IL1": 222, "IL2": 222, "IL3": 222 } } Every row on my database, it's containing this JSON, this object it's built when the system will read the data from the sensor, and every dictionary key, represents the primary key of the unit of measure (Referenced in an another model that describes the reading variables "ie.: VLN1 has the UnitOfMeasure 3, and so on..."), in this case, the key 3 it's Voltage and the key 4 it's the Ampere. My goal is to create the list of all measurements with a specific unit of measure. I've tried to use the django has_key method, but gives me the entire row data result, in any case, i need to obtain only a "part" of the entire json object, for example, the result might be similar to this one: select data->>'3' AS test from SmartDeviceMeasurement test {"VLN1": … -
AND query against foreign key table in django ORM
Given: class Video(models.Model): tags = models.ManyToManyField(Tag) class Tag(models.Model): name = models.CharField(max_length=20) I know I can use Video.objects.filter(tags__name__in=['foo','bar']) to find all Videos that have either foo OR bar tags, but in order to find those that have foo AND bar, I'd have to join the foreign key twice (if I was handwriting the SQL). Is there a way to accomplish this in Django? I've already tried .filter(Q(tag__name='foo') & Q(tag__name='bar')) but that just creates the impossible to satisfy query where a single Tag has both foo and bar as its name. -
How to enable file in path Django production enviroment IIS + FastCGI?
Im using IIS to publish my Django application, I have a file that we need to be on the root site (not staticfiles or media), for example, http://my-app.com/file.txt, but when I enter in that URL I got a 404 error from Django, my settings file is in DEBUG = False. -
Django - query multi-level foreign keys
I am trying to understand the concept of querying multiple level foreign key tables in Django, and I really hope someone can help me with it. So, I am trying to create a List view in Django which shows players, their scores and some related information like their level of expertise. The database structure is something like below: Players Table ------------- id name <field 1> <field 2> <field N> Then there is a table which stores the player's scores Player Scores Table ------------------- id player_id (this refers to player.id field from table above) score level_id (this refers to a level.id field from table below) And there is a level table like below: Level Table ----------- id level_text What I want is to create a list like below: Player Name Player Score Player Level ----------- ------------- ------------ Blue_Marvel 10000 Maestro Man_At_Arms 51 Noob P_K_In_Debt 1230000 God As you can guess the data for each of these three columns need to come from three different tables. I am very new to Django and can only perform some basic queries. I know I can do Player.object.all() and I get all the players (there is a player model defined). Similarly I can do Level.object.all() … -
Autocomplete to inputs added dynamically
I'm have an autocomplete function in JQUERY and a function that add an input in javascript.The problems is when I add the input, the autocomplete function doesn't work for it. This is my autocomplete function in jquery: $(function() { $(".espaciado").autocomplete({ source:"/inicio/api/get_asesores/", function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui); }, minLength: 1, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } This is my javacript function with which I add the input var id= 2 function AgregarAsesor(clicked_id) { var td = document.getElementById('scrollbar') var asesorID = "asesor_" + id; var cell=document.createElement("div"); cell.id = id; adviserText = document.createElement("input"); adviserText.setAttribute("type","text"); adviserText.setAttribute('class', "ui-widget espaciado"); adviserText.setAttribute('id',asesorID); var addadviser=document.createElement("i"); addadviser.id ="añadir_"+id; addadviser.setAttribute("onclick","AgregarAsesor('"+id+"')"); addadviser.setAttribute('class', 'fa fa-plus espacio'); cell.appendChild(adviserText); cell.appendChild(addadviser); td.appendChild(cell); id = id + 1; }; and this is who the autocomplete is in the input that alredy exists <input type"text" class="ui-widget espaciado" id="adviser_1"> <i id="añadir_1" class="fa fa-plus espacio" aria-hidden='true' onclick="AgregarAsesor(this.id)"></i> How Can I do to add the autocomplete function to the dinamically added inputs ? -
how to use two model forms on one view
I'm still new to django, i'm working on a project were i'll need users to enter some information about houses they want to rent out. I want the users to upload a minimum of 6 pictures and from what i've gathered, the best way to do this on django is to use two models, one collects basic information about the houses and the second stores images of the houses. How am i supposed to code the views.py. i've tried all to no avail. forms.py class MyHouseEditForm(forms.ModelForm): class Meta: model = Myhouses fields = ('name_of_accomodation', 'type_of_apartment','Number_of_rooms', 'house_rent', 'availability', 'location', 'nearest_institution', 'description',) class ImageForm(forms.ModelForm): class Meta: model = Image fields = ('__all__' ) models.py class Myhouses(models.Model): Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) Flat = 'F' Self_contained = 's' Bungalow = 'b' Mini_flat = 's' Duplex = 'D' Room = ( (Flat, 'Flat'), (Self_contained, 'Self_contained'), (Bungalow, 'Bungalow'), (Mini_flat, 'Mini_flat'), (Duplex, 'Duplex'), ) time = models.DateTimeField(default = datetime.now, blank = True) name_of_accomodation = models.CharField(max_length=20) type_of_apartment = models.CharField(max_length=2, choices=Room, ) Number_of_rooms = house_rent = models.IntegerField() house_rent = models.IntegerField() availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, … -
Django: Creating a colour filter
I want to create a filter that returns all products that contain a specific colour. I am using the django-filter package. I can achieve the desired results using a charfilter and entering the colour I want to search. class ProductFilter(django_filters.FilterSet): colour = django_filters.filters.CharFilter(lookup_expr='icontains') class Meta: model = Product fields = ['colour'] Is there a way I can create a dropdown filter with static colour options(e.g. 'blue', 'red', 'green') which will return any products with that colour. So if I have a product who's colour is 'red/green', selecting option red will return that product. -
How to do in-page jumping while using django for pulling posts from a database
I'm trying to crate jump links within a page that are placed on a sidebar using tags as shown here: http://www.webweaver.nu/html-tips/link-within-a-page.shtml However, since i am using django for pulling in different posts from a database, i have to use a for loop because of which i cannot use anchor tags. Is there any way to implement them using django for loops?? <body> <div class="sidenav"> <a href="http://127.0.0.1:8000/admin/login/?next=/admin/">Login</a> <a href="#Plant_Kingdom">Plant Kingdom</a> <a href="#clients">Clients</a> <a href="#contact">Contact</a> </div> <div> <h1><a href="/">Nayan's Files Online!</a></h1> {% for post in posts %} <div> <h1><a href="">{{ post.title }}</a></h1> <p><b>published: {{ post.published_date }}</b></p> <h4><p>{{ post.text|linebreaksbr }}</p></h4></div> </div> {% endfor %} </body></body> </html> enter image description here For example: when the user clicks plant kingdom he should jump to the heading plant kingdom How am i supposed to make anchor tags inside a for loop?? -
Django: Get all instances connected to some set of instances
I have 2 models: class Listing: title = models.CharField() class Location(models.Model): listing = models.ForeignKey(Listing) Given a set of locations, l = Location.objects.all() I want to find l.listing (Which is not the correct command) Something like listings = Listing.objects.filter(listing_set_in=l). It has to be as efficient as possible. -
Beginner going to build an e-commerce platform as my first project
I'm an it engineer and web developer beginner. As my first project I'd like to build an e-commerce platform that scrap products from websites and put them on sale on my platform. My question is what framework/CMS is better to use. I'm thinking of OpenCart because have already web scraping integration. Also I'm thinking of building with Django/Python but this will take longer because I have to learn. Does is worth? Also I don't want to build it on WordPress for personal beliefs. Is Magento a better option rather than the others? Thanks -
Django model form validation
I would like to only take input of A or B from HTML Form I create... But this one did not work. I have tried if type is not 'A' or 'B' or using !=.. nothing worked. What is the right code for it? forms.py class YamlForm(forms.ModelForm): class Meta: model = Form_info fields = '__all__' # fields = ['name', 'type', 'vlan_id', 'rdp', 'ip_master', 'ip_backup', 'vip', 'nat_ip', 'cidr', 'dns', 'dhcp', 'dhcp_pool_start', 'dhcp_pool_end'] widgets = { 'name': forms.TextInput(attrs={'id': 'name', 'name': 'name'}), 'vlan_id': forms.TextInput(attrs={'id': 'vlan_id', 'name': 'vlan_id'}), 'rdp': forms.Select(choices=BOOLEAN_CHOICES), 'dhcp':forms.Select(choices=BOOLEAN_CHOICES) } error_messages = { 'name': { 'max_length': _("This writer's name is too long."), }, } def clean_type(self): type = self.cleaned_data['type'] if not 'A' or 'B': raise forms.ValidationError("Please enter A or B") return type my HTML </div> <div class="row"> <div class="col-25"> <label for="type">TYPE:</label> </div> <div class="col-75"> <span class="text-danger" small>{{ form.type.errors }}</span> {{ form.type }} </div> -
Unable to sort queryset by country__name
I'm using django-countries to set a country in my django model. I would like a have a queryset ordered by country.name, but apparently the following queryset: MyModel.objects.live().order_by('country__name') does not work: Cannot resolve keyword 'name' into field. Join on 'country' not permitted. Further it is - apparently - not possible to use the model Meta option ordering. I could get it ordered in the template by: {% for item in items.all|dictsort:"country.name" %} but would prefer to get this done in the queryset. Did your, dear internet, are aware of a way to get this queryset orderd by country.name? -
django composite key data fetch
I have two tables dim_job and dim_stream when i do python manage.py inspectdb > models.py.......... then below shown models.py(class shown) is created in django........ dim_job table has three attributes where job_name and alias combined as primary key......here alias is also a foreign key referencing dim_stream table alias. dim_stream table has two attributes where alias is primary key........... When i try to execute DimJob.objects.all() shows error.? How can data be fetched from dim_job table?django queries? class DimJob(models.Model): job_name = models.CharField(max_length=50) alias = models.ForeignKey('DimStream', db_column='alias') job_start_time = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'dim_job' unique_together = (('job_name', 'alias'),) class DimStream(models.Model): stream_name = models.CharField(max_length=50, blank=True, null=True) alias = models.CharField(primary_key=True, max_length=50) class Meta: managed = False db_table = 'dim_stream' def __str__(self): return self.stream_name -
Static image url is returned without MEDIA_URL
i followed this tutorial about displaying profile pictures on website, i did everything correctly (i hope so) but instead of returning example.com/media/posters/pic1.jpg it returns example.com/pictures/pic1.jpg (real example) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py def index(request): movies = {'movies' : movie.objects.all()} return render(request, 'index.html', movies) models.py class movie(models.Model): poster = models.ImageField(upload_to='posters') and html {% for a in movies %} <img src="{{ a.poster }}" alt=""> {% endfor %} i added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urls.py file also, i had to use a.poster instead of poster.image.url, it just returned unknow, different django version i assume -
Create a browser files in django
I'm try create a basic browser files some one like this : on click on one folder how show files and open folder.. please a suggest thanks -
django authenticate user from more then one template
I am using django built in login class based view for user authentication, I am also using bootstrap modals for popup login window in other pages, but the problem I am facing is while using popup login window, if form contains errors then it redirect me to main login page with errors but what I want it to show the error in that window only. Here is my template <div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Login Required</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} <input class="form-control" type="text" name="username" placeholder="Email or Phonenumber"> <input class="form-control" type="password" name="password" placeholder="password"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input class="btn btn-primary" type="submit" name="" value="Login"> </form> </div> </div> Here is my url url(r'^login/$', auth_views.LoginView.as_view(template_name= 'accounts/registered/login.html', redirect_field_name='next',), name='login'), Thanks for giving me time. -
Django does not Send Email on TestCase, but It Does on Shell
I have a strange issue. Whenever I try to send an email from a TestCase, I cannot receive it. However, I try the same approach on Django shell and it successfully send the email. Here is my TestCase: class DefaultEmailTestCase(TestCase): def test_send(self): msg = EmailMessage( "Test Message", "This is a test message.", to=["foo@bar.com", "foo@baz.com"] ) val = msg.send() self.assertEqual(val, 1) It completes successfully, but I do not receive the email. And here is what I do on Django's shell: from django.core.mail import EmailMessage receivers = ["foo@bar.com", "foo@baz.com"] msg = EmailMessage( "Test Message", "This is a test message." to=receivers ) msg.send() And I successfully receive the message. Here is my settings in order (with dummy info): EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_HOST = "foo.bar.com" EMAIL_PORT = 465 # This is the port that my email provider uses. EMAIL_HOST_USER = "foo@bar.com" EMAIL_HOST_PASSWORD = "123456" # EMAIL_USE_TLS = True # Django raised an error saying that I cannot use both TLS and SSL. So I commented it out. EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = "Bar Testing Message <foo@bar.com>" Both the test case and Django shell uses my development settings, so they are the same. I do not have any idea why this does not work. Thanks … -
I made a comment model in Django. How would I go about making a comment reply model?
Here is my comment model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.TextField(max_length=100) message = models.TextField(max_length=1500) timestamp = models.DateTimeField(auto_now_add=False) How would I make another model that can reply to this comment model, then reply again to the replied comment. Please let me know if you need anymore detail on the question. -
Django (DRF) not showing CORS POST-ed data (from React frontend)
I am using a React frontend, communicating with a DRF (Django Rest Framework) backend. Currently both are running on their own development server, so they are running on separate domains. I am sending data from the frontend to the backend, using the POST method, using Axios to send the request. The code I use can be seen below. The problem: Django doesn't seem to be receiving the POST-ed data. As you can see in the code below, I try to print out the received data, but this is what I see in the console: [12/Jun/2018 13:33:17] "OPTIONS /order/create HTTP/1.1" 200 0 request.POST: <QueryDict: {}> [12/Jun/2018 13:55:47] "POST /order/create HTTP/1.1" 200 2 (it seems to be normal that the printed information comes first in the console, and the line for that POST request after that. Even though the print statement is executed by the POST request, not by the OPTIONS request. This confused me a bit initially.) What I have tried already: I've tried to add the following header: headers: {'Content-Type': 'application/json'} I've tried adding: withCredentials: true (commented out in my code, at the bottom if this post) Initially this gave me an error about the response to the preflight request … -
Rank of users - Django
How can I rank the users based on their total number of posts. example First : total number of posts 1-10 Second : total number of posts 11-20 Third : total number of posts 21-30 models.py from django.db import models User = get_user_model() class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title def count_posts_of(user): return Post.objects.filter(author=user).count()