Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
extract multiple pk from POST data , Django
I have troubles extracting multiple “pk” data from the request.POST Cant get my head around this but I feel like answer should be easy and/or question is dumb(optionally :)). I have following method in my view: def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): articles = Article.default.filter(id__in=self.request.POST["pk"]) article_titles = [article.title for article in articles] message = article_titles messages.add_message(request, messages.SUCCESS, message=message, fail_silently=True) return self.form_valid(form) else: return self.form_invalid(form) # what is defaul - default = models.Manager() ,that is equal to objects Technical it should extract list of PK’s from post data, then filter query-set and get list of articles, then extract their titles and message them to user via messaging framework. Quite straightforward. List of PK is sent to POST data by ModelMultipleChoiceField in form What I have in POST data: 'csrfmiddlewaretoken' ['DxrzPApYhtxh6ZCqszkvBkywbBTPIaXtpTZTjdJQEFCTqR0vSNXycAcJJnh3jnRC'] 'pk' ['34', '32', '25', '24', '22', '11'] 'submit' [''] and surprisingly on this POST data I have following query set: SELECT ••• FROM "articles_article" WHERE "articles_article"."id" IN (1) ORDER BY "articles_article"."created_at" DESC question is : -why IN(1)? -how to get list of pk’s in POST data to query-set filter? when i have singular pk -it works fine. Problem when i have multiple PKs only -
How to pass variable as parameter from url in django?
Not able to pass 'a' variable as parameter passing in Django url. <html> <head> <script> var a; fetch('http://localhost:8000/api/notes.json') .then(response => response.json()) .then(data => { for (i=0;i<data.length;i++){ document.getElementById('demo').innerHTML += data[i].subject + "</br></br>" document.getElementById('a').innerHTML = data[i].id } } ) </script> </head> <body> <h1> Notes List</h1> <h3><a href="{% url 'notesdetails' a %}" id='demo'></a></h3> </body> </html> NoReverseMatch at /notes/ Reverse for 'notesdetails' with no arguments not found. 1 pattern(s) tried: ['notes/(?P[0-9]+)$'] -
pip could not find a version that satisfies the requirement django==2.2.1
I just have changed my os to linux and I want to install django. But I am unable to install the latest version of django. I have tried pip install django However it installed django 1.11.11 which is not what I need. I also upgraded my pip to 19.1 However still I am unable to run the command pip install django==2.2.1 When I run the command this is what I see $ pip install django==2.2.1 DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. Collecting django==2.2.1 ERROR: Could not find a version that satisfies the requirement django==2.2.1 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, … -
How to use the django_cron with the managements/commands/file?
from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 120 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'my_app.my_cron_job' # a unique code def do(self): pass # do your thing here -
DRF password not being set by set_password()
I don't understand why the password is not being set: platforms = Platform.objects.all() platforms[2].is_active >> True platforms[2].check_password("abcd") >> False platforms[2].set_password("abcd") platforms[2].save() platforms[2].check_password("abcd") >> False models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class Platform(AbstractUser): pass serializers.py class PlatformSerializer(serializers.ModelSerializer): class Meta: model = Platform fields = ("username", "password") def create(self, validated_data): password = validated_data.pop('password') platform = Platform(**validated_data) platform.set_password(password) platform.save() return platform views.py class CreatePlatform(viewsets.ModelViewSet): queryset = Platform.objects.all() serializer_class = PlatformSerializer pagination_class = None permission_classes = (AllowAny, ) in my settings.py I have AUTH_USER_MODEL = 'users.Platform' PS: the Token being created just fine -
Delete Session Data From Django Template
Basically, I want the user to be able to click a button in the template that will invoke del request.session['example'] which is in my views.py So maybe something like. if *user has pressed button*: del request.session['example'] else: pass I can't figure out how to communicate this between my template and my views -
field name choice 'reference' is not a valid choice issue
I am trying to create a view set in which i want to filter all of the records that have the same reference number. there is a reference model field in the Member model, but it is telling me that it is an invalid field. this is the viewset: from groups.models import Member from ..serializers import MemberSerializer from rest_framework import viewsets class MemberViewSet(viewsets.ModelViewSet): queryset = Member.objects.filter(field_name='reference') serializer_class = MemberSerializer this is the models: class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) reference = models.CharField(max_length=22) balance = models.DecimalField(max_digits=12, decimal_places=2) open_tabs = models.IntegerField() created = models.DateTimeField(auto_now_add=True) this is the urls: from groups.api.views.memberViews import MemberViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', MemberViewSet, base_name='member') urlpatterns = router.urls so i want to filter out all of the member objects with the same reference field value... -
Multiple initial for checkbox rendered using widget-tweaks
I need guidance in selecting multiple initial values for checkbox which are rendered using widget-tweaks. My code is working great when I have a single initial value. However when there is more than 1 initial value, only the first will be checked in the checkbox. forms.py class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('name', 'category', 'pods') def __init__(self, group_id, category_id, *args, **kwargs): super(GroupForm, self).__init__(*args, **kwargs) selected_group = Group.objects.get(id=group_id) self.fields['name'].initial = selected_group.name self.fields['category'].initial = selected_group.category.id self.fields['pods'].queryset = Pod.objects.filter(category=selected_group.category.id) associated_pods = selected_group.pod.all() self.fields['pods'].initial = [pod.id for pod in associated_pods] views.py def GroupUpdate(request,id): group = get_object_or_404(Group, pk=id) context = {} group_id = group.id category_id = request.GET.get('category') context['form'] = GroupForm(group_id, category_id) return render(request, 'catalog/group_detail.html', context) html file ... <div class="form-group"> <label class="col-md-3 control-label">Group's Members</label> <div class="col-md-6"> <div class="input-group btn-group"> <span class="input-group-addon"> <i class="fa fa-th-list"></i> </span> {% render_field form.pods|attr:"multiple:multiple"|attr:"data-plugin-multiselect" title="group_member" class="form-control" %} </div> </div> </div> ... I need the pre-selected initial values of the checkbox to be rendered dynamically. Currently self.fields['pods'].initial = [pod.id for pod in associated_pods] will only tick one checkbox although there is more than one associated pods. -
High performance search on Django and select items? MySQL Database
I have a MySQL database and i have a Django model X with more than 1 million entries. I have to develop a web site where the user is able to search over 1 million items and select multiple items. I access these items through a ManyToMany relationship using Django forms with a MultipleChoiceField. But it's taking too much time when Django tries to load the 1 million items in a Django Form. How can i implement this efficiently in Django? The user should be able to search over the 1 million items efficiently and select multiple items. I already tried using django-select2. This let me search, filter and select multiple items but it's still very slow -
Replace items of a dictionary with django objects
I have a python script which provide answer in this format: a = {"('Open', 'New Delhi', 'Mumbai')": [{7: [5]}], "('Open', 'Doon', 'Gurgaon')": [{8: [2, 2, 1, 2]}, {7: [2, 4]}]} where the key is the route and the keys of dictionaries inside the list are truck_id (i.e. 7,8,7 are the truck_id) and (5,1,2,4 are the items_id) I want to replace the truck_id and items_id with django model objects. I tried this for the truck_id but it doesn't work container_trucks_final = {} for k,v in open_trucks.items(): for i in v: for m,n in i.items(): try: m = get_object_or_404(Truckdb, id=m) container_trucks_final[k] = m except: m = [get_object_or_404(Truckdb, id=m_id) for m_id in m] container_trucks_final[k] = m How can I do that ? Models.py class ItemBatch(models.Model): ttypes =(('Open','Open'),('Container','Container'),('Trailer','Trailer'),('All','All')) uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by') name = models.CharField(max_length=30) pid = models.IntegerField(blank=True) quantity = models.IntegerField(blank=True) length = models.FloatField(blank=True) width = models.FloatField(blank=True) height = models.FloatField(blank=True) volume = models.FloatField(blank=True) weight = models.FloatField(blank=True) truck_type = models.CharField(max_length=255,default=0, choices=ttypes) origin = models.CharField(max_length=100, blank=True) destination = models.CharField(max_length=100, blank=True) time = models.DateTimeField(max_length=100, blank=True,default=now) rtd = models.BooleanField(default=False) #ready to dispatch checkbox def __str__ (self): return self.name class Truckdb(models.Model): Name = models.CharField(max_length=30) Category = models.CharField(max_length=30) Truckid = models.IntegerField(blank=True) Length = models.FloatField(blank=True) Breadth = models.FloatField(blank=True) Height = … -
Code a drag and drop timeline project planner
I am beginner in web development who knows HTML,CSS and Python. I am trying to make a web app in Django which includes a drag and drop project planner. I am a little confused on how to make this timeline. Can you guys suggest some plugins,tutorials or articles that can help me execute this? -
UNIQUE constraint failed: app_item.sku
Users can register and login to my website. Users those who are currently logged in to my website could create their own item list. But when the create button is submitted, it returned me this error: UNIQUE constraint failed: app_item.sku but I have added user to my model. here it is class Item(TimeModel): item_name = models.CharField(max_length=50) sku = models.CharField(max_length=20, unique=True) author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE) how can this issue be tackled? -
How to elsaticsearch query in ajax?
I want to try to search using elasticsearch by ajax. Unfortunately, the response is "POST http://localhost:9200/kmm_santri/_search 406 (Not Acceptable)" $('#list_kegiatan').blur(function(){ var query = { "sort": [ {"kelompok.raw": {"order": "asc" }}, {"kelas.raw": {"order": "asc" }}, {"sex.raw": {"order": "asc" }}, {"nama.raw": {"order": "asc" }}, ], "from" : 0, "size" : 100, "query": {"match_all": {}} }; $.ajax({ url: "http://localhost:9200/kmm_santri/_search", crossDomain: true, type: 'POST', dataType: 'json', data: query, success: function(result){ console.log(result); } }); }); -
How can i render templates on the basis of conditions in django DetailView
I have tried overriding get_templates_name().But it is not helping me out. def get_template_names(self): theme = Themes.objects.filter(theme_creator=self.request.user) for t in theme: if t.technology_theme == True: return ["landing/preview/preview1.html/"] elif t.default_theme == True: return ["landing/categories/technology/technology1.html/"] -
Short if condition & for loop in django template
How can I in easily way list all of telephone numbers in td assigned to a given person with a foreign key in one-line statement? telefony_list, osoby_list and email_list contains all objects pushed from generic ListView. <tbody> {% for osoba in osoby_list %} <tr> <td>{{osoba.id}}</td> <td>{{osoba.imie}}</td> <td>{{osoba.nazwisko}}</td> <td>{% tel.telefon for tel in telefony_list if tel.osoba_id == osoba.id %}{% endfor %}{% endif %}</td> </tr> </tbody> -
Update data in database based on order id in Django
I am new in Django. I want to update the value in the database based on the order id. Therefore, every order id has different updates. But, i only can update the last item that i add to the order. And every previous orders that i have, will directly follow the update from the last item. models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) FoodId = models.TextField() Item = models.TextField() Qty = models.IntegerField(blank=False) Price = models.TextField() TotalPrice = models.TextField() Note = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=100, null=True) views.py def kitchen_view(request): chef_view = OrderItem.objects.all() if request.method == "POST": order_id = request.POST.get("OrderId") status = OrderItem.objects.filter(OrderId=request.POST.get("OrderId")) status.status1 = OrderItem.objects.update(food_status=request.POST.get("food_status")) return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view}) The result should be able to update the food_status based on the order_id. Therefore, every order_id may have different food_status and show it to the template. Anyone can help me to solve this problem? I really need the help to solve this issue. Really appreciate. -
how to fix error in my PUT function (views.py)?
I am trying to make a simple restful API (CRUD) using Django and Django-rest-framework. The delete, update and post works but the put function is the problem. I tried to comment each part of that and every time I try to run server it gives me some errors. The first error is gives me is: from article.views import ArticleView File "C:\Users\Amirhossein.DESKTOP-FA436E8\Desktop\Simple -API\project\article\views.py", line 33 if serializer.is_valid(raise_exception=True): ^ SyntaxError: invalid syntax Even though I had used this syntax in my POST method and it worked. Then I tried to comment this part of my code and it gave me back this error: from article.views import ArticleView File "C:\Users\Amirhossein.DESKTOP-FA436E8\Desktop\Simple -API\project\article\views.py", line 37 def delete(self, request, pk): ^ SyntaxError: invalid syntax Here is my code: def put(self, request, pk): saved_article = get_object_or_404(Article.objects.all(), pk=pk) data = request.data.get('article') serializer = ArticleSerializer(instance=saved_article, data=data, partial=True if serializer.is_valid(raise_exception=True): article_saved = serializer.save() return Response({"success": "Article '{}' updated successfully".format(article_saved.title)}) Here is the picture of my code: enter image description here -
Create Another model with related model on signal in django
Assumption models are: ACCOUNT_UNDER = ( ('Assets', 'Assets'), ('Bank', 'Bank'), ('Cash-in-Hand', 'Cash-in-Hand'), ) class Account(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') under = models.CharField(max_length=100, choices=ACCOUNT_UNDER) class MPTTMeta: order_insertion_by = ['name'] class JournalVoucher(models.Model): date = models.DateField() class Transaction(models.Model): voucher = models.ForeignKey(JournalVoucher, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField(default=datetime.date.today) class TransactionEntry(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, blank=True, null=True) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="transaction_entries") debit = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) credit = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) class Ledger(models.Model): account_name = models.CharField(max_length=254) class LedgerEntry(models.Model): ledger = models.ForeignKey(Ledger, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="debit_account") debit = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) credit = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) balance = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) In django admin, #using django-nested-admin from django.contrib import admin import nested_admin class TransactionEntryInline(nested_admin.NestedTabularInline): model = TransactionEntry extra = 0 class TransactionInline(nested_admin.NestedStackedInline): model = Transaction inlines = [TransactionEntryInline] extra = 0 @admin.register(JournalVoucher) class JournalVoucherAdmin(nested_admin.NestedModelAdmin): inlines = [TransactionInline] Accounting Example: Jan. 10 Creative Advertising obtained a loan of Rs. 20,000 from the bank. Journal Voucher Date Account Debit Credit Jan 10 Cash 20,000 Bank Loan 20,000 Ledger: Bank Loan Account Date Account Amount Date Account Amount Jan 10 Cash 20,000 Cash Account Date Account Amount Date Account … -
Django Not Serving Staticfiles after collectstatic
So I'm following this tutorial on serving staticfiles after collectstatic and after changing from {% load static %} to {% load staticfiles %} AND adding ` + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)` to urls.py AND adding ` STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ]` to the url pattern it still is not loading the static files. I tried using findstatic and it still tries to look in static instead of staticfiles. I would appreciate any help, I've tried reading the documentation and added everything but it refuses to look at staticfiles folder and goes to static. https://scotch.io/tutorials/working-with-django-templates-static-files#toc-settings-for-managing-static-files https://github.com/amos-o/djangotemplates -
Django Rest Framework view set url filter errors
I am building a backend using the django rest framework. I am building the defauly django user viewsets and urlpattern routers. I want to add a filter for the username in the url if there is a username passed in and if not, then show all the users. I will have my code below. This is the views: from django.contrib.auth.models import User from ..serializers import UserSerializer from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(username = username) return queryset Here is the urls file: from users.api.views.userViews import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'(?P<username>.+)/$', UserViewSet, base_name='user') urlpatterns = router.urls here is the urls in the settings: path('api/users/', include('users.api.urls.userUrls')), I want the following: api/users/ to return all users & api/users/testAdmin to return the admin user object -
Django query users that like each other
I have a Django model that looks like this: class Matches(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) voter = models.ForeignKey(User, related_name='given_vote', on_delete=models.CASCADE) vote = models.BooleanField(default=False) I am trying to write a query using django's ORM, but am stuck. Given a user (let's say user_1), I want to return all rows where user_1 has voted True on another user (let's say user_2) AND user_2 has voted True on user_1. I'm thinking I might need to use Django's Q function but not sure. Here is what I've got: class User: def calculate_matches(self): return Matches.objects.filter(Q(voter=self, vote=True) & Q(user=self, vote=True)) -
Naive Bayes ClassifierIndexError: list index out of range
I am trying to run this code using Python 3.6.4 Shell however I had face this problem and I don't know where is the error in my code. Please help, thank you. This is the traceback error: RESTART: C:\Users\User\Desktop\project-files-master\CyberBullying_classifier.py starting main Naive Bayes Classifier Traceback (most recent call last): File "C:\Users\User\Desktop\project-files-master\CyberBullying_classifier.py", line 292, in true_positives,true_negatives,false_positives,false_negatives = get_PR(NB_results,expected_output_list) File "C:\Users\User\Desktop\project-files-master\CyberBullying_classifier.py", line 125, in get_PR expected_outcome = expected_output[expected_output_index] IndexError: list index out of range This is the link to my code file. https://www.codepile.net/pile/NB8E4Lk6 -
Django request.user becomes anonymous after redirect. Using custom user model and authentication
I am using django 2.1.7 and python 3.6.5 version, extending the django user model with 'AbstractUser' and overwritting django authenticate method. Everything seems to work fine until login, but when the page redirects to home request.user becomes null. I have tried to render instead of redirecting, this seems to works but then when i open the same page in different tab or refresh the page i got 403 forbidden error (CSRF verification failed. Request aborted.) Tried the below settings, but still does'nt seem to work CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False settings.py LOGIN_URL = '/' LOGIN_REDIRECT_URL = 'home' AUTH_USER_MODEL = 'hygie_portal.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'hygie_portal.mybackend.MyBackEnd', ) models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_admin = models.IntegerField(blank=True, null=True) role = models.CharField(max_length=256, blank=True, null=True) def set_is_admin(self, is_admin): self.is_admin = is_admin def set_role(self, role): self.last_update = datetime.now() self.role = role forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.forms import TextInput,EmailInput,PasswordInput CustomUser = get_user_model() class LoginForm(forms.Form): """Login form.""" username = forms.CharField(label='Username', max_length=100) password = forms.CharField( widget=forms.PasswordInput()) class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email') admin.py from … -
Text overlap of Django official website in Chrome?How to fix it?
Overlap Text in Chromeenter image description here -
File not being saved synchronosly
I have written a serilaizer to create a model instance. It requires the request serilaizer field to create a file using the request being sent, save it, execute a system command which has the saved file as one of its argument. I am facing an issue with the saving of the file. def _save_file(input): with open(settings.PATH, "w+") as file_handle: file_handle.write(input) This is the code I am using to save the file. The problem is that the file gets saved out of order and much later which causes the request to not being able to read the saved file. I am not sure why this is not working sequentially in order. Please help.