Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django load static
When I'm trying to change anything in css files, I can't see any changes. Like if I once built project, he saves this style, so if change background color in default.css from white to black and run the project, background still will be white. I think it comes from {% load static %} in html file but not quite sure. The only way I found to apply changes in css is to create new css file and link html with it. Any ideas how to fix it? -
Django Multiple User profiles (design decision)
The title might seem very familiar (lots of related questions but I couldn't find relevant to my use case). Here's my app info: Two types of user profiles (Basic & Professional) Basic user is an instance of User with an addition field (phone) Basic user posts questions (needs help with stuff) Pro users provid various services (help/answer the questions posted by basic users) Pro users belongs to an Organisation class, basic users don't. Also, Pro represents its own org, so an Organisation belongs to one profile (hence OneToOneField) Question: So I need help with deciding whether to create two separate profiles (BasicProfile & ProProfile) for each type or create a single Profile and use a boolean field that says whether a profile is_proor not (much like the django's is_superuser boolean field) Approach 1: class Organisation(models.Model): name = models.CharField(_('Name'), max_length=50) profile = models.OneToOneField(ProProfile, on_delete=models.CASCADE) ... class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(_('Phone'), max_length=200, null=True, blank=True) class Meta: abstract = True def __str__(self): return self.user.get_full_name() class UserProfile(Profile): pass class ProProfile(Profile): verified = models.BooleanField(default=False, verbose_name=_('Verified')) Approach 2: class Organisation(models.Model): name = models.CharField(_('Name'), max_length=50) profile = models.OneToOneField(Profile, on_delete=models.CASCADE) class ProfileManager(models.Manager): def basic(self, **kwargs): return self.filter(is_pro=False, **kwargs) def pro(self, **kwargs): return self.filter(is_pro=True, **kwargs) … -
creating custom messages/exceptions creating account
I'm creating a Sign up view, and would like to create some custom messages, for instance if email is already taken or username is already taken. i've so far created a custom_exception_handler, but i'm not sure how to implement so that it is returning the UsernameInUse view class AccountViewSet(viewsets.ModelViewSet): lookup_field = 'username' queryset = Account.objects.all() serializer_class = AccountSerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.AllowAny(),) if self.request.method == 'POST': return (permissions.AllowAny(),) return (permissions.IsAuthenticated(), IsAccountOwner(),) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): Account.objects.create_user(**serializer.validated_data) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response({ 'status': 'Bad request', 'message': 'Account could not be created with received data.' }, status=status.HTTP_400_BAD_REQUEST) serializer class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'first_name', 'last_name', 'password', 'confirm_password',) read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): return Account.objects.create(**validated_data) def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() password = validated_data.get('password', None) instance.set_password(password) instance.save() return instance exception_handler from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = … -
Save origin ration django easy thumbnails
Django and easy-thumbnails. Is it possible to change the image when saving it to the db? But I need to save origin aspect ratio, one thing to do is to decrease image size. For example, when user upload photo with 2400x1600 it become 1200x800 3200x2000 -> 1600x1000 but: 500x300 -> 500x300 So, actually I don`t know what exactly to do, but I need to decrease image size. -
How to create admin for each group in Django Admin?
I want to to make an (special,custom) admin for each group in Django Admin. The superadmin can manage all of users and groups and the admin of one group can manage only users who are in this group. How can I make it? Thanks! -
Django migrations old database, forgot one model before
I have existing database/production system pre-migration support for Django. We did start to use Djangos migration 2 years back it turns out I did forget to install migrations for one model that now causes problems. 2 years back I had the following models; Location, Tool and a third Log that points to instances of Location and Tool. The 0001_inital.py for Log model has a dependency to Tool for 0001_inital but for Locations it points to _ first _ Now, today I am trying to get Location to use migration (so I later can add things to it, needed now) for the first time... Running makemigration Location works and generates a new clean migration directory and all, but then when doing migrate --fake I get the following django.db.migrations.exceptions.InconsistentMigrationHistory: Migration log.0001_initial is applied before its dependency locations.0001_initial on database 'default'. Understand this is caused by the mistake earlier by forgetting to get migrations done for Locations when we started to use this in Django - any ideas how to resolve this in a good way? -
Django model request array
I am new to python and Django. I haven't found anything in documentations so I have to write here. I have such problem. I have cars table where you can find it's make, model. year and so on. Usually i make request by just Cars.objects.filter(make=x, model=y, year=z) I want to make search and all params are in array. There are many params and is it possible to make something like Cars.objects.filter(array) -
Django how to loop through objects and display variables in a template
I'm working with boto3 to display various data about my s3 buckets in AWS. I have the following code in views.py to display s3 page: class s3(TemplateView): template_name = 'project/s3.html' def get_context_data(self, **kwargs): context = super(s3, self).get_context_data(**kwargs) aws = boto3.resource('s3') buckets = aws.buckets.all() for bucket in buckets: totalSize = 0 bucketName = bucket.name createdAt = bucket.creation_date fileBuckets = boto3.resource('s3').Bucket(bucketName) for file in fileBuckets.objects.all(): totalSize += file.size context['buckets'] = buckets context['bucket'] = buckets context['createdAt'] = createdAt context['bucketName'] = bucketName context['totalSize'] = totalSize return context I'm trying to display these variables in a template like this: <div class="s3Items"> {% for bucket in buckets %} <div class="s3Name"> <div id="left"> <h4 id='s3ItemName'>{{ bucketName }}</h4> </div> <div id="right"> <ul id='s3ItemDesc'> <li>{{ createdAt }}</li> <li>{{ totalSize }}/4GB</li> <li> <button type="button" name="button" class='button delete'>Delete</button> </li> </ul> </div> </div> {% endfor %} But obviously this doesn't work. How can I iterate through those buckets in template? I also tried the below and it worked but not completely as I cannot get the total sizes of all files in each bucket: <div class="s3Items"> {% for bucket in buckets %} <div class="s3Name"> <div id="left"> <h4 id='s3ItemName'>{{ bucket.name }}</h4> </div> <div id="right"> <ul id='s3ItemDesc'> <li>{{ bucket.creation_date}}</li> <li>{{ ??? }}/4GB</li> <li> <button … -
django rest framework and forms: How to do
I have a model in my Django App as below. I am using ReactJs as frontend and pass data using Django Rest Framework. class Ingredient(models.Model): MUNITS_CHOICES = ( ('kg', 'Kilogram'), ('ltr', 'Liter'), ('pcs', 'Pieces'), ) name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) munit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=KILOGRAM) rate = models.DecimalField(max_digits=19, decimal_places=2,validators=[MinValueValidator(0)],default=0) typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT) density_kg_per_lt = models.DecimalField(max_digits=19, decimal_places=2,verbose_name='Density (kg/lt)',null=True,blank=True,validators=[MinValueValidator(0)]) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) As you see the model fields have lot of parameters like max_length, choices, ForeignKey(which is also kind of choices), DecimalField, CharField, DateTimeField etc I was creating and rendering forms using Django Forms. Also the validaton is done in the Form class. The advantage of this is the form is inserted very easily in the template using {{ form }}. and it takes care of all the parameters like max_length, choices, fieldtypes etc. Also we can validate the form and the errors are send back etc. So most the job is done automatically. But since i am using DRF i created a serializer class to create or update: class IngredientCreateUpdateSerializer(ModelSerializer): class Meta: model = Ingredient fields = [ 'name', 'munit', 'rate', 'typeofingredient', 'density_kg_per_lt', ] Here again i have to write the validation logic which i … -
Django, Elixir or NodeJS?
Quick question, I'd just like to know your opinions. Now, what should I learn? Django, Elixir or NodeJS. Which one is the best? Thx! -
Retrieving ID to use in a query, Django
I have a simple question I guess: I am trying to query my data base in order to retrieve the number of team members linked to a specific team, linked to a specific project. team_member_count = Project.objects.get(id = id).team_id.members.count() The query is for the project detail view using a url like : localhost/website/project/141/ In the shell my query is Project.objects.get(id = 141).team_id.members.count() but in the views I get : TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' My view is the following (retrieving data for chart.js) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None, *args, **kwargs): user_count = MyUser.objects.all().count() project_count = Project.objects.all().count() team_member_count = Project.objects.get(id = id).team_id.members.count() labels = ["Users", "Projects", "Team_number", "Green", "Purple", "Orange"] default_items = [user_count, project_count,team_member_count,28,12,32] data = { "labels":labels, "default":default_items, } return Response(data) -
Understanding Django Admin
I am building a web application using Django, let's say I have apps such college and department. my URL looks like below for the end users. urlpatterns = [ url(r'^add/$', collegeCreate.as_view(), name="college_create"), url(r'^(?P<college_id>[0-9]+)/info', collegeDetail.as_view(), name="college_detail"), url(r'^(?P<college_id>[0-9]+)/activate/', college_activate, name="college_activate"), url(r'^(?P<college_id>[0-9]+)/deactivate/', college_deactivate, name="college_deactivate"), url(r'^$', collegeList.as_view(), name="college_list"), url(r'^add/', departmentCreateView.as_view(), name="department_create"), url(r'^(?P<department_id>[0-9]+)/update/', departmentUpdateView.as_view(), name="department_update"), url(r'^(?P<department_id>[0-9]+)/info/', departmentDetailView.as_view(), name="department_detail"), url(r'^$', departmentListView.as_view(), name="department_list") ] How can i add views and urls for admin like above,currently i am achieve that by overiding get_urls in Model Admin ,and create separate views for admin but i am repeating same block, so what is the best way to achieve this -
Django - check email matching while registering
I am making a register page and want users to double check their email address. The second email is not in the User model, so I did this: class RegisterForm(forms.ModelForm): email = forms.EmailField(label="Email") email2 = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [#fields are going to be shown here 'username', 'password', 'email', 'email2', ] def clean_email(self): email = self.cleaned_data['email'] email2 = self.cleaned_data['email2'] if email != email2: raise forms.ValidationError("Emails must match") return email when I click on submit button, it raises a KeyError on "email2" and it goes to email2 = self.cleaned_data['email2'] Appreciate for any help! -
Modal Django Popup forms for User Input
I have a page which shows the portfolio of the user, in that page ,I have an 'Add New' button. I want that the add new button should popup instead of opening in new window and then user could save the new entry and after saving, the main portfolio page should display the new data too. I know it is possible with ajax, but even after looking for 2 days, I could not come up with a solution. My portfolio(base page) html is :- {% block stylesheet %} <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <<link rel="stylesheet" href="{% static 'css/portfolio.css' %}"> {% endblock %} {% block body %} <div class="container"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-4"> <h2>My<b>Portfolio</b></h2> </div> <div class="col-sm-4"> <div class="search-box"> <div class="input-group"> <input type="text" id="search" class="form-control" placeholder="Search by Code"> <span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span> </div> </div> </div> </div> </div> <div class="mb-4"> <a shref="{% url 'add_new_form' %}" class="btn btn-primary">Add New</a> </div> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>NSE Code</th> <th>Quantity</th> <th>Average Buy Price</th> <th>Total Buy Value</th> <th>Today's Change</th> <th>Today's Change %</th> <th>Overall Change</th> <th>Overall Change %</th> <th>Current Value</th> <th>Actions</th> </tr> </thead> {% for myportfolio in myportfolios %} <tbody> <tr> <td>1</td> … -
Django + Chart.js rendering issues
I am having some troubles figure out my issue. I am using Chart.JS in order to use graphs + data within my app. I followed a tutorial on youtube but I am getting an error that I do not know how to fix: I get a message error that t is nul .. but don't really know what it means ............................................................................................................................................................................................................................................................................................................ Chart.min.js:10 Uncaught TypeError: Cannot read property 'length' of null at Object.acquireContext (Chart.min.js:10) at t.construct (Chart.min.js:10) at new t (Chart.min.js:10) at (index):259 acquireContext @ Chart.min.js:10 construct @ Chart.min.js:10 t @ Chart.min.js:10 (anonymous) @ (index):259 here is my HTML: {% block extrajs %} <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js" integrity="sha256-vyehT44mCOPZg7SbqfOZ0HNYXjPKgBCaqxBkW3lh6bg=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" integrity="sha256-N4u5BjTLNwmGul6RgLoESPNqDFVUibVuOYhP4gJgrew=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" integrity="sha256-N4u5BjTLNwmGul6RgLoESPNqDFVUibVuOYhP4gJgrew=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" integrity="sha256-c0m8xzX5oOBawsnLVpHnU2ieISOvxi584aNElFl2W6M=" crossorigin="anonymous"></script> <script> var endpoint = 'api/chart/data' var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, … -
How to verify hashed passwords in Bcrypt?
I have been using bcrypt for hashing my passwords for an authentication system in Django. I could succesfully hash it but not not decrypt for getting inside my login system. -
Django: why is ViewClass.as_view used with brackets in URLconf?
If I have a view-class and I want to use it in URLconf, I will have to use its as_view()-method, since the view-class isn't a function, but a class. My question is, in URLconf, why is as_view() called with brackets? Doesn't this mean that the function will be run upon reading URLconf? If so, what is it exactly that as_view does? Example: # urls.py from django.conf.urls import url from some_app.views import AboutView urlpatterns = [ url(r'^about/$', AboutView.as_view()), # <--- We're calling the method. Why? ] -
Remove history button from Django admin
I want to enable/disable history from django admin button based on the type of user. My end goal here is to be able to understand how to show hide this button. -
Django LocaleMiddleware permanent redirects
I want to be able to have https://example.com/ 301 redirect to https://example.com/en/ https://example.com/fr/ https://example.com/de/ etc depending on what the LocaleMiddleware determines the users language to be (for SEO purposes). Currently it 302 redirects by default. This was apparently added but I can't figure out how to do it. The documentation doesn't mention anything about it. Any help would be much appreciated. -
How can I force the page refresh with Django Channels?
i am looking for a way to reload a web page whenever a server side event occour with Django Channels. -
django using can_order to change order of form fields
I'm new to django. I have a form with one field that keeps only the name of family members. I want user be able to change the order as he/she wishes. Now he order is the order of their creation. I found something can_order that when I added it to my form, another field appeared aside names and was an integer showing the number in the list. My question is can I change order playing with this number? If yes how should I do that? my form: class FamilyMemebrsNameForm(forms.Form): name= forms.CharField(label=_('name'), max_length=250) FamilyMemberNameItem= formset_factory(FamilyMemebrsNameForm, can_delete=True, can_order=True) FamilyMemberNameItem is what I use.Thanks -
Recursive app dependencies django
Django's INSTALLED_APPS is a list in the settings file, which ultimately the devops girl/guy of the wsgi-application is responsible for. However, when creating an app, I often use templates and templatetags of other apps, for example django-bootstrap4. Consider a simple bootstrap4-with-butter app, that only proivides this template: bs4wb/templates/bs4wb/base.html {% extends "bootstrap4/bootstrap4.html" %} {% block bootstrap4_extra_head %} <script> confirm('with butter?!'); </script> {% endblock bootstrap4_extra_head %} It is not enough for the devops to install and add to INSTALLED_APPS bs4wb, they also need to do the same for django-bootstrap4, and moreover, he/she also needs to keep track of the version I used whenever I upgrade from django-bootstrap4 to django-bootstrap5` or something. That is, I need to document an extra step which can change. How can I specify recursive INSTALLED_APPS? Is there something like an app-union? For example (obviously ugly syntax, sorry): export('bs4wb', app_by_union(['bootstrap4', 'bs4wb']) ) which would insert bootstrap4 and bs4wb next to each other whenever bs4wb is added to INSTALLED_APPS? -
Failed to start Redis In-Memory Data Store
After trying to establish WebSocket Connection using Redis this error was appeared. I have no idea what happened because I've established this connection well but soon after publishing a message using RedisPublisher in Django-websocket-redis, Redis seems to be dead. What's going on and how can I make Redis work in this situation? -
event.save() gives error in Django
I am getting sqlite3 Integrity Error - Datatype Mismatch. But python manage.py migrate and python manage.py makemigrations run well. My form data is valid. I am getting this error if I try to save the data to the database by making use of event.save in views. My model is: class createEvent(models.Model): FirstName = models.CharField(max_length=150) LastName = models.CharField(max_length=150) EventName = models.CharField(max_length=150) EventOrganizer = models.CharField(max_length=150) Location = models.CharField(max_length=200) Date = models.DateField() LastDateOfRegistration = models.DateField() EventDetails = models.TextField() My views.py is def create_event(request): title = "Drizzlelore" subtitle = "Create event" if request.method == "POST": form = createEventForm.createEventForm(request.POST) print(form.errors) if form.is_valid(): fname = form.cleaned_data.get('FirstName') lname = form.cleaned_data.get('LastName') eventName = form.cleaned_data.get('EventName') eventOrganizer = form.cleaned_data.get('EventOrganizer') location = form.cleaned_data.get('Location') date = form.cleaned_data.get('Date') lastDateofReg = form.cleaned_data.get('LastDateOfRegistration') eventDetails = form.cleaned_data.get('EventDetails') event = form.save(commit=False) event.save() context = { "title":title, "subtitle":subtitle, "form" : form, } return HttpResponse("Success form submitted") else: print("Form not valid") return HttpResponse("Failure") else: form = createEventForm.createEventForm() context = { "title":title, "subtitle":subtitle, "form":form, } return render(request,"home/createevents.html",context) My form is class createEventForm(forms.ModelForm): class Meta: model = createEvent fields = [ 'FirstName', 'LastName', 'EventName', 'EventOrganizer', 'Location', 'Date', 'LastDateOfRegistration', 'EventDetails', ] -
How do I use Django's return JsonResponse in the template and show it as a notification message?
I have this return JsonResponse in a method in views.py: return JsonResponse({"message": "You're Successfully Registered!"}) I want this message to show as a notification message in the HTML template. What is the ajax function that I should use to retrieve the data returned from this JsonResponse?