Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - Creating custom queryset for RelatedManager
I tried about 25 Stackoverflow links and nobody seems to have a working solution for this problem. I created a custom queryset like this: class ProjectQuerySet(models.QuerySet): def get_active(self): from apps.projectmanagement.models import Project return self.filter(active=True) class ProjectManager(models.Manager): def get_queryset(self): return ProjectQuerySet(self.model, using=self._db) This works great if I start at the model like Project.objects.get_active() But if I want to use it in a relation, no luck so far: employee.projects.get_active() I always get this error: AttributeError: 'ManyRelatedManager' object has no attribute 'get_active' What I've tried so far: 1) I read that use_for_related_fields = True in the manager class is deprecated. Does not work anyway on django v2.1 2) Adding this in my model, as half the internet states: class Project(models.Model): ... objects = ProjectManager() class Meta: base_manager_name = 'objects' 3) Trying to avoid the RelatedManager and to work with a queryset: employee.projects.all().get_active() Any ideas what I've been doing wrong? And how would I solve this? Can't be too hard, right? Thx! Ron -
How to get the current request object in python
I have function in views.py call operational , operation has a request object , from operation i call another function banks_data without passing the request object , from banks_data i call 3rd function call check_duplication, from check_duplication i want to return a error message to the html page which from which i called operation , is there any way to get the current request object if i didnt send it to the function or to send the message back to the html page with out sending some kind of return code to the first operation function? Thanks, Nir -
Django complex query filter through reverse relationships
I have two models: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(db_index=True, max_length=20, unique = True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(db_index=True, max_length=256, null=True) friends = models.ManyToManyField("self", related_name = 'friends', symmetrical=True) For search purposes, I need a query to: SELECT all friends and friends of friends (excluding self) WHERE username__startswith(query) OR full_name__startswith(query) I can't figure out how to do that given the structure: need to access friends, then friends of friends and reverse User objects. -
Set page name on navbar in django
I have a 'base.html' that other page's style uses it. This file included a navbar. I want to set the name of the page on the navbar; For example, I have 'setting' page, I want to set 'setting' on the navbar. How can I do this? Thanks -
how different hash is getting created for same data everytime?
I am adding hash of Account model object to one column of Account object. I am retrieving data from some target and creating Account object for that.Before saving object I am calculating hash of Account object and assigning to field hash_value. Then I am checking whether hash present in Account against hash_value field. To avoid unnecessary updation. But every time before insertion generated hash is different . Why? I tried comparing each field in obj coming from target and Account present..those are same. # Account model class Account(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) application_id = models.ForeignKey(Applications, related_name="account_application_id", on_delete=models.CASCADE) employee_id = models.TextField(null=True) username = models.TextField(null=True) display_name = models.TextField(null=True) mail = models.TextField(null=True) department = models.TextField(null=True) company = models.TextField(null=True) description = models.TextField(null=True) entitlements = models.TextField(null=True) hash_value = models.BigIntegerField(null=True) def __hash__(self): hash_sum_value = hash( ( # self.uuid, no two uuid can be same str(self.application_id.uuid), # include only uuid of application in hash str(self.employee_id), str(self.username), str(self.display_name), str(self.mail), str(self.department), str(self.company), str(self.description), str(self.entitlements) ) ) return hash_sum_value # checking hash present to avoid unnecessary updation. obj = Account() # some code to add values in obj if entity_type == 'account': try: obj.hash_value = hash(obj) except TypeError: logging.info("Account info " + str(obj)) logging.error("Unable to hash object: " + … -
What is the better way of getting API data, rendering it and in general working with it
I am working a lot with API data in my Django applications lately. I have written some APIs and I am trying to get a better understanding of best practices. So as I understand it, I can get my API data in two ways. I can either get my data through my django view out of my database, turn it into JSON format with json.dumps, pass it to my template, save it into a javascript variable and from there pass it to my .js file where I can use it as I please. Alternatively, I think I can make an API call from my .js file and get the data directly from my API without taking the road through my database. But what is better in regards to performance and especially security? The way I imagine it is that the second way (js-way) might be better in terms of performance whereas using the database-approach might be safer? I simply do not know. Let's for instance assume I have an API that I only want to use internally without public access. What would be the way to go? Or let's say I have a public API. Does that change the equation? … -
DRF show ForeignKey field choices
What's the best way to go about letting a frontend user know about ForeignKey field choices using Django Rest Framework? In the Browsable API these fields have a dropdown widget with all the existing objects as choices. A custom metadata class could return the available choices for each field but the request could be very slow if there are millions of objects. Suppose you have a model similar to below and there's only 5 unit objects. How would you go about listing the unit choices? class OrderLine(models.Model): order = models.ForeignKey(Order) product = models.ForeignKey(Product) unit = models.ForeignKey(Unit) -
Django signals doesnt save models with custom params
I have a custom user model CustomUser and related models Employee with Foreignkey field to user. class Employee(models.Model): """Employee information.""" user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) first_name = models.CharField("first name", max_length=32, blank=True) last_name = models.CharField("last name", max_length=32, blank=True) I try to create Employee instance after user registration using post_save signals with fields first_name and last_name imported from my user model fields. @receiver(post_save, sender=CustomUser) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: if instance.first_name and instance.last_name: employee = Employee.objects.create(user=instance, first_name=instance.cleaned_data['first_name'], last_name=instance.clened_data['last_name'] ) else: employee = Employee.objects.create(user=instance) But always created model with blank field. What is the reason for this and what needs to be changed? p.s. I need the same filds at both models for some reason. -
Multiple file uploads not working in Form Wizard Django
I am working on a project that requires an upload of multiple images in one of the form wizard steps. The form wizard also has several models used for the wizard which I think complicates the whole process the more. Here is the relevant code: models.py from django.db import models from django.contrib.auth.models import User from location_field.models.plain import PlainLocationField from PIL import Image from django.core.validators import MaxValueValidator, MinValueValidator from listing_admin_data.models import (Service, SubscriptionType, PropertySubCategory, PropertyFeatures, VehicleModel, VehicleBodyType, VehicleFuelType, VehicleColour, VehicleFeatures, BusinessAmenities, Currency ) class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='list_owner' ) def __str__(self): return self.listing_title def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) return "listings_pics/%s-%s" % (slug, filename) class ListingImages(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) image_url = models.ImageField(upload_to=get_image_filename, verbose_name='Listing Images') main_image = models.BooleanField(default=False) class Meta: verbose_name_plural = "Listing Images" def __str__(self): return f'{self.listing.listing_title} Image' class Subscriptions(models.Model): subscription_type = models.ForeignKey(SubscriptionType, on_delete=models.CASCADE) subscription_date = models.DateTimeField(auto_now_add=True) subscription_amount = models.DecimalField(max_digits=6, decimal_places=2) subscribed_by = models.ForeignKey(User, on_delete=models.CASCADE) … -
How to get the string alone in a query instead a tuple?
When a query is made with User.object.values_list('username') is returns Quersy_set: (('user1',)('user2,)...) which is a tuple. When i print, it shows ('user1',). How to get the user1alone, so that i can display it in the template. -
Django from Query to csv dataset?
how to extract a csv dataset from the mysql database in django? or more precisely how to convert a queryset into a CSV dataset that can be later used for recommendation -
data are between parenteses in a query
I ve done a query to add values of a data set to be added to another table. query works fine but when adding data in Group table, data are like this: ('Autres dépenses',) But i just want to have: Autres dépenses. Why there is ( and , and ' characters in ? this is my code: def add_group_fromcoa(request): # add type and subtype of chart of account as first serie of group and subgroup # ------ Type adding ----- types = ChartOfAccount.objects.order_by().values_list("field_type").distinct() for type_types in types: upload_data = Group.objects.get_or_create(group_name=type_types,) print(types) give me that: <QuerySet [{'field_subtype': 'Compte chèques'}, {'field_subtype': 'Fonds en caisse'}, {'field_subtype': 'Comptes clients (CC)'}, {'field_subtype': 'Fonds non déposés'}, {'field_subtype': 'Provision pour créances irrécouvrables'}, {'field_subtype': 'Autres actifs à court terme'}, {'field_subtype': 'Autres immobilisations'}, {'field_subtype': 'Comptes fournisseurs (CF)'}, {'field_subtype': 'Passif à court terme'}, {'field_subtype': 'Impôts à payer'}, {'field_subtype': 'Compte d’attente pour la TPS/TVH'}, {'field_subtype': 'Autres passifs à long terme'}, {'field_subtype': 'Capitaux propres'}, {'field_subtype': 'Capital d’apport ou surplus'}, {'field_subtype': 'Action ordinaire'}, {'field_subtype': 'Actions privilégiées'}, {'field_subtype': 'Bénéfices non répartis'}, {'field_subtype': 'Capital d’ouverture'}, {'field_subtype': 'Autres revenus primaires'}, {'field_subtype': 'Revenu de service/frais'}, '...(remaining elements truncated)...']> thanks for helping -
Elastic-beanstalk gzip Python & Django
I am trying to enable gzip compression for Python 2.7 & Django 1.11 with Apache 2.4.39 (Amazon). I successfully enabled gzip compression when I created an Elastic Beanstalk php 7.2 application. I placed the .htaccess file in /etc/httpd/conf.d and called it compression.conf I restarted Apache sudo service httpd restart My test .html page used local js and css files which were now compressed with gzip. The file comes from the compression section of html5 boilerplate. However, I failed with Elastic Beanstalk, Python 2.7 and Django 1.11 I placed the file here /etc/httpd/conf.d/compression.conf restarted Apache The local css and js files are not compressed. There are no relevant errors in /var/log/httpd/error_log Any suggestions welcome. -
Django - passing data and redirecting between views
I'm making a project related to quizzes online and I'm stuck at the moment where I want to pass data from one view to another. My goal is to get a quiz name from the user in the form in one view and pass it to another view, after submitting a form. I've made 2 views: add() - which has the first form with the name for the quiz and redirects to add_questions with the name of the quiz add_questions() - which captures the name of the submitted quiz and displays another form for the questions views.py @login_required def add(request): if request.method == 'POST': QuizForm = QuizNameForm(request.POST) if QuizForm.is_valid(): # create a quiz new_quiz = QuizForm.save(commit=False) new_quiz.owner = request.user new_quiz.save() request.session['quiz_id'] = new_quiz.id print("Quiz saved, now I'm redirecting to add_questions") return redirect(add_questions) #return HttpResponseRedirect('add_questions') --- didn't work #return render(request, 'quiz/add_questions.html', {}) --- didn't work else: QuizForm = QuizNameForm() return render(request, 'quiz/add.html', {'quizForm': QuizForm}) @login_required def add_questions(request): print("Add questions here! I've captured a quiz named: {}".format(quiz.name)) quiz = DB_questions.objects.get(id=request.session['quiz_id']) if request.method == 'POST': print("ok, post method - cool") #create a question/answer forms else: print("Got into else in add_questions view") Question_form = QuestionForm() return render(request, 'quiz/add_questions.html', {'quiz_name': quiz.name, 'question_form': Question_form }) My … -
while sending csv to controller 'str' object has no attribute 'get'
I am trying to insert a CSV file through Postman for some data science stuff but I am getting "'str' object has no attribute 'get'" this error while sending the post request I have tried creating a fresh installation. def putContentData(request): if "POST" == request.method: try: csv_file = request.FILES["file"] if not csv_file.name.endswith('.csv'): return HttpResponse(dumps({'Message':'The input file is not in .csv format'})) else: return 'Done' except: return HttpResponse(dumps({'Message':'Error in getting the data',"status":"400"})) expecting the return message "Done" and getting the message "'str' object has no attribute 'get' django" -
How to display a string with space in an input?
I have a field "comment" in my site and I want to make it editable. To do that, I use an input field and with a javascript function it is saved in my database. However sometimes a comment has already been saved and I want to display it the user but it only displays the first word, it means Nothing is dispayed after the first space even if there is no problem in the database. <input id ="comment" class="w3-col round subsection-overview w3-hover-shadow" data-url="{{ request.path }}" onKeyPress="saveComment('data-url',this, '{{object.pk}}')" value ={{object.comment | default:''}} > </input> -
customizing django-cms user model ERROR : value does not refer to a Field and how to fix it?
i'm trying to customize the django user model but i get this error while making migrations : (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'cms.PageUser'. : (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'PageUserAdmin', or an attribute or method on 'cms.PageUser'. : (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'PageUserAdmin', or an attribute or method on 'cms.PageUser'. : (admin.E108) The value of 'list_display[3]' refers to 'last_name', which is not a callable, an attribute of 'PageUserAdmin', or an attribute or method on 'cms.PageUser'. : (admin.E116) The value of 'list_filter[0]' refers to 'is_staff', which does not refer to a Field. : (admin.E116) The value of 'list_filter[2]' refers to 'is_active', which does not refer to a Field. my usermanager class: class UserManager(BaseUserManager): def create_user(self,email,number,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError("error") if not password: raise ValueError ("error") if not number: raise ValueError("error") user_obg = self.model( email = self.normalize_email(email) ) user_obg.set_password(password) user_obg.staff = is_staff user_obg.admin = is_admin user_obg.active = is_active user_obg.save(using=self._db) return user_obg def create_staffuser(self,email,password=None): user= self.create_user( email, password=password, is_staff=True ) return user def create_admin(self,email,password=None): user= self.create_user( email, password=password, is_staff=True, is_admin=True … -
How to complete a text with the data that was later acquired
I need a solution to complete a specific section of a static text with data that is later specified. We are using django rest framework for our backend. I need a solution to do something like below: "Dear %s welcome to our site." And %s is the username of our client that i should make queries to find it and complete the static text above that is populated in our database. -
Django Annotations affecting eachother (Max / Count)
I observed weird behavior using Django annotation in a Query set. As long as I only count the number of child objects, everything is fine: >>> myqs = Parent.objects.all().annotate(num_children=Count('children)) >>> myqs.first().num_children 4 When I add a second annotation regarding some child attributes using Max the counted number seems to change. Apparently, this has to do with the number of status >>> myqs = Parent.objects.all().annotate(num_children=Count('children)).annotate(status=Max('children__status__color')) >>> myqs.first().num_children 8 What is going on here? How do I get the expected behavior (result = 4)? -
Getting Error in Django urls.py file Please help me
I am working on Django and I am getting error while run code like this : Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^employees/ The empty path didn't match any of these. here is my urls.py : from django.conf.urls import url from django.contrib import admin from webapp import views from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^employees/', views.employeeList.as_view()), ] -
module' object is not callable (TypeError at /add/2/ ')
i am facing this problem while pressing on add to cart button please help... from HomePage import Mycart //its directory in homepage app from .Mycart import Mycart from .models import Product from .models import Category ...............these are header files and error lies here @require_POST def cart_add(request, product_id): //the line bellow is an error destination line //// cart_var = Mycart(request) # create a new cart object passing it the request object product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart_var.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('pages:checkout') module' object is not callable -
Django REST Framework: Why Adding IsAuthenticated Permissions Only Threw 500 Internal Error Instead of 401 / 403 Errors?
My original backend API based off Django REST Framework was working without any security measures implemented. Now I am implementing a JWT Token Authentication process, but realised the ever-bugging problem on the backend-Django side was that once I have added "IsAuthenticated" to "'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated')" , the page that is thrown from Django is consistently a 500 Internal Error, instead of a 401/403 Authenticated Error, of which I may at least know how to move forward in resolving. Thus, I hope someone can help to point me some direction in resolving it. I have been trying for the last 5-days to implement a JWT Token, Machine-to-Machine verification, with zero-user account, and purely based on a Token authorization access, and have sort-of sorted out most of the front-end request access process via Auth0. The process by which I presumed works based on what I have read from Auth0 API: Client Browser sends request to Auth0 token authentication API Auth0 replies with Token Client Browser uses replied Token to send as Authorization Header to backend API Server API replies with result data. The current problem I do realised is that upon Step 4, is that my server kept throwing 500 Errors instead … -
path : Django 2.2 path converter
I must miss something on how to work with path (not the function, the path converter). I don't understand why the None value in the following : I have an url : urlpatterns = [ ... re_path(r'(<path:current_path>)?', views.index, name='index'), ... ] A view : def index(request, current_path): logger.error(f'current_path : {current_path}') path = request.path ... Everything functions except that current_path value remains None, whatever is the given path, while request.path holds the correct value. Why ? -
How to replace django form tag with html input?
How to replace the default django form fields - {{form.fields}} with html tags - <input type="text"> I thought of hiding this default {{form.fields}} and link these with <input> fields so that i can easily customize CSS and JS. How can i acheive this? Currently i am styling this form with bootstrap with the django widgets in forms.py. I need to loop name of the students in the {{form.student}}, since it is an attendance form. An alternatives with same django form tags is also appreciated. Thanks in advance! -
How to request a resource from a server with Electron Download Manager?
We are developing an Electron client software where we need to get some configuration files (...) which are stored on our server running Django. As we want to get specific config files for each user, we need a login for the transfer. This is the code we are using in the Electron client (using Electron Download Manager): DownloadManager.download({ url: "http://" + SERVER_NAME + "/sessions/" + USER_ID.toString() + "/downloadConf", path: "config", onLogin: (authInfo, callback) => { callback('USERNAME', 'PASSWORD'); }, }, function (error, info) { if (error) { console.log(error); } }); Obviously all caps variables are assigned in the code above this snippet. In Django we have the route and view working (if you login with a user and navigate to this URL you get the files as HTTP response), but when trying to get it from the client by the code above there is no error message. This is what we configured the Django views head to: @login_required def download_conf(request, user_id): We wanted to use this with bulkDownload at first but as it didn't work, we built this small example to test it, but even this doesn't work.