Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django duplicates in pagination with order_by() on manytomany field
I am sorting a query on a timefield from a manytomany object but have trouble during pagination. models.py: class Validated(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) views.py: results_list = Validated.objects.filter(job_id_list__user=request.user).\ distinct().order_by('-job_id_list__job_time') My problem is that pagination is messed up and I get duplicates in my pagination output, even when the query output is ok. (other have this problem too) I tried several solutions but my issue does not get solved as sorting is bases on a field from a many-to-many object order_by('job_id_list__job_time') I was thinking of a work-around through creating an annotation to my model by the use of a Model.Manager. Inside this annotation, i try to add the job_time which is a result of a function inside the model. In that way, the job_time would be easily accessible: for i in result_list: job_time_from_model = result_list[i].job_time I would do this as followed but I don't know how to incorporate the %%function logic%% inside the annotation. Is this even possible in this way or is another approach required? models.py: class ValidatedManager(models.Manager): **%%function-logic%%** def date(self, user, id): xlinkdatabase_validated_object = self.get(id=id) job_id_list = xlinkdatabase_validated_object.\ job_id_list.all().order_by('-job_time') date_added = None for item in job_id_list: … -
How to handle for/if loops from Jinja2 in Django Tempates
Working on a legacy project where we're using django templates. How can I translate this for/if syntax from Jinja2 to django: This Jinja example works as intended but syntax error out in django: {% for story in stories if story.status == "published" %} <h1> {{story.title}} </h1> {% empty %} <p>Nothing to see here</p> {% endfor %} This will not work with {% empty %} because the if statement is inside the scope of the for loop. {% for story in stories %} {% if story.status == "published" %} <h1> {{story.title}} </h1> {% endif %} {% empty %} <p> Nothing to see here</p> {% endfor %} -
Why django ugettext_lazy inside a set doesn't always work?
TL;DR I'm having a hard time to dynamically remove the whole Important dates section from django.contrib.auth.admin.UserAdmin when I take translation into account =( security/admin.py ... from django.utils.translation import ugettext_lazy as _ ... class CustomUserAdmin(UserAdmin): exclude_section_set = {_('Important dates')} ... def _filter_sections(self): result = deepcopy(fieldsets) return tuple( section for section in result if section[title_index] not in self.exclude_section_set ) return result django.po ... #: security/admin.py:17 msgid "Important dates" msgstr "Datas importantes" ... Translation is working as far as I can tell. This piece of code removes correctly the section when my browser uses the en language, but it doesn't when my browser is using the pt_BR language. I have (hopefully) isolated the problem. It seems to be the in operation of the set type using ugettext_lazy instances, but I don't understand the behavior. Results of my python console using pt_BR language: >>> _('Important dates') in {_('Important dates')} True >>> print({_('Important dates')}) {'Datas importantes'} >>> _('Important dates') in self.exclude_section_set False >>> print(self.exclude_section_set) {'Datas importantes'} Results of my python console using en language: >>> _('Important dates') in {_('Important dates')} True >>> print({_('Important dates')}) {'Important dates'} >>> _('Important dates') in self.exclude_section_set True >>> print(self.exclude_section_set) {'Important dates'} What am I missing here? PS: I'm using Django … -
Google API Discovery Build
I'm having some trouble with the google api discovery build. If I put the credentials from the flow.credentials into the discovery.build I can get the response from drive.files().list().execute(). However, if I put them into a dictionary like so: data = { "token": credentials.token, ...etc... } And then create the credential with: credentials = google.oauth2.credentials.Credentials(data) Then call the: drive = googleapiclient.discovery.build('drive', 'v1', credentials=credentials) list = drive.files().list().execute() I get an error like below: {'client_secret': 'example', 'token': 'example'...} could not be converted to unicode. Any Ideas? Im guessing one of the values is not a unicode? This is the basic example, I'm actually getting the results from the database but the error happens even if I dont save them to the db and just put them into the {}. Thank you, -
How to upload multiple files using FileField in Django?
So I have a model with this FileField. I was wondering if there is a way to let the user from admin panel, add as many files as he wants. file = models.FileField(blank=True, upload_to='documents') def file_link(self): if self.file: return "<a href='%s'>download</a>" % (self.file.url,) else: return "No attachment" file_link.allow_tags = True -
FORMVIEW and GET
I am trying to clean a FORMVIEW with very little success. I have the following form: FORMS... class BookRequestNumberSearch(forms.Form): q = forms.IntegerField(required=True) def __init__(self, *args, **kwargs): user = kwargs.pop('user') q = kwargs.pop('q', None) super(BookRequestNumberSearch, self).__init__(*args, **kwargs) self.fields['q'].widget.attrs['class'] = 'name2' def clean(self): cleaned_data = super(BookRequestNumberSearch, self).clean() request_number = cleaned_data.get('q')# if request_number: if Book.objects.filter(request_number__iexact=request_number).exists(): try: Book.objects.get(request_number__iexact=request_number) self.add_error('request_number',' Error.') except Book.DoesNotExist: pass return cleaned_data And the View.... class BookRequestNumberSearchView(LoginRequiredMixin,FormView): form_class = BookRequestNumberSearch template_name = 'Book/book_request_number_search.html' def get_form_kwargs(self): kwargs = super(BookRequestNumberSearchView, self).get_form_kwargs() kwargs['user'] = self.request.user kwargs['q'] = self.request.GET.get("q") return kwargs def get_initial(self): init = super(BookRequestNumberSearchView, self).get_initial() init.update({'q':self.request.GET.get("q")}) return init And the HTML <form method="GET" autocomplete=off action="{% url 'Book:procedure_request_number_search_detail' %}" > <div> <h1 class="title">Book Request Number Search</h1> </div> <div class="section"> {{ form.q }} </div> This code works, but I can't figure out how to get Django to invoke CLEAN. I suspect maybe because I'm doing a GET the CLEAN doesn't get recognized? I've spent most of the afternoon playing with variations but no matter what I do CLEAN is just ignored. Thanks for any thoughts. -
Connect Angular4 Frontend to API written in Python
I'm mostly looking for advice or direction to try to figure out a problem. I have a Python API and I need to connect it to an Angular 4 Front-end. Any advice or direction would be appreciated. I can always answer any questions on the subject. Thank you in advance. -
Django Website Not Updating
I have created a new html file in the static/partials folder of my project and trying to see it on my Django website. I can edit older html files in that folder and see those changes, but can not see the new html file, which is pretty annoying. In the main urls.py, I redirect the links to pages in the static/partials folder to the base file, which is redirected to a js file to retrieve template information. This is what the js file looks like that redirects links to the partials html pages (the essential parts): x = angular.module('x', []); . . . x.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when( '/', {templateUrl: '/static/partials/index.html'}). when( '/newpage', { templateUrl: '/static/partials/newpage.html', controller: "ControllerName" }); $locationProvider.html5Mode(true); }]); -
Using Foreign Key on Django model to populate select input
im having problems finding out on the documentation how to solve my problem so im posting here: I have 3 Models one for a class room with its attributes, one for students and the last one a relation of the room and the student. So on the template i want it to show a select button with a option value being the student id and the label being the student name on my models.py i have this: student_id = models.ForeignKey('Student', verbose_name=u"Student") on my template.html i just call the field: {{ field }} and the result that i get is: <select name='student_id'> <option value='1'>Student object</option> </select> is there a way that i can preset the value and label like its done using choices for static data? to something like this: STUDENT_CHOICES =( (model.student.id , model.student.name), ) student_id = models.ForeignKey('Student', verbose_name=u"Student",, choices=STUDENT_CHOICES) let me know if im not clear enough on the question since im fairly new to python and django -
PyCharm debugger disconnects from remote host after short idle time
I've been using the PyDev/PyCharm debugger's remote debugging feature for years, and it's worked just fine. I've been using it for a Django-based project which runs in a Docker container for the last year or so, and it worked just fine with that, too. But ever since a few months ago (possibly due to my code shop's switch to Python 3?), I've had no end of frustration with it because the debugger keeps disconnecting for no reason. I'll be in the middle of a debug session that's going just fine, but then if I let the system idle for about a minute, the debug session suddenly dies, and execution of the request goes on without me. When that happens, I'll see the console output change from: Connected to pydev debugger (build 173.3942.36) To: Connected to pydev debugger (build 173.3942.36) Waiting for process connection... And once this happens, the only solution to get the debugger to reconnect to the running Django server inside my container is to restart gunicorn, either through editing a file to make gunicorn reload itself, or through restarting the gunicorn application with kill -HUP. Further requests made against the server will not trigger any breakpoints unless I … -
Ajax client connecting to a Django (cross domain) works only with JSONP
We have a Django application running in tomcat with Basic Authentication. I want to make cross domain request but only with $.ajax({...dataType: 'JSONP',...}) it works. dataType: JSON doesnt work. Does that mean the server doesnt have CORS enabled. Any tips or pointers to enable CORS in Django -
Delete/Replace aditional items/images when an image is replaced, using an inlineformset
I have 2 models Product and Image: class Image(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) # we need this key to the original image because otherwise we can get/update individual cropped images parent = models.ForeignKey('self', blank=True, null=True, verbose_name='original image', on_delete=models.CASCADE) image = models.ImageField(upload_to=file_upload_to) image_type = models.CharField(max_length=50) The ImageForm is uploaded as Inlineformset in the Product ModelForm. Steps: I upload an image (original) - parent key in the model I crop starting from the original image, 2 other images(base on type) I replace the original Image with another Image (in form) In the database Django (inlineformset)deletes the old original Image record and a add a new record for the replaced Image crop and add in database: if crop_image(disk_path, new_disk_path, size): Image.objects.update_or_create(image_type=type_key, parent_id=parent_id, product_id=product_id, defaults={'image': new_db_path}) My problem is that, when Django change original image by deleting and adding (not updating) I remain in the database with two cropped imaged, linked to the original record that is not there anymore. If Django used an update, my function will work, but it is not. Also 'on_delete=models.CASCADE' doesn't work, because oterwise it should have deleted tem cropped image. So I need somehow do delete this images. -
Syntax for connecting models to admin, Django
I have been learning python for some months, and started tinkering with Django. Before posting this, I read up on the auto-generated 'admin.py'-code on github, as well as googled the matter. It appears my question is a little specific, and I was quite frankly very confused from that specific reading. Thus, I hope asking this adds value to this wonderful community. Question: When connecting a model to the admin page, in admin.py, you first import admin: from django.contrib import admin After this, you import your model. Then, you supposedly connect your model through: admin.site.register(MODEL) What I do not understand is what 'site.register' is. The fact that the line starts off with 'admin.' makes perfect sense, as you are specifying from where the following import (ex. 'admin.function' or 'admin.class') comes from. Had it only been 'admin.somefunctionfromadmin' I would have totally understood this. Now, instead, I am confused as to what 'sites.register' is. Is 'sites' a module, a file, and 'register' a function from within that module? If so, what does that make 'admin'? A package? I have seen lines similar to these throughout Django, and feel a bit confused. Thank you! -
How do I represent two models on the same webpage?
So I have my 3 models from the code below. I represented my courses as a list already and then generated the page below for each course. Now on the same page I want to represent, for that specific course, all course_category fields with their specific lecture_title and content, etc. I tried something.. but I can't figure it out. def courses(request, slug): con = get_object_or_404(Course, slug=slug) return render(request, 'courses/courses.html', {'course': con}) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='') course_category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE) lecture_title = models.CharField(max_length=100) content = models.TextField() link = models.URLField(blank=True) file = models.FileField(blank=True, upload_to='documents') def __str__(self): return self.lecture_title class CourseCategory(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE) course_category = models.CharField(max_length=50, unique=True) def __str__(self): return self.course_category class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE) name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Course.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() {% block body %} <ul> <li>{{ course.study_programme }}</li> <li>{{ course.name }}</li> <li>{{ course.ects }}</li> <li>{{ course.description }}</li> <li>{{ course.year }}</li> … -
Is there an alternative way to request JSON REST API in django?
I currently have a fully working Serializers using the Django REST Framework. I want to be able to parse data or request data that can be used in my django app. I have been using import requests r = requests.get('django_api_url') data = json.loads(r.text) I have no problem using this, but I'm trying to see if there's a better/faster way. -
Django constraint between ManyToManyField and ForeignKey
Consider I have following models: class Cargo(models.Model): name = models.CharField(default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) class Box(models.Model): name = models.CharField(default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.ManyToManyField(Cargo, blank=True) I want to avoid situation when I add some cargo object to box with different owner. For example: cargo = Cargo(owner=1) box = Box(owner=2) box.add(cargo) How to add such a constraint on a model level? -
Get object list with ajax in Django
I'm using ajax in my django aplication, it works well except when I want to get all the registers in a table. I don't know how to send from my 'ajaxview' to the javascript code and then, how to parse the result. Here is my list.html <table> <thead> <tr> <th>id</th> <th>Name</th> <th>Gender</th> <th>Birth date</th> </tr> </thead> <tbody id="clientList"> <!--Here where I want to put the client list--> </tbody> </table> <script> getAllClients(); </script> This is my urls.py from django.conf.urls import url, include from django.contrib import admin from django.urls import path from django.views.decorators.csrf import csrf_exempt from store_app import ajax as ajaxview urlpatterns = [ path('admin/', admin.site.urls), url(r'^listClients/$', csrf_exempt(ajaxview.listClients), name='listClients'), ] This is my ajax.py where I have diferent views than in views.py def listClients(request): data = [] clientlist = clients.objects.filter(clientstatus=1) #Here is where I don't know if I am doing correctly #I don't know how to send the client list or if I have to send it as a JSON #Please help here data.append({'clist':clientlist }) return HttpResponse(json.dumps(data), content_type="application/json") The last code actually work for other stuff, but not to send all the data This is my list.js script funtion getAllClients() { $.ajax( { type: "POST", url: "/getAllClients/", data: "", success: function(result) { … -
Saving data from form to database django
I am trying to add objects to database via form, but nothing happens, information does not appear in db. Here is my code, i've been searching for a few hours and found nothing models.py from django.db import models import os from django import forms from django.contrib.auth.models import User class Projects(models.Model): Cascades = [] for d, dirs, files in os.walk('pd/haarcascades'): for f in files: path = os.path.abspath(f) # формирование адреса name = os.path.splitext(f)[0] file_name_path = () file_name_path = (path, name) Cascades.append(file_name_path) ProjectName = models.CharField(max_length = 15) ProjectOwner = models.OneToOneField(User, primary_key = True) # ProjectType = models.CharField(max_length = 1) # D for Detection , C for Creating Own Cascacde CascadeType = models.CharField(max_length = 150, choices=Cascades) CascadePath = models.CharField(max_length = 150, null = True) ProjectPath = models.CharField(max_length = 100)# for later downloading ProjectReadyFilter = models.BooleanField(default=False)# 0 uncompleted project, 1 - completed forms.py from django import forms import os from .models import Projects class ChosingCascade(forms.ModelForm): class Meta: model = Projects fields = ('ProjectName', 'CascadeType',) views.py class PhotoDetectionProcessView(FormView): template_name = "pd/ChosingCascade.html" success_url = "/pd/ChosingCascade" form_class = ChosingCascade def ChosingCascade(request): def get(self, request): form_class = ChosingCascade() return render(request, self.template_name, {'form_class':form_class}) def post(self,request): form = ChosingCascade(request.POST) if form.is_valid(): post = form.save(commit = False) UserName = request.user post.ProjectOwner … -
Clean Django form fields with same name
Below is a Django form (which has been rendered in a template) whose fields have same names. I want to use the cleaned_data method to clean form data in views.py before storing them in the database. <input name='this-field' value="testValue"> <input name='this-field' value="anotherTestValue"> The problem I'm facing is that if I use form.cleaned_data['this-field'], only the last field's data is fetched i.e. in this example, the field with value anotherTestValue is fetched and cleaned. If I fetch the data using request.POST.getlist('this-field'), all the fields' data is fetched and stored as a list, but, I don't know how to clean it using cleaned_data method. Is there a way to apply the cleaned_data method to the list of field data? -
Why is Django returning a QuerySet even if flat is True?
Can someone please explain me why this is returning me a QuerySet even if flat=True ? images = Image.objects.filter(message_id=messageid).values_list('image', flat=True) I thought that if flat is set to true it would return me ValuesListQuerySet. Image is just the url which is stored in the database as VARCHAR. Maybe I do something wrong ? Thank you for your help. -
Accessing custom thumbnail options in templates
In a Django CMS project with Filer enabled, the Admin dashboard for Filer allows you to create custom Thumbnail Options, similar to defining an alias using easy-thumbnails. How do I access these options in templates? {{ obj.image.thumbnails }} allows me to choose from one of the DEFAULT_THUMBNAILS defined in abstract.py in the Filer package, such as admin_tiny_icon, but I can't for the life of me figure out how to access these custom options defined in the front-end. Thumbnail images are also not automatically created in {{ MEDIA_ROOT }} for these custom Thumbnail Options when adding new images like they are for the DEFAULT_THUMBNAILS. -
Can I change a django model field type without deleting the table?
My question is maybe idiot, but how can I change a model field type in Django without deleting the existing records? I want to change an IntergerField to a DecimalField, the makemigrations command is ok but the migrate says: No migrations to apply. I presume this is because there is already a migration, so Django tells me the migration is already applied. This occurs even if I delete the migrations file. I have read the solution was to delete the concerned rows in the sql table. Is there an other solution? Can we change model field type easily? -
Can't get model to be saved getting error: "TypeError expected string or bytes-like object"
I'm trying to take info from a few models and generate table entries in the model Calendar. I cannot get it to save the Calendar entry. Getting a TypeError. Eventually I would like this system to add calendar entries into the future based of the last scheduled monday. But currently this task will only be performed on mondays. But I would like to be able to project more than one week forward if possible. Template: <form action="{% url 'portal:custom_admin' %}" method="post"> {% csrf_token %} <div style="background-color:red; width:15%;"> <button name="submit">Project</button> DANGER! Only click on mondays, until future projecter can go based off futuremost monday generated into Calendar </div> </form> View with which I am struggling: def custom_admin(request): """ Displays MaxSettings, also Takes time_slots and create a week of it into the future (only should be done on mondays) Note:eventually this should be able to generate from the last monday in the calendar instead of today """ max_settings = MaxSettings.objects.filter() time_slots = TimeSlots.objects.filter() if request.method != 'POST': pass # Do nothing else: # Project A week forward for slot in time_slots: #there will be an if statement for each weekday if slot.day.weekday == 'Monday': new_entry = Calendar( date=datetime.timedelta(days=7), timeslot_A=slot.timeslot_A, timeslot_B=slot.timeslot_B, booked=False ) … -
Heroku worker can't access database
I have a Django project hosted by Heroku with a (postgresql) database, an app that interacts with that database (on a web dyno), and a worker that should also interact with the database. The app asks the worker to do long running tasks in the background, like some database queries. However, I'm having trouble implementing this. I think the problem is that the worker is not authorized to access the database. The specific error I'm seeing is: app[worker.1]: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This doesn't make sense to me as an error coming from the worker. The settings are getting loaded fine- everything on the web dyno works as expected. The only thing I can figure is that the worker doesn't have access to the configured settings, including the database credentials. How do I resolve this? -
django and angular export xlsx file
Good afternoon! hi guys I've been trying to export an xlsx file from my django backend and get it with my Angular front-end. Like I have a button with ng-click that call my function this button is in my template and it is getting my table id 'diogo-test' and passing to my function <md-dialog-actions> <md-button ng-click="doExcel('diogo-test')" class="md-raised md-accent" aria-label="t"> Imprimir </md-button> </md-dialog-actions> this is my angular function in my controller vm.diogoTeste = function(oportunity){ reportProvider.diogoTest(oportunity.id) .then(function(report){ $mdDialog.show({ controller: ["$scope","reportProvider","oportunity","data",function($scope,reportProvider,oportunity,data){ $scope.data = data; $scope.oportunity = oportunity; $scope.doExcel = function(idDOM){ var textRange; var j=0; var tab = document.getElementById(idDOM); // id of table console.log(tab) for(j = 0 ; j < tab.rows.length ; j++) { var tab_text=tab_text+tab.rows[j].innerHTML+"</tr>"; console.log(tab_text) tab_text=tab_text+"</tr>"; } tab_text=tab_text+"</table>"; tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { txtArea1.document.open("txt/html","replace"); txtArea1.document.write(tab_text); txtArea1.document.close(); txtArea1.focus(); sa=txtArea1.document.execCommand("SaveAs",true,"test.xlsx"); } else{ sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); return(sa) } } $scope.today = function(){ return new Date(); } }], templateUrl: staffUrls.templates['diogoTest'], // Vai chamar a url que esta em staff.url.js parent: angular.element(document.body), …