Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a pre-commit hook that will track errors from my Django code before I push to my server
I've only recently found out what a pre-commit hook is, and from what I understand it's a file (.git/hooks/pre-commit) that tracks my code for errors before the changes are committed to my server (DigitalOcean). So I want to make this file but I don't know what code to add to it. I've tried to find example files of pre-commit for Django projects but cannot find any. Advice appreciated. -
Update chart.js after form submission and page reload
I have a chart.js bar chart that pulls data via an ajax call to a Django APIView. The ajax call returns one dictionary with a stack of data inside I use to customize the chart. Here's the chart.js code: var current_year = '{% url "saveskore:api-current-year-savings" %}' $.ajax({ url: current_year, type: 'GET', cache: false, dataType: 'json', success: function(data) { var ctx = document.getElementById('current-year-chart'); var chart = new Chart(ctx, { type: 'bar', data: { labels: data['dates'], datasets: [ { label: data['income_label'], backgroundColor: "#8e5ea2", data: data['income'], }, { label: data['expense_label'], backgroundColor: 'green', data: data['expenses'], }, { label: data['savings_label'], backgroundColor: "#3e95cd", data: data['savings_goal'], }, { label: data['avail_label'], backgroundColor: "#pink", data: data['avail_to_spend'], }, ] }, options: { legend: { display: false }, title: { display: true, text: 'Savings for ' + data['year'] } } }); } }); Works great. Looks great. But! I have a django formset on a separate page that updates the table data that the chart pulls from. When I update the data in the formset and submit, redirecting to the chart page ... NO UPDATE OCCURS. If I make some code change or otherwise reload the browser, VOILA, the chart updates. I have read about either cache=false and chart.update(), but find … -
'NoneType' object is not callable on Django 2.0
I am following Obeying the Test Goat by HJWP and deploying my Django app on an Ubuntu Droplets and I come across a problem running my functional test (unit tests all clear). Details: Python 3.6, Django 2.0.1, Selenium, gecko driver 19.1, remote Unbuntu 16.04, local win10 git bash I’ve been trying to perform a function test both locally and against the server and got the results below: Local Test Result File "C:\...\.virtualenvs\superlists\lib\site- packages\django\core\handlers\base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable Against Remote Server Result: ValueError at /lists/new The view lists.views.new_list didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://midsummerseve.life:8000/lists/ I think based on the above results, there has to be something wrong with the view function which in this case is def new_list(request): list_ = List.objects.create() Item.objects.create(text=request.POST['item_text'], list=list_) return redirect(f'/lists/{list_.id}/') But I have no idea where to further and what makes it return a None object. Could it be the issue of the models of list and item? Migration steps seem quite smooth though. class List(models.Model): pass class Item(models.Model): text = models.TextField(default='') list = models.ForeignKey(List, on_delete=models.CASCADE) I am also wondering why the server would process a GET request … -
Django foreign key select field empty
I've been working on a small django website as I learn django. According to the documentation when you create a form class with a meta class that points at a model with foreign key fields, it'll render those fields as select inputs. In my application I have 3 models, client test, and record where record carries two foreign keys, each of whom point to client and test respectively Models.py class Client(models.Model): first = models.CharField(max_length=264) last = models.CharField(max_length=264) DOB = models.DateField() def __str__(self): return self.first + " " + self.last class Test(models.Model): test = models.CharField(max_length=264) fee = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.test class Record(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) date = models.DateField() def __str__(self): return str(self.date) + " " + str(self.test) + " for " + str(self.client) Form.py class NewLabRecord(forms.ModelForm): client = forms.ChoiceField( label='Client ID', widget=forms.Select( attrs={'class': 'form-control'})) test = forms.ChoiceField( label='Test ID', widget=forms.Select( attrs={'class': 'form-control'})) date = forms.DateField( label='Test Date', widget=forms.DateInput( attrs={'class': 'form-control'})) class Meta: model = models.Record fields = '__all__' I render NewLabRecord at the top of my index view for records. The idea is to create a record and redirect back to the page (therefore seeing it in the list of records). Presently, I'm … -
Using existent Windows Shared Drive with Django instead of using MEDIA Files upload
I'm building a Django web application for my team. We share a drive that contains all of our documents. Is there a way for Django to mirror a shared drive instead of re-uploading everything using MEDIA FILES? Can we keep saving our files in the shared drive or do we have to upload them through Django every time? -
Is there a way to debug line by line code written in a view function of django on the website itself?
I have a view function in a django application on a webpage that a user himself writes code for (using a framework known to them). After uploading the code, they are redirected to the webpage for which they have written the code for. I want to have a way to visualize line by line the python code that is running on the view function as it gives a clear indication to the user how their code works. Is there a way to debug code on the website itself? -
Route requests with query parameters in Django without prepending with a backslash
I'm trying to process requests that have query parameters similar to the following url: http://127.0.0.1:8080/foo?bar=-capacity. I've done quite a bit of trial and error with Django's url patterns and regex but no success so far. My regex knowledge is admittedly lite. This pattern url(r'^foo(.)$', views.QueryFoo.as_view()), will process the above request but the problem is it grabs regular get requests like the following: http://127.0.0.1:8080/foo. I can add a backslash to the url pattern like this url(r'^foo/(.)$', views.QueryFoo.as_view()), which seems to be the Django norm but then I have to handle get requests from two separate urls. Any suggestions? -
Django Inline Copy Entry
I have been browsing many questions about Django inline, but can't quite find how to do this. I am using Django Nested Admin and am wanting to see how I can copy an existing row in the admin so that when I click on "Add another", it creates the new one as a copy. Here is an example: As an example...let's say I am creating a set of recipes. In these recipes, I want to create "variations" with the ingredients. So if I had "Strawberry Smoothie", I want to create a "variation" that has both the regular option, as well as a lactose-free option. So I have my main model called "Recipe": class Recipe(models.Model): name = models.CharField(max_length=128) instructions = models.TextField(blank=True) From here, I then need to add the ingredients, so in my admin.py, I have added: class RecipeAdmin(NestedModelAdmin): model = Recipe inlines = (VariationsInline,) Using the Nested Inline, I have an inline that allows me to add as many Variations, where each variation can then have as many ingredients inside of it. The issue I am running into is that sometimes these variations have 10+ ingredients (and their respective quantities) and I have to remake those for each variation I … -
Django Formset Ajax
This is a very complex process...I have a formset (using jquery formset) in django and I would like to allow users to add forms and input data. Which are all good. The problem is when I try to include ajax. when the input data is changed, there will be a suggestions on what the currency inventory is. The ajax would work on one level only. SO if I add two forms or more forms, inventory number wouldn't show for Here is the code $('#form-inline tbody tr').formset({ addText: 'add link', deleteText: 'remove', prefix: 'positions' }); {% for forms in formset %} $(".{{forms.product.value}}").change( function(){ var symbol = $(".{{forms.product.value}} option:selected").text(); $.ajax({ url: "{% url 'inventory:get_inventory' portfolio_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $(".{{forms.id.value}}_ouput").html('Inventory Left'+' ' + data.inventory); }}); }); {% endfor %} html {% for forms in formset %} {{ forms.id }} <tr class="dynamic"> <td style="width:200px" class="{{forms.stock.value}}">{{ forms.product.errors }} {{ forms.product}} </td> <td>{{ forms.inventory.errors }} {{ forms.inventory}} </td> <td>{{ forms.price.errors }} {{ forms.price}} </td> <td style="padding-left: 10px;"> {{ forms.total.value|floatformat:2}} </td> <td style="padding-left: 10px;padding-right: 10px;"> {{ forms.weight.value|floatformat:2}}% </td> {% for op in forms.operation %} <td style="padding-left: 10px;"> {{ op}} </td> {% endfor %} <td>{{forms.operation.errors}} {% if … -
Including a listview in another listview for categories
I'm using a listview that gets me the category-names from one model(Choice) to render it to the choice_list.html On that choice_list.html I'm trying to include another list_view using an absolute url and slug field to only get the data back that belongs to that category. The problem so far is that it includes the second page fabric_list.html but it doesn't bring the data belonging to the view from that html file, instead it has the queryset as from choice_list.html. If I look at fabric_list.html directly, it show's me all the data I'm asking for at the moment, but I can't include it to another html file somehow. Urls.py urlpatterns = [ url(r"^detail/(?P<slug>[\w-]+)/$", views.CategoryListView.as_view(), name="cloth_detail"), ] Views.py class CategoryListView(ListView): model = Choice def get_context_data(self, **kwargs): context = super(CategoryListView, self).get_context_data(**kwargs) context.update({ 'choices': Choice.objects.order_by('category') }) return context class ClothListView(ListView): queryset = Fabric.objects.all() template_name = 'cloth/fabric_list.html' def get_queryset(self): return Fabric.objects.order_by('name') Models.py class Choice(models.Model): category = models.CharField(max_length=120) slug = models.SlugField(max_length=120, unique=True) def get_absolute_url(self): return reverse('cloth:cloth_detail', kwargs={'slug': self.slug}) def __str__(self): return self.category class Fabric(models.Model): AVAILABLE = [('available','available'), ('unavailable','unavailable'),] name = models.CharField(max_length=120) the_choices = models.ManyToManyField(Choice) availablity = models.CharField(choices=AVAILABLE,max_length=120) fabric_cover = ThumbnailerImageField(upload_to='fabric_images',blank=True, default='/placeholder/neutral_book_cover.png', resize_source=dict(size=(200, 200))) def __str__(self): return self.name html example: choice_list.html {% extends "base.html" %} {% block … -
Django rest framework hyperlinkrelatedfield for one table using primary key
I have a table called 'users' and 'location' . users table has a foreign key that relates to location table. I have a users serializer to get the JSON. What would I do to get the hyperlinks for the users table using its primary key. In django rest framework documentation, I couldn't find a solution. I tried using hyperlinkrelatedfield. But still I couldn't achieve this . can someone help me in finding the solution? -
URL pattern name as parameter in template
In my project I have several user types and each of them has separate URL pattern for signup process. I use the same template to render the signup form for each of this types of users and only pass form itself as parameter to template. The problem I'm having is I can't wrap my head around how to dynamically pass url pattern name to template so that every time Submit is clicked appropriate url pattern is called? <form class="form-horizontal" action="{% url 'appropriate_url_pattern' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> ... rendering a form here... <input class="btn btn-default" type="submit" </div> </form> -
Trying to create hyperlink from Google Map lat/lon to individual posts Django
I'm currently trying to create hyperlinks to posts that are currently displayed on a google map. The map shows each post based on its latitude and longitude. The code below links to the title of each post, but the issue with that is the title will often times be uppercase or have spaces. Here's what I have: ` <div class="court-listing" id="map-canvas"></div> <script> function initialize() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 40.674, lng: -73.945}, zoom: 12, styles: [ {elementType: 'geometry', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.stroke', stylers: [{color: '#242f3e'}]}, {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'poi.park', elementType: 'geometry', stylers: [{color: '#263c3f'}] }, { featureType: 'poi.park', elementType: 'labels.text.fill', stylers: [{color: '#6b9a76'}] }, { featureType: 'road', elementType: 'geometry', stylers: [{color: '#38414e'}] }, { featureType: 'road', elementType: 'geometry.stroke', stylers: [{color: '#212a37'}] }, { featureType: 'road', elementType: 'labels.text.fill', stylers: [{color: '#9ca5b3'}] }, { featureType: 'road.highway', elementType: 'geometry', stylers: [{color: '#746855'}] }, { featureType: 'road.highway', elementType: 'geometry.stroke', stylers: [{color: '#1f2835'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'transit', elementType: 'geometry', stylers: [{color: '#2f3948'}] }, { featureType: 'transit.station', elementType: 'labels.text.fill', stylers: … -
django imagefield form, how can I display image in the form
I have a Django ImageField model that I would like to add in the form to display image. How can I do that ? I tried this but the answer is incomplete. Display image from ImageField by means of form class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""<img src="$link"/>""") return mark_safe(html.substitute(link=value)) class EmployeeFaceImageUploadForm(forms.ModelForm): face_image = forms.ImageField(widget=PictureWidget) class Meta: model = Employee fields = ("face_image",) there are errors. Im not sure how to complete this. NameError: name 'Template' is not defined NameError: name 'mark_safe' is not defined AttributeError: 'Template' object has no attribute 'substitute' My main goal is to have image shown in the form which has the ImageField field -
Django Form becomes Invalid When Field is Disabled
I am developing a django application for tracking a list of (music) albums that I've listened to, and when I've listened to them. I am trying to come up with how to render a form for creating a Listen (one of my models) for a specific Album (another model). The relevant part of Listen is very simple: class Listen(models.Model): """A model representing an instance of listening to an album. """ album = models.ForeignKey(Album, on_delete=models.CASCADE) listen_date = models.DateField(default=datetime.date.today, null=True) I have a generic CreateView for creating a view with no pre-populated data: class ListenCreate(generic.edit.CreateView): """View for adding a new Listen. """ model = Listen form_class = ListenForm template_name = 'tracker/generic_form.html' Then ListenForm looks like: class ListenForm(forms.ModelForm): class Meta: model = Listen fields = ['album', 'listen_date'] I've created a view that then is meant to add a listen for a specific album, where the album is deduced from an artist and album name in the URL: class ListenCreateForAlbum(generic.edit.CreateView): """View for creating a listen for a specific album. """ model = Listen form_class = ListenFormForAlbum template_name = 'tracker/generic_form.html' def get_initial(self): initial = copy.copy(self.initial) # Get the initial Album using the artist/album names in the URL initial['album'] = Album.objects.get( name__iexact=unquote_plus(self.kwargs['album_name']), artist__name__iexact=unquote_plus(self.kwargs['artist_name'])) return initial Now, … -
Django how to do aggregation on three tables
I'm doing now educational exercise about django ORM. Need to show total values of orders for particular customers for chosen Supplier on Northwind database, the database diagram can be found here: Northwind database diagram So far I did: QuerySet of ORDER_DETAILS objects that have products made by SUPPLIERS.supplierid = 1 >>> od =OrderDetails.objects.filter(product__in=(Products.objects.filter(supplier=(Suppliers.objects.get(supplierid=1))))) QuerySet of ORDERS objects that have ORDER_DETAILS products made by SUPPLIERS.supplierid = 1, without duplicated ORDERS Objects >>> o = Orders.objects.filter(orderdetails__in=od).distinct() Firstly I'm not sure if those two statements are correct? Secondly I have QuerySet of ORDERS objects that are about products manufactured by chosen supplierid and can't find a way to aggregate it to get total values of orders for particular customers. -
How to hash text with md5 in django? [duplicate]
This question already has an answer here: python django unsalted md5 password hash format 3 answers I need to generate some key or 'token' based in the combination of some email and password sended. I want this in MD5 but I don't know what plugins or libriries or something help me to do this... The equivalent of what I want in php is the next: <?php $email = $_POST['email']; $pass = $_POST['pass']; $token = MD5($email.'-'.$pass); ?> How can I do this in Django? -
Django template renders all my files at once
I am stuck with this issues for a while now. It goes like this: I have a model with lectures. I want that for every lecture to be able to upload multiple files, so I created a model that has FileField. So in my template, I want that for every lecture, the files would be displayed and downloadable as well. The Issue is that every lecture displays all the files that have ever been uploaded in the admin panel. Here is my code: class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), ), default=0) lecture_title = models.CharField(max_length=100) content = models.TextField() files = models.OneToOneField('FileUpload', on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return str(self.lecture_category) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) def __str__(self): return str(self.files) def file_link(self): if self.files: return "<a href='%s'>download</a>" % (self.files.url,) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'File Download' <ul> {% regroup lectures by get_lecture_category_display as category_list %} <h3>Lectures</h3> <ul> {% for category in category_list %} <strong> <li>{{ category.grouper }}</li> </strong> <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in files %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> … -
Override the default UserAttributeSimilarityValidator error message in django
I am trying to override the default UserAttributeSimilarityValidator error message in django, but i don't know how? -
Is it possible to monkey patch Django's reverse?
Some of our urls include #. These are used for reverse lookup, both using reverse and the {% url template tag (which uses reverse internally). Django 1.8 used to leave it alone, 1.11 now encodes it to %23. Is it possible to put a monkey patch wrapper somewhere and have it be used everywhere without fail? Here's the wrapper I have: def patch_reverse(func): def inner(*args, **kwargs): print "inner reverse" url = func(*args, **kwargs) return url.replace("%23", "#") return inner from django.urls import base base.reverse = patch_reverse(base.reverse) The print statement is so I can see if it's actually running. I've tried putting it in settings, the __init__ of the first installed app, and in the urls of the first installed app. Nothing works. -
Regrouping in a Django template after the first regroup
I'm trying to create a page that has a group of photos, categorized by event, then within the event, by date. Currently, in my view, I am doing this: photos = Photo.objects.all().order_by('event') Then, in my template, I am doing this: {% regroup photos by event as event_list %} {% for event in event_list %} <h6 class="event-title"> {{ event.grouper|safe }} ({{ event.grouper.date }}) </h6> {% for photo in event.list %} <img data-src="{{ photo.thumbnail.url }}" alt="{{ event.grouper|safe }} ({{ event.grouper.date }})" class="img-responsive img-thumbnail" /> {% endfor %} {% endfor %} Is there a way I can group the photos once again by photo.date_captured? Would it be better to do this in the view? -
How do I grab the first objects from a Django queryset?
execution_list = JobExecution.objects.filter(job__name=job_name).order_by('-build_id')[:50] last = execution_list.pop(1) print last.id I've also tried execution_list[0], which throws another queryset error. How do I i just grab the first object from the queryset? I am aware that I can just append .last() to the query, but the problem is I need the full list as well as the first item. What am I doing wrong here? Error: 'QuerySet' object has no attribute 'pop' -
Django Multiple Files Upload Using Ajax without forms
I have an aplication in Django 2.0 where one user can upload many images of their diplomas at the same time but also, I need to make this with ajax so the page will not reload. This is my models.py class diploma(models.Model): user = models.ForeignKey(user, on_delete=models.CASCADE, null=True) diploma=models.ImageField(default='nopic.png', null=True) def __str__(self): return self.diploma And this is my file input in my template upload.html <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <input type="file" id="images" name="images[]" multiple accept="image/jpg,image/png,image/jpeg,image/gif"> <a onclick="uploadWithAjax()"> Upload Images </a> If you notice, there's no Form html tag. Just an 'a' link that calls the function uploadWithAjax(). This is my script with the uploadWithAjax() function function uploadWithAjax() { var files = $('#images')[0].files; $.ajax( { type: "POST", url: "/UploadImages/", data: "", //I DON'T KNOW WHAT DATA I HAVE TO PUT HERE success: function(result) { alert('IMAGES UPLOADED'); } }); } I Think I have to send the 'files' variable in the 'data' atribute of ajax, but I'm not sure becouse there are files and dont normal inputs. Please help. This is my ajax.py file, where I recive the images def UploadImages(request): diplomas = request.FILES['images'] #I don't know if this is correct I didn't finish the view becouse I don't know how to continue or how … -
Using django orm to update a table without deleting relations
I have this two related django models class Item(models.Model): item_nbr = models.IntegerField(primary_key=True) created = models.DateTimeField(auto_now_add=True) item_nbr_desc = models.CharField(max_length=155) class SetItem(models.Model): set_id = models.CharField(primary_key=True, default='', max_length=12) set_nbr = models.IntegerField() items = models.ForeignKey(Item) Im running an script (periodically) to read the Item table from another database and to update the django db database. Im using the django orm framework in this task script.py from app.models import Item item_table = pd.read_sql(__) item_table = some_transformations(item_table.copy()) #I remove all the Items that will be updated Item.objects.filter(item_nbr__in=item_table.item_nbr.unique()).delete() item_table_records = item_table.to_dict('records') item_instances = [] fields = item_table.keys() for record in item_table_records: kwargs = { field: record[field] for field in fields } item_instances.append(Item(**kwargs)) Item.objects.bulk_create(item_instances) # update the new rows the problem is that the setItem table its deleted each time that I delete the Items related (because the on_delete=models.CASCADE behavior). I want to update the items not erasing the setItem related rows, and i don't want to change the on_delete default behavior because just in this script I need to upload a whole table, its possible that i want to delete a Item in another context and i hope that the cascade behavior is working. what can i do? its there a bulk update function that might perform … -
Django REST framework queryset object has no attribute pk
I am building a larger Django-based web app, but I have a blocking issue with an API view that should return some data. I the application I have a model (mail.models.Message) and a matching serializer and viewset. For a reporting feature, I need to get filtered set of results and have therefoer created a seperate rest_framework.views.APIView for the purpose of the reporting. The model is located in one app and the reporting is in another app. Here is the model: class Message(models.Model): class Meta: ordering = ('-timestamp',) get_latest_by = 'timestamp' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) from_address = models.CharField("From", max_length=511, blank=True, default="", db_index=True) from_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) to_address = models.CharField("To", max_length=511, blank=True, default="", db_index=True) to_domain = models.CharField(max_length=255, blank=True, default="", db_index=True) subject = models.TextField(blank=True, default="", db_index=True) client_ip = models.GenericIPAddressField("Client IP", db_index=True, null=True) mailscanner_hostname = models.CharField(max_length=255, db_index=True) spam_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) mcp_score = models.DecimalField(db_index=True, default=0.00, max_digits=7, decimal_places=2) timestamp = models.DateTimeField(db_index=True) size = models.FloatField(default=0) token = models.CharField(max_length=255, null=True) mailq_id = models.TextField("Mailqueue identification", null=True) whitelisted = models.BooleanField(db_index=True, default=False) blacklisted = models.BooleanField(db_index=True, default=False) is_spam = models.BooleanField(db_index=True, default=False) is_mcp = models.BooleanField(db_index=True, default=False) is_rbl_listed = models.BooleanField("Is RBL listed", db_index=True, default=False) quarantined = models.BooleanField(db_index=True, default=False) infected = models.BooleanField(db_index=True, default=False) released = models.BooleanField(db_index=True, default=False) def __str__(self): …