Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DB query becomes 'None' as seen with DEBUG=True inside a long-running management command
I am using Django 2.2 in several modes, one of which is a long-running management command which runs under Supervisord. This has worked fine with several weeks of testing. However, today I witnessed something disturbing which I can't explain. I am running all this in a TEST environment, so I have DEBUG set to True as well as my logger debug levels turned up. Because of this, I can see every DB query and have a good idea of where the problem occurred. The task had been running fine for about 17 hours, which is nothing compared to how long it has run successfully in the past (many days). What happened was, the actual query that was supposed to go out to the DB was missing. It literally showed 'None' in the DB log. Eg: 2020-05-29 10:58:36,001 DEBUG utils (0.000) None; args=('SKFHJ7H5S6',) which, when all is well, should be something like: 2020-05-29 10:58:36,001 DEBUG utils (0.000) SELECT `item`.`id`, `item`.`name`, `item`.`info` FROM `item` WHERE `item`.`id` = 'SKFHJ7H5S6'; args=('SKFHJ7H5S6',) Once it got in this mode, it was perfectly reproducible. Once I restarted the process, haven't seen it since. Also of note.. I have 2 threads in this task. Queries continued to work … -
How to send foreignkey data type in API by DRF
I have API written by Django Rest Framework: models.py STATUSES = (("F", "free"), ("R", "registered"), ("N", "not free") ) class Collector(models.Model): ip = models.TextField() class Meta: verbose_name = 'Коллектор' verbose_name_plural = 'Коллекторы' ordering = ('ip',) def __str__(self): return str(self.ip) class Port(models.Model): port = models.CharField(max_length=1000) status = models.CharField(max_length=1, choices=STATUSES, default="F") collector_link = models.ForeignKey(Collector, on_delete=models.CASCADE) class Meta: verbose_name = 'Порт' verbose_name_plural = 'Порты' ordering = ('port',) def __str__(self): return str(self.port) serializers.py class CollectorSerializer(serializers.ModelSerializer): class Meta: model = models.Collector fields = ("__all__") class PortSerializer(serializers.ModelSerializer): class Meta: model = models.Port fields = ("__all__") views.py class CollectorAPIView(APIView): serializer_class = serializers.CollectorSerializer allowed_methods = ["POST"] def post(self, request, *args, **kwargs): ip = request.POST['ip'] obj = models.Collector(ip=request.POST['ip']) obj.save() return Response(status=status.HTTP_200_OK) class PortAPIView(APIView): serializer_class = serializers.PortSerializer allowed_methods = ["POST"] def post(self, request, *args, **kwargs): port, status1, collector_link = request.POST["port"], request.POST["status"], request.POST["collector_link"] entry = models.Port(port=port, status=status1, collector_link=collector_link) return Response(status=status.HTTP_201_CREATED) In result, when I'm trying to send data to API in json format like {"port": "1", "status": "F", "collector_link": "10"} (collector_link=10 is id of collector instance in data base) I'm getting the next error: ValueError at /sm/api/v1/port/ Cannot assign "'10'": "Port.collector_link" must be a "Collector" instance How I can to fix it? . -
Django Model Field as Button Group
How can i create a button group using Django model fields and widgets? #models.py GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('-', 'Other') ) class Profile(models.Model): gender = models.CharField(choices=GENDER_CHOICES, max_length=128) This field is rendering as a Select field, a dropdown, but i need a button group, just like this. -
Is there a Django equivalent for writing a SQL SELECT statement with a function in the WHERE clause?
I have a series of protein sequence alignments with inserts ('-' character) that need to be removed so I can search for a pattern in the sequence. I can do this with the following SQL query: select sequence from sequences where replace(sequences.sequence,"-","") like "%"+pattern+"%" As I understand it, having the replacement and pattern matching in a query should be more efficient than looping through every sequence and doing the replacement and pattern matching in python. Is this correct? If #1 is correct, is there a Django equivalent of that query? -
Will Django UUIDFIeld unique=True, blank=True and null=True behave correctly?
I am adding a field to a database: identifier = models.UUIDField(unique=True, null=True, blank=True) but I am curious if this will behave like a CharField or a number field when someone saves an instance in the admin without a value. Will it try to save the value as an empty string "" or will it be smart and save it as null? I am using Postgres for the database. I've seen other answers for CharField, but nothing that speaks to UUIDField. My end goal is to have a field that is guaranteed to be unique, and will default to null. would it be more appropriate to write it as: identifier = models.UUIDField(unique=True, null=True, default=None) or will the admin form validation complain if no value is provided? -
Refresh attribute value after html() with ajax
I am making start/pause button that works like this: var btns = document.querySelectorAll(".repairToggle"); for (i = 0; i < btns.length; i++) { btns[i].addEventListener("click", manageOrderStatus); } function manageOrderStatus() { var func = this.getAttribute("func"); var btn = this; var endpoint = "{% url 'mtn:ajax_repair_toggle' %}"; $.ajax({ url: endpoint, type: "GET", data: { 'func': func, }, success: function (data) { $(btn).html(data); } }); } I have start and stop buttons stored in separate html files: work_order_start.html: <div type="button" class="repairToggle" func="start"> <svg>...</svg> </div> work_order_pause.html: <div type="button" class="repairToggle" func="stop"> <svg>...</svg> </div> In view i render one of the buttons based on the value of func attribute: def repair_toggle(request): ... func = request.GET.get('func') if func == 'stop': return render(request, 'mtn/work_order_start.html') else: return render(request, 'mtn/work_order_pause.html') The problem is it only works once. After the first click it keeps executing ajax call but it sends the same old func value in request. How do i fix that? UPDATE: I figured out the problem. $(btn).html(data); only replaces the svg element. So the func stays the same. If i do this instead: <div type="button" class="repairToggle"> <svg id='funcButton' func="stop"> </div> How do i get func out of svg. I tried this.getElementById('funcButton').getAttribute("func"); but it doesn't work. -
Show popup if user selects a a sequence of options in dropdown menu
I have a multi-step signup form with multiple fields. Relevant to this question are fields asking for the user's country, whether they are employed/earn a steady salary and if they would like to pay for services in installments or upfront. I would like to show a popup page in cases where the user selects the country as Nigeria, indicates that they are employed and that they would like to pay for services in installments. So the popup form would occur the moment the person selects yes to wanting to pay in installments after having selected Nigeria as a country and indicating that they are employed. Here is my html and what I have tried: <div class="row"> {% if form.errors %} <div class="alert alert-error"> <ul> {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> {% endif %} </div> <div class="row"> <div class="col-md-10 col-md-offset-1"> <!-- --> <form id="msform" method="post" action="" > {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" class="form-control"> <ul id="progressbar"> <li>More about you</li> <li>Contact Details</li> </ul> <fieldset> <h2 class="fs-title">More about you</h2> {{form.city}} <br> <select name='country' required class="form-control my-2"> <option value="" disabled selected hidden>Country</option> {% for value, name in form.fields.country.choices %} <option value="{{value}}">{{name}}</option> {% endfor … -
Profile picture is not getting displayed in django template base html page
I am creating a taskToDo web application. Most of the html files under templates are extending base.html file which includes a navbar in which i want to show the user profile picture under navbar of base.html. The profile picture is getting saved under profile_pics directory of 'media' folder. I have tried giving {{user.profile_pic.url}} as the source for image, but still the image is not getting linked My models.py , project urls.py, settings.py, relevant part of views.py are as follows:- models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.core.exceptions import ValidationError from datetime import datetime # Create your models here. class UserCustom(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username #user os object defined above class UserTask(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) label=models.CharField(max_length=264) date=models.DateField() status=models.BooleanField(default=False) def __str__(self): return str(self.label) settings.py from django.contrib import admin from django.urls import path,include from taskApp import views from django.conf.urls.static import static from django.conf import settings # new urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('taskApp/',include('taskApp.urls')), path('logout/',views.user_logout,name='logout'), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) forms.py from django import forms from django.forms.fields import DateField from django.core import validators from django.contrib.auth.models import User from taskApp.models import UserCustom,UserTask from django.contrib.admin.widgets import AdminDateWidget from datetime import datetime,timedelta class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model=User fields=('username','email','password') class … -
django: translate table2 column headers in template
I am using table2 from django in my webapp and I am confused about how to translate the column headers on the frontend. The website has two languages available and I would like the column headers to automatically translate when the user select a language. I have seen in django documentation that I could use localization but it does not seem to work. Here is what I have been able to do so far: table.py class AnormalTable(tables.Table): class Meta: model = stock_anormal template_name = "django_tables2/bootstrap4.html" export_formats = ['csv', 'xlsx'] localize = ("reference_anormales","stock_alerte_calcule","stock_alerte_recommande") models.py class stock_anormal(models.Model): reference_anormales = models.CharField(max_length=100, primary_key=True, verbose_name='items') stock_alerte_calcule = models.FloatField(default=0, verbose_name='safety stock calculated') stock_alerte_recommande = models.FloatField(default=0, verbose_name='safety stock recommended') def __str__(self): return self.reference_anormales html <section class="no-padding-top no-padding-bottom"> <div class="container-fluid"> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">{% trans 'ITEMS IN ALERTE SAFETY STOCK LEVEL' %}</h1> <div> <a href="{% export_url "csv" %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> {% trans 'Generate Report'%}</a> </div> </div> <table> {% render_table table %} </table> </div> </section> </div> </div> it does not work and I cannot find anywhere how to achieve the translation. Would anyone has a clue on how to do it? -
How do I set a default file for `models.FileField()`?
How do I set a default file for models.FileField()? class MyModel(models.Model): myfile = models.FileField(upload_to='mydocs', default=???) The answer would appear to be: myfile=models.FileField(upload_to='mydocs', default='mydocs/myfile.pdf') However this does not result in the desired behaviour when creating a new object. Whereas for other fields like CharField the default= value is displayed on a new form as the widget value. However for FileField it is not, it still results in "no file chosen": So how does one set a default? Should we try to create a new FieldFile instance? Do we need to create a file object? -
Jump to a <Section> when a Textfield gets clicked
so i dont know how to approach it. I got my HTML <input type="text"> Is it possible to jump to a <section> when i click on the textfield so the textfield jumps to the top of the screen so its easier to see? thanks for reading -
How to upload a blob form in Javascript to Django backend
I have an audio blob with the following code I'm looking to send to a form with javascript function sendData(blob) { let fd = new FormData; fd.append('fname', 'test.wav'); fd.append("recording", blob); let token = '{{csrf_token}}'; $.ajax({ url: 'landing/submit/', type: 'POST', headers: { 'X-CSRFToken': token }, data: fd, cache: false, processData: false, // essential contentType: false, // essential, application/pdf doesn't work. enctype: 'multipart/form-data', }); } I am trying to send this to a django form, but i'm getting a 403 error. Here is the view it's being sent to: views.py def post_new(request): if request.method == 'POST': form = PostAudio(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('landing-home') else: form = PostAudio() return render(request, 'landing/submit.html', {'form': form}) What am I missing? Most other folks posting online say this has to do with not using CSRF tokens, but I included them in my headers. -
Django - Restrict Stripe SuccessUrl access
I have just integrated Stripe Checkout with my Django app. However, from their code: session = stripe.checkout.Session.create( customer_email=customer.email, payment_method_types=['card'], line_items=line_items, mode='payment', success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/cart' ) It redirects to a Success_url. I would like to display their order info and send an email from the success page but currently, everyone can visit(would cause random emails etc). Is there a way i can limit this for the person that just checked out? Thank you! -
while running my admin.py I'm getting "ImportError: attempted relative import with no known parent package" error
I am using Django 3.0 version for my project and wants to make a simple registration page but some how my registration information is not reflecting at admin database page. Although python manage.py runserver command is not giving any error but when I tries to run admin.py or views.py then I'm getting these import error which is clearly mentioned in the code section I'm also sharing same code snippet. Here are some snippet of my admin.py, views.py, models.py and settings.py. error [Running] python -u "g:\Study\Python\Django Project\checkproject\checkapp\views.py" Traceback (most recent call last): File "g:\Study\Python\Django Project\checkproject\checkapp\views.py", line 3, in <module> from .models import registerPerson ImportError: attempted relative import with no known parent package admin.py from django.contrib import admin from .models import registerPerson class register(admin.ModelAdmin): list_display = ['firstname', 'lastname', 'email', 'password'] admin.site.register(registerPerson,register) views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import registerPerson def register(request): return render(request,'registration.html') def add_registration(request): firstname = request.POST["first_name"] lastname = request.POST["lastname"] email = request.POST["email"] password = request.POST["password"] info = registerPerson(firstname=firstname, lastname=lastname, email=email, password=password) info.save() return render(request,'registration.html') models.py from django.db import models # Create your models here. class registerPerson(models.Model): firstname=models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.CharField(max_length=30) password = models.CharField(max_length=32) def __str__(self): return self.firstname settings.py [""" Django settings for … -
Django messages framework - lack of i18n by default
By default django messages framework does not localize it's messages correctly. For example As you can see, all other things in admin panel are localized. Here is my settings. LANGUAGE_CODE = 'ru' # I've tried 'ru-RU' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True How to fix this? Thanks in advance. I have django version 3.0.6 -
Why do we write [0] after get_or_create in model_name.object.get_or_create() in django
A function in Faker script to add data in my model Department. department = ['I.T.','C.S.E','M.E.','E.C.'] def add_dept(): d = Department.objects.get_or_create(dept_name=random.choice(depatment))[0] -
I have a problem with the in django search function
I have a problem with my search function. He's tasked to search for movies by name and I don't know how to write it and it works My Views: class AllMovies(ListView): model = Movie template_name = 'All_movies.html' cats = Category.objects.all() def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() search_term = '' context = super(AllMovies, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def search(request): # wszytskie filmy (lista) movier = Movie.objects.all() search_term = '' if 'search' in request.GET: search_term = request.GET['search'] movier = Movie.objects.filter(name__icontains=search_term) paginator = Paginator(movier, 30) page = request.GET.get('page') movier = paginator.get_page(page) get_dict_copy = request.GET.copy() params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode() return render(request, 'AllMovies.html', {'movie': movie, 'params': params, 'search_term': search_term}) Here, two functions should be divided and combined, but I don't know how My urls: path("AllMovies/", AllMovies.as_view(), name="AllMovies"), My templates: <form class="form-inline"> <input class="form-control mr-sm-2 " align="middle" type="search" placeholder="Name Movie" aria-label="Search" name='search' value = "{{ search_term }}"> <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button> </form> The most important thing is for the search engine to work. Help me! -
Replace div element with html()
I have a problem replacing div element with ajax. The idea is start/stop button. There's a list of card elements on the page, each with its own button. Both buttons are stored in separate html files. work_order_start.html: <div type="button" class="repairToggle" order_id="{{ order.id }}" func="start"> <svg>...</svg> </div> work_order_pause.html: <div type="button" class="repairToggle" order_id="{{ order.id }}" func="stop"> <svg>...</svg> </div> Initially only one is rendered on the page based of if condition: {% if order.status == 'DN' %} {% include 'mtn/work_order_pause.html' %} {% else %} {% include 'mtn/work_order_start.html' %} {% endif %} Here's my script: var btns = document.querySelectorAll(".repairToggle"); for (i = 0; i < btns.length; i++) { btns[i].addEventListener("click", manageOrderStatus); } function manageOrderStatus() { var order_id = this.getAttribute("order_id"); var func = this.getAttribute("func"); if(func == 'start'){ var endpoint = "{% url 'ajax_start_order' %}"; } else { var endpoint = "{% url 'ajax_stop_order' %}"; } $.ajax({ url: endpoint, type: "GET", data: { 'order_id': order_id, }, success: function (data) { $(this).html(data); } }); } and my views: def start_repair(request): ... return render(request, 'mtn/work_order_pause.html') def end_repair(request): ... return render(request, 'mtn/work_order_start.html') The view executes correctly, but $(this).html(data); doesn't replace one div with another. What am i doing wrong? -
Showing user's comments on posts in Django
I am adding a comment section for my posts in a blog, I reached to the part where I can add new comments and get it saved in the db and I can view them in the admin, but I am stuck to showing the username and the comment in the comment section, I have to go the admin and choose the name of the user and the blog name to appear in the page, how do i link them together Here is the Models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content', ] success_url = … -
How to query related models in a Haystack search
I am using Haystack with Elasticsearch backend to implement a search of related models. Considering the simplistic models: class Album(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Photo(models.Model): album = models.ForeignKey("app.Model", on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField() Given a search term 'abc', I would like to have search results matching 'abc' in any Album name or description, or any Photo, but be able to present the results by Album with matching photos nested under the Album. In other words an Album is a match if it has either a match in its description or names, or if it contains photos that are a match in their name or description. Results should look like: Album 1 No photo Album 2 Photo 1 Photo 2 ... I tried using a different index for each model, but the relation is lost in the process, or use only one index and index all photos in a MultiValuefield, but I am not sure how to return only the photos that are a match in a SearchQuesyset combining both models. I saw one can take advantage of nested queries in Elacticsearch as in this gist, but I am not sure that it is needed as … -
How to use Django-OTP to use SMS verification
I'm new to Django and am still learning, so the the official django-otp docs are a bit confusing to me. How to add sms verification and how to differentiate between verified and authorized users. Thanks in advance -
Can we use django-allauth and django-rest-auth in single project? And What is the differents?
Whenever I used both in my project then It's showing django-allauth is not recognized. -
Django allauth - Add custom logic after email verification is successful
I am creating an application that has a list of Employees, and after a user registers and verifies their email, I create a relationship between the Employee and their User account. I am using Django all auth, and have the email confirmation on GET set to True. I am unsure on how I can add logic, so after the GET I perform some operations, find use the email to find the user, etc. I have created a custom RegisterSerializer before, but since this is a GET instead of POST I wasn't sure if I could do something similar with EmailVerification. How would I go about adding custom logic for this? -
How to output to the admin panel field relation ManyToMany with through?
There are three models class ParentCategories(models.Model): parent_category_name = models.CharField(max_length=45, choices=PC, unique=True) class Modules(models.Model): parent_categories = models.ManyToManyField('ParentCategories', through='ModulesParentCategories', related_name='parent_categories') class ModulesParentCategories(models.Model): module = models.ForeignKey('Modules', on_delete=models.CASCADE) parent_category = models.ForeignKey('ParentCategories', on_delete=models.CASCADE) primary = models.BooleanField(default=False) I'm trying to put the ManytoMany field on the Modules editing admin page. admin.py class ModulesParentCategoriesAdmin(admin.ModelAdmin): model = ModulesParentCategories extra = 1 class ModulesAdmin(admin.TabularInline): model = Modules inlines = (ModulesParentCategories, ) class ParentCategoriesAdmin(admin.ModelAdmin): model = ParentCategories inlines = (ModulesParentCategories, ) admin.site.register(Modules, ModulesAdmin) admin.site.register(ParentCategories, ParentCategoriesAdmin) But I got this message django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'apps.vendors.admin.ModulesAdmin'>: (admin.E104) 'apps.vendors.models.ModulesParentCategories' must inherit from 'InlineModelAdmin'. <class 'apps.vendors.admin.ParentCategoriesAdmin'>: (admin.E104) 'apps.vendors.models.ModulesParentCategories' must inherit from 'InlineModelAdmin'. System check identified 2 issues (0 silenced). How do I get the relation out to the admin panel? -
image not saved while updating userprofile in django
I am trying to update a userprofile model that i used to save additional information over the inbuilt User model, now when i am trying to update it , the image does not gets saved. I need help to resolve this issue # In views.py @login_required(login_url=LOGIN_REDIRECT_URL) def update_user_profile(request): userobj = get_object_or_404(UserProfile, user=request.user) form = UserProfileForm(data = request.POST or None,files= request.FILES or None, instance=userobj) if request.method=='POST': print(form.is_valid()) if form.is_valid(): profile = form.save(commit=False) profile.picture = form.cleaned_data['picture'] profile.about = form.cleaned_data['about'] profile.save() else: print("NO picure") return HttpResponseRedirect("/blog/profile/") return render(request, "blog/post_update.html", {'form':form}) #models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=200, null=True, blank=True) picture = models.ImageField(upload_to="profile_images/", blank=True) def __str__(self): return str(self.user) #In forms.py class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['about'].widget.attrs.update({'class': 'form-control '}) self.fields['picture'].widget.attrs.update({'class': 'form-control-file'}) class Meta: model = UserProfile fields = ('about', 'picture') # userprofileform.html {% extends 'base.html' %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Create Profile"> </form> {% endblock %} please take a look at the code and help. while registering if the image was uploaded it get's saved , but when i try to update the userprofile directly in profile section image does not get changed and shows …