Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto deploying django code from bitbucket to server
I have a n existing setup at my workplace, where we are using Gitlab and Bitbucket. New code is pushed to Bitbucket which further pushes code to Bitbucket and if the push succeeds, it does an ssh into the remote machine and pulls the changes from remote repo, after which docker-compose is run automatically to restart the container setup. So, there's two things I would like to do: Remove Gitlab from the process and use only Bitbucket instead of Gitlab. Push new code to Staging Server(for testing) as soon as it is pushed to remote staging branch. Later on, I would like to extend this to production setup as well. I would like to do this with minimum hassle. Can anyone help? -
Why change in Django on server take time?
Every time when i change some code in my current Django site it's take time to show changes on front end of my site. -
Display queyrset and it's foreign keys in order by id in django template
I am building a quiz program. Every test has question and questions have options. Option has foreign key to a question and question has foreign key to a test. Every thing is good. But sometimes when displaying these in template, choice appear in reverse order that is sometimes choice d appears first and choice A appears last. Here is the code. { {% for question in test.sscquestions_set.all %} <div class='well quest'> <h3 style= 'font-weight:bold;'> {{question.text}} </h3> {% for choice in question.choices_set.all %} <p> {{choice.text}}</p> {%endfor%} } How to always display choices in particular order (ie. OptionA first and Option D last) -
Can I use a directory to contains a couples app directory?
Can I use a directory to contains a couples app directory? I mean, my project is very large, and there are many apps in my project. such as apps about admin user, apps about normal user, apps about frontend, apps about ... So, my project is very clutter, I want to use a group directory to wrap the related apps into it. I don't know whether this idea is feasible. some friend can help me with this? is there should take care of some other things? The snapshot red framework is a group apps. I want to group them, who can help me with this? -
Refreshing datatable with new data using django ajax and js
I've been using a modal where i can update user accounts that are in the datatable. I've been trying to figure out how to use ajax to refresh data after submitting the modal but what usually happens, is the table keeps duplicating and ends up crashing the browser before i can even try out the edit account function itself. datatable from admin.html page I wish to refresh <div class="x_content"> <div class="col-md-9" style="padding-left: 0;width: 80%" id="testRefresh"> <table id="datatable" class="table table-striped table-bordered projects dt-responsive" style="border:0; width: 100%"> <thead> <tr> <th style="text-align: center; width:10%; font-weight: 700">Group</th> <th style="text-align: center; width:10%; font-weight: 700">Member</th> <th style="text-align: center; width:10%; font-weight: 700">Router</th> <th style="text-align: center; width:10%; font-weight: 700">Switch</th> <th style="text-align: center; width:10%; font-weight: 700">Terminal</th> </tr> </thead> <tbody> {% for groups in groups %} <tr> <td> <a href="#editGrp-{{groups.id}}" data-toggle="modal"><strong>{{ groups.name }}</strong></a> <br /> </td> <td> <ul class="list-unstyled"> {% for user in users %} {% ifequal user.profile.group.id groups.id %} <li><a href="#editAcct-{{user.id}}" data-toggle="modal">{{user.username}}</a></li> {% endifequal %} {% endfor %} </ul> </td> <td> {% for gtd in grouptodevice %} {% ifequal gtd.group.id groups.id %} {% ifequal gtd.type 'AP' %} {% ifequal gtd.device.type 'Router' %} <ul class="allocatedDev-list"> <li style="padding-left: 0"> <a> <img src="{% static 'production/images/routerAvatar.png' %}" class="avatar" alt="Avatar" style="margin-right: 6px"> <strong>{{gtd.device.name}}</strong> <br/> … -
Hosting 2 django project inside one VPS server
I am trying to run 2 django project in one single VPS server in 2 different domain. I am using gunicorn as my project server. I have created 2 virtual env, 2 supervisor and 2 separate file in sites-available and enable-folder. My project is running well but the problem is in one time only one project is running in both the domain. Though in my nginx sites-avaible files are given different domain as server_name still one django project is running both of the domain Can any oone help. -
Django rest Framework sending json to api endpoint within another class-based view
I want to post to an endpoint from within a CBV and retrieve the response (in order to access the id of the created resource). I've had a look at How to programmatically call a Django Rest Framework view within another view? but cannot find how to send field values through with the request object. request.data is immutable, and passing kwargs through doesn't seem to be doing anything: from app.views import OtherViewSet class NewViews(APIView): def post(self, request, *args, **kwargs): # kwargs value here is {'field1':1, 'field2':2...} view_func = OtherViewSet({'post':'create'}) response = view_func(self.request, *args, **kwargs).data Although the kwargs contains the field values (set through several url named groups), the response always looks like: {'field1': ['This field is required'], 'field2':['This field is required... What am I doing wrong? Thanks all :) -
site domain issue in Django project
I started django server with following command: python manage.py runserver 192.168.31.79:8030 when I use following code, from django.contrib.sites.models import Site current_site = Site.objects.get_current() print (current_site.domain) the result will be 192.168.31.79:8000, why not port is 8030? Anyone could explain it for me? how could I retrieve 192.168.31.79:8030 via coding. many thanks. -
Project update crashed my Docker Image
I have a django project that I moved to docker and it was running perfectly with all of the different actions that it was doing. I update my profject by adding a model, forms, and a few views. I then built a new image and ran the image in docker container. Now all the sudden the port number fro the new container I created is not active or not recieving any data from the project. I was working a few minutes ago. Why would a change like this happen after a few project updates i added. There are no issues when I run the django project locally, I did change the branch but I don't think it would do anything to cause this issue... Here is what I ran to get the docker container and image up: docker build -t split_v2.1 . Sending build context to Docker daemon 220.2kB Step 1/7 : FROM python:3 ---> 79e1dc9af1c1 Step 2/7 : WORKDIR users ---> Using cache ---> 3b5d3885ed52 Step 3/7 : COPY requirements.txt ./ ---> Using cache ---> 65bbcf290db2 Step 4/7 : EXPOSE 8000 ---> Using cache ---> dd4c5d64a9e1 Step 5/7 : RUN pip install -r requirements.txt ---> Using cache ---> 0836ad8085d3 … -
Django: How to add recursive asymmetrical many to many relation
I have a model named Tag, with a ManyToManyField named parents: parents = models.ManyToManyField('self', blank=True, symmetrical=False) When I have a tag tag2 and try to add parent tag1 to it, Django seems to treat the relationship as symmetrical, when I need it to be asymmetrical. To be specific, when I run this code: tag1 = Tag.objects.get(name='Academic') tag2 = Tag.objects.get(name='Accounting') tag1.parents.clear() tag2.parents.clear() print("Before:") print("Tag1 has these parents:", tag1.parents.all()) print("Tag2 has these parents:", tag2.parents.all()) tag2.parents.add(tag1, symmetrical=False) print("After:") print("Tag1 has these parents:", tag1.parents.all()) print("Tag2 has these parents:", tag2.parents.all()) tag1.parents.clear() print("Lastly:") print("Tag1 has these parents:", tag1.parents.all()) print("Tag2 has these parents:", tag2.parents.all()) This is the output: After first clearing: Tag1 has these parents: <QuerySet []> Tag2 has these parents: <QuerySet []> After adding parent: Tag1 has these parents: <QuerySet [<Tag: Accounting>]> Tag2 has these parents: <QuerySet [<Tag: Academic>]> After clearing again: Tag1 has these parents: <QuerySet []> Tag2 has these parents: <QuerySet []> I need tag1 to be a parent of tag2, but not vice versa. I'm able to make this happen through the admin interface, but I can't seem to do it in code. This seems like it should be a very basic and common function, so I'm confused as to why it's misbehaving. -
HOW TO sum two OR MULTIPLE ROWS SAME ID IN DjANGO?
Bill# | Product | Quantity | price1 | price2 | total PK-20 | prod | 2 | 1110 | 3700 | 2590 PK-20 | prod | 2 | 550 | 3700 | 3145 PK-21 | prod | 3 | 550 | 3700 | 3145 PK-21 | prod | 3 | 550 | 3700 | 3145 I need SUM of total column sum same ID. MY query is. filtered_record = BillManagement.objects.filter(creation_date__range=[date, date1], **kwargs).annotate( price=F('product__cost') - F('customerproductbill__discounted_price')).annotate(total_spent=Sum('price')).values_list( 'bill_number', 'product__product_name', 'quantity', 'distype__percentage_discount', 'customerproductbill__discounted_price', 'product__cost', 'price', 'customerservicebill__discounted_price', 'total_spent' ).distinct() -
Django View & Form Inheritance
I am trying to change the password change form for my custom user auth django project. I am running into a bit of a problem. Perhaps I am too tired, perhaps I am wrong or misunderstanding things, which is why I am seeking help. I know it seems like a lot of work for such a small thing but I am trying to create a 'canned' auth app. My goal with this particular problem is simply to apply style to the PasswordChangeForm(SetPasswordForm) class without the aid\dependency of non-native packages. Am I wrong in my thought process here? urls calls a view that inherits from the auth view which points to a form that inherits from auth form with changed field values. Thanks in advance. urls.py from .views import ChangePasswordView from django.contrib.auth.views import ( PasswordChangeDoneView, ) urlpatterns = [ path('change_password/', ChangePasswordView, name='password_change'), ] views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.views import PasswordChangeView from .forms import ChangePasswordForm @login_required class ChangePasswordView(PasswordChangeView): template_name='account/change_password_form.html' form_class = ChangePasswordForm forms.py from django import forms from django.utils.translation import gettext, gettext_lazy as _ from django.contrib.auth.forms import ( PasswordChangeForm, SetPasswordForm, ) class ChangePasswordForm(PasswordChangeForm): template_name='account/change_password_form.html' old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True, 'placeholder': 'Password', 'class': 'form-control', 'required': 'true'}), ) new_password1 … -
Is there any method to check parameter of view functions in python (Django)?
What I want: @api_view(['POST']) @params(required=["arg1", "arg2"], optional=["arg3"]) def test(request): # if arg1, args not posted, abort 400 or something arg1 = request.data.get("arg1") arg2 = request.data.get("arg2") arg3 = request.data.get("arg3") # do something I use the rest framework but it seems that there is only validator for serializer. -
Django: how to link a class and function from views.py onto same URL(app)
I have a class and function in django views.py, one is used for django forms and other for accepting file input from user and store it in 'BASE_ROOT/media/'. views.py from django.views.generic import TemplateView from home.forms import HomeForm from django.shortcuts import render, redirect from home.models import Post from django.conf import settings from django.core.files.storage import FileSystemStorage class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() # text = form.cleaned_data['post'] form = HomeForm() args = {'form': form} return render(request, self.template_name, args) def upload(request): print ('--Function called--') if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'home/home.html', {'uploaded_file_url': uploaded_file_url}) return render(request, 'home/home.html') below is my url.py file: from django.conf.urls import url from home.views import HomeView from . import views urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), url(r'^$', views.upload), ] the problem is that the upload function is not being called. only the functions inside the class are being called. I have also tried to put the upload function inside the same class but … -
update preview field after submitting the value
I have a model for storing document numbering where the fields to fill are document, prefix, suffix, length and start. This I could do but after filling those data I need to show preview field in the table and preview field is based on the prefix, suffix and length. What I mean to say is if I fill the prefix as 1, suffix as -2345 and length as 4 then the preview should be for that document as 1xxxx-2345 if prefix as he-, suffix as -7459 and length as 5 then the preview should be he-xxxxx-7459 This can be done with the following logic preview = str(prefix)+(('x')*length)+str(sufix) But how can I implement this in django. Do I have to use signals or override save method? Can anyone give me an idea, please? Here is my model class DocumentNumbering(models.Model): office = models.OneToOneField(OfficeSetup, blank=True, null=True) document = models.OneToOneField(Document blank=False, null=False) prefix = models.CharField(max_length=100, blank=True, null=True) sufix = models.IntegerField(blank=True, null=True) start_number = models.PositiveIntegerField( default=0, blank=False, null=False) length = models.PositiveIntegerField(default=0, blank=False, null=False, validators=[ MaxValueValidator(10), MinValueValidator(1)]) // not sure where to implement the logic for preview def save(self, *args, **kwargs): -
IsAuthenticated Permission is not working - Django Rest Framework
When creating a post and there's no user logged in, the result shows "Authentication credentials were not provided", something like that. When I'm trying to create a post and there's no user logged in, it doesn't show the message above. It still proceed in creating. What do I need to do? This the code the I used. from rest_framework.generics import ( CreateAPIView, DestroyAPIView, ListAPIView, UpdateAPIView, RetrieveAPIView, RetrieveUpdateAPIView ) from rest_framework.permissions import ( AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, ) from posts.models import Post from .permissions import IsOwnerOrReadOnly from .serializers import ( PostCreateUpdateSerializer, PostDetailSerializer, PostListSerializer ) class PostCreateAPIView(CreateAPIView): queryset = Post.objects.all() serializer_class = PostCreateUpdateSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(user=self.request.user) class PostDetailAPIView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' #lookup_url_kwarg = "abc" class PostUpdateAPIView(RetrieveUpdateAPIView): queryset = Post.objects.all() serializer_class = PostCreateUpdateSerializer lookup_field = 'slug' permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] #lookup_url_kwarg = "abc" def perform_update(self, serializer): serializer.save(user=self.request.user) #email send_email class PostDeleteAPIView(DestroyAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer lookup_field = 'slug' #lookup_url_kwarg = "abc" class PostListAPIView(ListAPIView): queryset = Post.objects.all() serializer_class = PostListSerializer Thanks -
Update variables on HTML page using Ajax in Django
I'm new to Ajax and Django so I have a problem. I have a python function in Django like this: Python function all_cves = [] cves = cve.objects.all()[len(cve.objects.all())-10:] for post in cves: cve_list = [] cve_list.append(post.cve_id) cve_list.append(post.rating) cve_list.append(post.description) cve_list.append(post.date) all_cves.append(cve_list) context = { 'id1': all_cves[0][0], 'rating1': all_cves[0][1], 'description1': all_cves[0][2], 'date1': all_cves[0][3], ... } if request.is_ajax(): print("RETURN AJAX") return JsonResponse(context) else: print("RETURN HTTP") return render(request, "header.html", context) It returns 10 rows from my DB and then sends dict to my HTML page. My JavaScript function looks like this: Ajax function <script type="text/javascript"> $( document ).ready(function() { setInterval(function(){ $.ajax({ url:'/' , type: "get", cache: true, timeout: 30000, dataType: 'html', success: function(data) { console.log("success"); $('#MyTable').html(data); }, error: function(data) { alert("Got an error dude "+data); } }); },50000); }); </script> It should update variables on page every 50 seconds and in PyCharm I see that it sends request and python function work fine and prints that it's Ajax request. My HTML page looks like this: HTML <div id="MyTable"> <div class="row" style="margin-top: 5px"> <div class="col-xs-0 col-md-2"><a href="http://cve.circl.lu/api/cve/{{ id1 }}" target="_blank">{{ id1 }}</a></div> <div class="col-xs-0 col-md-1">{{ rating1 }}</div> <div class="col-xs-0 col-md-6"><marquee scrollamount="4">{{ description1 }}</marquee></div> <div class="col-xs-0 col-md-3">{{ date1 }}</div> </div> ..... </div> As you can see … -
Django update base on current field value
Given the schema: stats { id: integer total: integer total_accepted: integer total_rejecged: integer } I need to update the record at one go like this: UPDATE stats SET total = total + 1, total_accepted = total_accepted + 1 WHERE id=1 So how to achieve it in Django if do not use a raw query? -
How to get avatar of user in template?
I have an extended usermodel via abstractuser class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) View: class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'topic_posts.html' paginate_by = 2 def get_context_data(self, **kwargs): self.topic.views += 1 self.topic.save() kwargs['topic'] = self.topic return super(PostListView, self).get_context_data(**kwargs) # Here we define query to url def get_queryset(self): self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('pk'), pk=self.kwargs.get('topic_pk')) queryset = self.topic.posts.order_by('created_at') return queryset My template <div class="col-2"> <img src="" alt="{{ post.created_by.username }}" class="w-100"> <small>Posts: {{ post.created_by.posts.count }}</small> </div> What will I need to add to "img src" to display avatar of user? -
xframe_options_exempt for enabling iframe not working in django
I am currently trying to load an iframe in Django within Facebook messenger following the official guide: https://developers.facebook.com/docs/messenger-platform/webview/extensions I have whitelisted the domain I am trying to load in the iframe. I am using Django version 1.11.3 plain vanilla Django folder structure ngrok for testing my application in my settings.py file I have under middleware 'django.middleware.clickjacking.XFrameOptionsMiddleware', my view.py file looks like this from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt from django.shortcuts import render import requests @xframe_options_exempt def login(request): return render(request, 'template5.html') Replacing my function return to return HttpResponse("some text") won't help. The decorator is specified in the django documentation for allowing iframes: https://docs.djangoproject.com/en/1.11/ref/clickjacking/ my urls.py file looks like this: urlpatterns = [ url(r'^login/', view.login, name='login'), ] However, iframe won't open in desktop browsers. Also removing 'django.middleware.clickjacking.XFrameOptionsMiddleware', from settings.py doesn't help -
Django Rest Framework format decimal field to 2 decimal places (for output)
I use Django and DRF,I have many decimal fields in models, like amount = models.DecimalField(max_digits=16, decimal_places=4) I want format output Two decimal places ,in every serializers field can do this amount = serializers.DecimalField(max_digits=16, decimal_places=2) There's an easyer way? -
Multi-model filtering worked in Django view, but not in Django REST Framework view
I have a sneaking suspicion this has to do with using DRF APIView class, where as this older application was just in pure Django. Anyway, this used to work in the old project where it would return the results based on multi-model filtering. from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from account.models import UserToSurvey, Surveys # The following prohibits access to the website unless authenticated @login_required # Create your view here. def home(request): survey_user = Surveys.objects.filter(stage='active').order_by('-name').filter(usertosurvey__survey__isnull=False, usertosurvey__user=request.user) return render(request, 'home/home.html', {'survey_user': survey_user}) I would like to implement something similar in a React-Django (DRF) I am working on, but when it comes across usertosurvey__user it thinks it is a field name in the Surveys.objects.. This is what I have for the new version: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from rest_framework.views import APIView from .serializers import GetHomeSerializer, GetSurveySerializer from .models import Home, UserToSurvey, Surveys # Create your views here. class GetHomeAPIView(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): user = request.data['user'] serializer = GetSurveySerializer(UserToSurvey.objects.filter(user=user, surveys__stage='active').prefetch_related('survey'), many=True) return Response(serializer.data) Anyway, anyway to do something similar here? -
Django : migration success but not creating new table
I've been using django migration to handle database. recently, I split session into two, one is for reading and the other one is for writing. After done this, I made new migration file that adding new table and run it. It was successful, Operations to perform: Apply all migrations: food Running migrations: Applying food.0107_auto_20171116_0849... OK However, when I checked mysql database using shell, there was no new table. I deleted django migrations history and attempted few times more but the result was same. It says migration applied but there was no new table. This is my migration file # -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-11-16 08:49 from __future__ import unicode_literals from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('bubi', '0106_auto_20171110_1452'), ] operations = [ migrations.CreateModel( name='FoodHistory', fields=[ ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)), ('date', models.DateField(verbose_name='updated date')), ], options={ 'verbose_name': 'food updated date', 'verbose_name_plural': 'food updated date', }, ), ] I wonder if splited session may affects to do migrations. thanks! -
Using ABC, PolymorphicModel, django-models gives metaclass conflict
So far every other answer on SO answers in the exact same way: construct your metaclasses and then inherit the 'joined' version of those metaclasses, i.e. class M_A(type): pass class M_B(type): pass class A(metaclass=M_A): pass class B(metaclass=M_B): pass class M_C(M_A, M_B): pass class C:(A, B, metaclass=M_C): pass But I don't know what world these people are living in, where they're constructing your own metaclasses! Obviously, one would be using classes from other libraries and unless you have a perfect handle on meta programming, how are you supposed to know whether you can just override a class's metaclass? (Clearly I do not have a handle on them yet). My problem is: class InterfaceToTransactions(ABC): def account(self): return None ... class Category(PolymorphicModel, InterfaceToTransactions): def account(self): return self.source_account ... class Income(TimeStampedModel, InterfaceToTransactions): def account(self): return self.destination_account ... Which of course gives me the error: "metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases" I've tried many variations of the solution given above, the following does not work, gives the same error. class InterfaceToTransactionsIntermediaryMeta(type(PolymorphicModel), type(InterfaceToTransactions)): pass class Category(PolymorphicModel, InterfaceToTransactions): __metaclass__ = InterfaceToTransactionsIntermediaryMeta ... Nor does putting anything inside the class Meta function. I've read … -
How sites framework works?
I am trying to develop a ModelManager with an operation similar to the Sites Framework. Depending on a user's field, the ModelManager returns a queryset. I tried to imitate the operation of the Sites Framework but I do not understand how the SITE_ID is obtained dynamically with this function: def get_queryset(self): return super(CurrentSiteManager, self).get_queryset().filter( **{self._get_field_name() + '__id': settings.SITE_ID}) It seems to be static :/. I capture the user's field through a Middleware and assign it to request.field. How can I retrieve that field in the ModelManager and perform the query?