Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add django-cms articles specific to a page template created using html and django views?
I am creating a page on my website where I need a section where I can pull data for an item X from the SQL database associated with the django models and another section where I need to put an article created/written specifically for that item X. similarly, for all items in that model, I will need to do the same. There must be a way to save the articles with IDs of items in django models, so I can pull the linked articles. I have gone through the django-cms docs and read about 'page lookups' but haven't been able to implement it. Adding any article is easy using aldryn-form plugins but I need to have an artcile from the DB specifically related to that item. -
How can I integrate paystack with Django
Does anyone know how I can integrate my Django website with Paystack. I checked the documentation and all they seem to be writing about is PHP. -
How do I deal with the "|as_crispy_field got passed an invalid or inexistent field" error message?
I am making a web app with a few pages. On one of the pages, I would like to have a form that looks something like this However I keep getting an error message saying: " raise CrispyError('|as_crispy_field got passed an invalid or inexistent field') crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field [10/Jul/2019 23:21:12] "GET /year2 HTTP/1.1" 500 148042 " Here is my year2.html which appears to be where the error occurs: {% extends "HelloDjangoApp/layout.html" %} {% load crispy_forms_tags %} **HelloDjangoApp/year2.html** {% block content %} <form method="post" novalidate> {% csrf_token %} <div class="row"> <div class="col-6"> {{ form.name|as_crispy_field }} </div> <div class="col-6"> {{ form.email|as_crispy_field }} </div> </div> {{ form.job_title|as_crispy_field }} {{ form.bio|as_crispy_field }} <button type="submit" class="btn btn-success">Calculate</button> </form> {% endblock %} For context, here is my views.py from django.shortcuts import render from django.http import HttpResponse from datetime import datetime from django.shortcuts import render # Added for this step from django.views.generic import CreateView from .models import Person class PersonCreateView(CreateView): model = Person fields = ('name', 'email', 'job_title', 'bio') def index(request): now = datetime.now() return render( request, "HelloDjangoApp/index.html", # Relative path from the 'templates' folder to the template file # "index.html", # Use this code for VS 2017 15.7 and earlier … -
django-rest-framework-datatables JSON will not Load
I am using django-rest-framework-datatables and following the directions but can not get to work. I have followed this: https://django-rest-framework-datatables.readthedocs.io/en/latest/index.html I am getting the warning "DataTables warning: table id=transactions - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1" my URLS are in an app called "custom" app_name = 'custom' router = routers.DefaultRouter() router.register(r'exber', views.ExberViewSet) urlpatterns = [ url('^exber/api/', include(router.urls)), url('^exber/', views.exber_index, name='exber'), ] my views: class ExberViewSet(viewsets.ModelViewSet): queryset = Exber_transactions.objects.all() serializer_class = ExberSerializer def exber_index(request): return render(request, 'custom/exber/transactions.html) the model: class Exber_transactions ( models.Model ): date = models.DateField ( null = True, blank = True ) desc = models.CharField ( max_length = 100 ) activity = models.CharField ( max_length = 100 ) qty = models.DecimalField ( max_digits = 12, decimal_places = 3, default = 0 ) price = models.DecimalField ( max_digits = 12, decimal_places = 2, default = 0 ) accrued_int = models.DecimalField ( max_digits = 12, decimal_places = 3, default = 0 ) amount = models.DecimalField ( max_digits = 12, decimal_places = 2, default = 0 ) the serializer: class ExberSerializer(serializers.ModelSerializer): id = serializers.IntegerField ( read_only = True ) class Meta: model = Exber_transactions fields = ('date','desc', 'activity','qty', 'price', 'accrued_int', 'amount') datatables_always_serialize = ('id',) and this … -
result wasn't alphabetical order when i'm using a "sort function"
i'm a beginner and i'm wan't to do something here's my problem form DJANGO part 3 tutorial i put 3 questions and i want it to show but in a alphabetical order here's what i did. the normal result is this: bWhat's 02aWhat's 01cwhat's 03 def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:3] output = (''.join([q.question_text for q in latest_question_list])) output_list = list(output) output_list.sort() return HttpResponse(output_list) and then i try to convert it into a list() to sort but here's what i got result: '''000123WWaaaabchhhssstttw -
How to make this function work in views.py of django?
I want to make this Destination() function work with multiple variables because I don't want to write it again and again. I made it equal with two variables but it is not working. How to solve this problem? def index(request): a,b = Destination() a.desc = 'Hello, How are you!' a.img = '01.jpg' b.desc = 'Hello, How are you!' b.img = '02.jpg' target = [a,b] context = { 'target': target } return render(request, 'index.html', context) -
Django multiple templates in single view
I have 2 templates first one team vs team and last one player vs player. For example, dota2 matches team vs team. However, heartstone matches are player vs player. my url path '<str:gameslug>/turnuva/<str:tournamentslug>/mac/<str:lolslug>' I want like this; if gameslug==lol return render template1 if gameslug==heartstone return template2 How can i do? def game_detail(request,tournamentslug,lolslug,gameslug): game = get_object_or_404( LeagueofLegendsGame, tournament__tournament_slug=tournamentslug, lol_slug=lolslug, tournament__game__slug=gameslug ) context={ 'game':game, } return render(request,'esports/lolgame.html',context) -
Django query "icontains" works only with numbers
My query: result = Test.objects.filter(Q(description__icontains=data) | Q(code__icontains=data)) if 'data' in a number it works, if 'data' is a word not work, why? TY -
I have a trouble after uploading debug files to sentry on-premise
I used aws pre-configured sentry image and everything work fine except debug files . When I go to debug files , this show me like the following image and in console , 500 internal server error occurs. Error image Console logs -
How to fetch a product from woocommerce api based on the sku?
I found difficulty in fetching a product from my woocommerce website to my django app based on the sku. In the official documentation here: http://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-product i found a solution only for fetching the product knowing the post id(794 in the example),like: print(wcapi.get("products/794").json()) Is there a way to catch the product based on the sku? -
Django rest framework serialize filtered Foreign keys
Models.py class ModelA(models.Model): ... class ModelB(models.Model): parent = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name='modelB', blank=True, null=True) string = models.CharField() If I need to search by "string" field I can write modelA.objects.filter(modelB__string__icontains=request.GET['string']).values('modelB__string') Which return ModelB instances only with necessary string values: <QuerySet [{'modelB__string': 'Test1'}]> But if I try to serialize this queryset, I'll get the whole object with all FK: "modelB": [ // I need only this FK { "id": 46, "string": "Test1", "item": 1 }, // ------------------- { "id": 47, "string": "Test85", "item": 1 }, { "id": 48, "string": "Test64", "item": 1 } ] -
Editing the saved user profile in django
I created a registration form with django user model with adding an extra field confirm_pwd. Now i need to edit the entered details of a particular user.In the edit page i need to display all the form fields which are in registration form.I wrote the logic for it. Here is my code models.py from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py from django import forms from django.forms import ModelForm from .models import UserProfileInfo from django.contrib.auth.models import User class EditProfileForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_pwd = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ['first_name','last_name','username','email','password'] help_texts={ 'username': None } def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_pwd") print(confirm_password) if password != confirm_password: print("yes") raise forms.ValidationError( "password and confirm_password does not match" ) views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from .models import UserProfileInfo from django.contrib.auth.models import User from .forms import UserForm,UserProfileInfoForm,GithubInfo,EditProfileForm from django.contrib.auth import authenticate, login, logout from django.urls import reverse def edit_profile(request): user = request.user form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'username':user.username, 'email':user.email, 'password':user.password}) pform = UserProfileInfoForm(request.POST or None, initial={'confirm_pwd':confirm_pwd}) if request.method == 'POST': if form.is_valid() and pform.is_valid(): user.first_name = request.POST['first_name'] user.last_name = … -
__init__ override in Form class
Please explain the three lines in if statement I extracted this from my friends project. from django import forms from posts import models class PostForm(forms.ModelForm): class Meta: fields = ("message", "group") model = models.Post def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) if user is not None: self.fields["group"].queryset = ( models.Group.objects.filter( pk__in=user.groups.values_list("group__pk") ) ) -
Matching query does not exists on first time login
I have elasticsearch over my database. I indexed a table called Student, Student is having a Foregin key of User my sample code goes like this, index.py class Meta: model = Student related_models = [User] fields = ['id', 'class','classteacher'] def get_instances_from_related(self, related_instance): if isinstance(related_instance, User): return Student.objects.get(user= related_instance.id) models.py class Student(CommonBase): """ Student details. """ user = models.ForeignKey(User, on_delete=models.CASCADE) classteacher = models.ManyToManyField('Teacher', null=True, blank=True) class = models.IntegerField( blank=True, null=True) class User(CommonBase, AbstractUser): first_name = models.CharField(blank=True,max_length=255, verbose_name='first name') dob = models.DateField(null=True, blank=True) profile_pic_link = models.CharField(max_length=200, null=True, blank=True) email = models.EmailField(max_length=254, unique=True, verbose_name='email address') When I try to login via Django admin I am getting, self.model._meta.object_name students.models.Student.DoesNotExist: Student matching query does not exist. ERROR "POST /admin/login/?next=/admin/ HTTP/1.1" 500 203435 This happens because of this lines, def get_instances_from_related(self, related_instance): if isinstance(related_instance, User): return Student.objects.get(user= related_instance.id) ie, It tries to get "User" through "Student" while login through Django. I made a temporary fix by putting a try catch , def get_instances_from_related(self, related_instance): if isinstance(related_instance, User): try: return Student.objects.get(user= related_instance.id) except: logger.error(str(e)) Is there any better solutions?? -
How to have multiple images and description in one loop in function in views.py of django?
I want to have multiple images and description in loop. But I don't know how implement for loop so that I don't have to write destination.img and destination.desc again and again. How could I manage image and description in a separate way. The second thing I don't want Destination() function to be written again and again. def index(request): number = 2 for index in range(number): destination = Destination() destination.desc = 'Hello, How are you!' destination.img = '01.jpg' target = [destination] context = { 'target': target } return render(request, 'index.html', context) -
Not all form fields are reaching model during save
I'm sending an image field with crop dimensions to django in order to edit the image before saving. The edit and save part are working, but only when I hardcode the required dimensions. My problem is that in the model the cropping dimensions don't turn up and show as None. The model being saved is processed using a formset. The cropping dimensions were added later, I've not forgotten to migrate the fields. Here's my code: view.py for i, form in enumerate(picture_formset_from_request.forms): if form.is_valid(): form.save() From pycharm this would appear to be the file where the data is not passed any further: forms/models.py def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, 'created' if self.instance._state.adding else 'changed', ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() # <- it seems to go wrong here self._save_m2m() else: # If not committing, add a method to the form to … -
How to use django-admin in registering models, list_display
I want to display some fields in admin how to specify it? I have used list_display but it's showing error : (admin.E108) The value of 'list_display[1]' refers to 'holiday', which is not callable, an attribute of 'EmpLeaveAdmin', or an attribute or method on 'leave. Leave'. class EmpLeaveAdmin(admin.ModelAdmin): list_display = ('name', 'holiday') -
How to upload file larger than 2.5MB to django?
I my goal is to upload file larger than 2.5MB to django server. I can upload file, if it is smaller than 2.5MB, if file is bigger then 2.5MB I get 413 Payload too large in browser. And I do not understand why. I set MAX_UPLOAD_SIZE = 429916160 MEDIA_ROOT = os.path.join(BASE_DIR, 'files') MEDIA_URL = '/files/' and FILE_UPLOAD_MAX_MEMORY_SIZE = MAX_UPLOAD_SIZE in my settings.py. Currently I use django development server without apache or nginx. My models.py: def validate_file_extension(value): ext = os.path.splitext(value.name)[1] # [0] returns path+filename valid_extensions = ['.vsdx'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') class UpLoadFile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to=path, validators=[validate_file_extension]) uploaded_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username + '/' + self.file.name class UploadFileForm(forms.ModelForm): file = forms.FileField(required=True, label="") class Meta: model = UpLoadFile fields = ('file',) views.py: if request.method == 'GET': upload_file_form = UploadFileForm() all_files = UpLoadFile.objects.select_related("user").filter(user__username=request.user).all().order_by("-uploaded_at") return render(request, 'interface/files.html', {'page_title': 'Datoteke', 'files': all_files, 'upload_file_form': upload_file_form}) elif request.method == 'POST': if "upload-file" in request.POST: file_name = request.FILES.get("file") username = request.user if bool(os.path.exists(f'files/{username}/{file_name}')): messages.error(request, "Datoteka s tem imenom že obstaja!") return redirect('files') else: upload_file_form = UploadFileForm(request.POST, request.FILES) upload_file_form.instance.user = username if upload_file_form.is_valid(): upload_file_form.save() messages.success(request, "Datoteka je uspešno dodana!") return redirect('files') messages.error(request, "Te vrste datoteke ni mogoče naložiti … -
search page in django
Basically, I need to create a search page in django which has input fields say po_no,po_date, description . A user might enter any or all of the details and click search. It should go to another html template and view the details matching it to the details entered. po.html <form method = "GET" action="{% url 'po_dtl' %}"> <label class="sr-only">PO NUMBER</label> <input type="text" name="a" class="form-control" placeholder="PO NUMBER" value="{{request.get.a}}"> <label class="sr-only">PO DATE</label> <input type="text" name="b" class="form-control" placeholder="PO DATE" value="{{request.get.b}}"> <label class="sr-only">DESC</label> <input type="text" name="c" class="form-control" placeholder="DESCRIPTION" value="{{request.get.c}}"> <label class="sr-only">APPR</label> <input type="text" name="d" class="form-control" placeholder="APPROVED DATE" value="{{request.get.d}}"> <label class="sr-only">SUPP</label> <input type="text" name="e" class="form-control" placeholder="SUPPLIER CODE" value="{{request.get.e}}"> <label class="sr-only">BUTTON</label> <button class="btn btn-secondary btn-block mt-4" type="submit">Search</button> </form> po_dtl.html {% if search_results %} {% for post in search_results %} PO NO: <span class="float-right">{{post.po_no}} </span> PO date: <span class="float-right">{{post.po_date|date:"F d, Y"}}</span> Supplier Code: <span class="float-right">{{post.sup_code}}</span> <table> <thead> <tr> <th>Item Code</th> <th>TAX</th> <th>Amount</th> <th>Quantity</th> </tr> </thread> <tbody> <tr> <td>{{post.item_code}}</td> <td>{{post.tax}}</td> <td>{{post.amt}}</td> <td>{{post.qty}}</td> </tr> </tbody> </table> {% endfor %} {% endif %} views.py def po_head(request): if request.method == 'GET': p_no = request.GET.get('a') date = request.GET.get('b') desc = request.GET.get('c') ap_date = request.GET.get('d') s_code = request.GET.get('e') search_results = po_detail.objects.filter(Q(po_no=p_no)|Q(po_date__iexact=date)|Q(sup_code=s_code)) return render(request,'erp/po_dtl.html',{'search_results':search_results}) else: return render(request,'erp/po.html',{}) @login_required def po_dtl(request , po_no): context = … -
Running a background task continuously in Django
I am running a server in Django,which is taking values continuously. The function usede foreverloop in it, when I call that function it nevers gets out of the loop. My problem - I want to take values continuously from the server and use it afterwords wherever I want. I tried threading, what I thought I could do is make a background task which keeps on feeding the database and when I want to use I can take values from it. But I dont know how to do this ip = "192.168.1.15" port = 5005 def eeg_handler(unused_addr, args, ch1, ch2, ch3, ch4, ch5): a.append(ch1) print(a) from pythonosc import osc_server, dispatcher dispatcher = dispatcher.Dispatcher() dispatcher.map("/muse/eeg", eeg_handler, "EEG") server = osc_server.ThreadingOSCUDPServer( (ip, port), dispatcher) # print("Serving on {}".format(server.server_address)) server.serve_forever() -
how to display all the reviews for the particular product?
With the below code i am adding reviews for some particular product in the database and it is doing good but the problem is while displaying the reviews for the selected product.I get confused how can i display the all reviews of some product and which review done by which user at what time? models.py class Product(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) featured = models.BooleanField(default=False) def __str__(self): return self.name class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.review views.py def detail(request,pk): product = College.objects.get(pk=pk) form = ReviewForm() return render(request,'products/detail.html',{'product':product,'form':form}) @login_required(login_url='products:signin') def review(request,pk): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.product = Product.objects.get(pk=pk) review.user = request.user review.save() messages.success(request, "Review saved") return redirect('products:detail',pk) else: messages.error(request,'error in form') return redirect('products:detail', pk) detail.html <h3>All reviews(total.no. of reviews?)</h3> # Here i want to display all reviews and which is done by which user and at what time <div class="col-lg-6 col-md-6 mb-6"> <form method="post" action="{% url 'products:review' product.pk %}"> {% csrf_token %} {% form.as_p %} <input type="submit" class="btn btn-success"> </form> </div> -
Why in response the data of different table coming in different array?(using Django, Rest framework, MySql)
Actually I have joined various tables in Django using Rest framework and MySql database. The response is coming correctly but data from different table is coming in different arrays. But I want the response in a single array.I am posting the present response and the required response. Please help me out with this. The response is coming like this : { "count": 282566, "next": "http://127.0.0.1:8000/inventoryregister/?limit=1000&offset=1000", "previous": null, "results": [ { "inventory_batch": { "inventory_reg": { "id": 1, "company_id": "28", "inventory_group_id": "1", "is_owned": "1", "cost_center": { "location": "Bangalore Production", "lob_id": 230, "nick_name": "Bangalore Production", "lob": { "lob_name": "LAB", "cs_id": "3" }, "department": null }, "inventory_date": "2019-04-19", "inventory_action": "2", "product_type2_id": "57", "asset_type": { "asset_type": "Fixed Assets" }, "dimension": null }, "batch_no": "New10190420192" }, "barcode_no": "0803843276" } But I want the response in this way : { "count": 282566, "next": "http://127.0.0.1:8000/inventoryregister/?limit=1000&offset=1000", "previous": null, "results": [ { "id": 1, "company_id": "28", "inventory_group_id": "1", "is_owned": "1", "location": "Bangalore Production", "lob_id": 230, "nick_name": "Bangalore Production", "lob_name": "LAB", "cs_id": "3" "department": null "inventory_date": "2019-04-19", "inventory_action": "2", "product_type2_id": "57", "asset_type": "Fixed Assets" "dimension": null "batch_no": "New10190420192" "barcode_no": "0803843276" } } -
What is the cost of many null-foreign keys in a model?
I have a Post model, an Image model, and a Channel model. I have a foreign key in the Image model connected to the Post model. Additionally, I am trying to add a nullable foreign key connected to the Channel model. class Image(models.Model): post = models.ForeignKey(Post, null=True, blank=True, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, blank=True, on_delete=models.CASCADE) news = models.ForeignKey(news_models.News, null=True, blank=True, on_delete=models.CASCADE) message = models.ForeignKey(messenger_models.Message, null=True, blank=True, on_delete=models.CASCADE) channel = models.ForeignKey(messenger_models.Message, null=True, blank=True, on_delete=models.CASCADE) file = ProcessedImageField(upload_to='uploads/%Y/%m/%d/', processors=[Transpose()], format='JPEG', options={'quality': 50}, blank=True) My concern is that the channel field will be mostly null as I only need one image per channel. But the image has to be connected with a Post. So each one channel has one image that is connected to the post. However, There will be incompariably more posts and images than a channel, so the channel field in the Image model will be wasted most of the time. Another solution I thought of is creating a new image model exclusively for the Channel model and when the new image instance is created, manually copy the image from the original image-post connected instance. But I cannot relationally connect my Channel model to the Image model in this way, which … -
Images on my Django website are not loading
I am having images on my menu template which when clicked I want to redirect to another template in Django **Below is my code for the menu template:** {%for count in item%} <div class="col-md-6 col-lg-4 menu-wrap"> <div class="heading-menu text-center ftco-animate"> <h3>{{count.supper}}</h3> </div> <div class="menus d-flex ftco-animate"> <div class="menu-img img" style="background-image: url({{count.pic.url}});"></div> <div class="text"> <div class="d-flex"> <div class="one-half"> <h3>{{count.name}}</h3> </div> <div class="one-forth"> <span class="price">${{count.price}}</span> </div> How can i make this happen ? Can an onclick event be applied? -
how to scroll to bottom after ajax insert using jquery or js?
how to create array using for loop in django view?? success: function(result) { console.log("result : " , result); alert("insert success") window.history.pushState("", "", '/wm/myshortcut/') var raw_template = $('.myshortcut_row').html(); var tpl = _.template(raw_template); var rendered = tpl({ shortcut_id : result.shortcut_id, shortcut_title : result.shortcut_title, shortcut_content : result.shortcut_content, }); $(rendered).appendTo($('.myshort_list_area')); // I want to scroll to bottom how to make it? } Can I make the bottom visible through the scroll after input? Another question. I want to move the scroll up a little after moving as below. Is it possible? $ (". go_btn"). click (function () { const number = $ (". go_input"). val (); if (number == 1) { $ ('html, body'). animate ({ 'scrollTop': $ ("# index_first"). offset (). bottom }); } $ ('html, body'). animate ({ 'scrollTop': $ ("# index _" + number) .offset (). top }); }} The reason is that some of them are covered because of the navigation. Thank you very much for letting me know about this.