Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rerun Query on Validation Failure
Here is my views.py. When the validation on the form fails, it returns you back to a blank board because my query cant be executed . What is the easiest way for me to rerun the query ? Thanks for the help ! @login_required def K8_Points_Classroom(request): #context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm(request.POST) if form.is_valid(): form.save(commit=False) form.save() class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form ,'students' : students, 'class_name': class_name,} messages.success(request,("Points were successfully added for student !")) return render(request,'points/k8_points_classroom.html', context) else: <--- Have to rereun query here so students will show again on redirect. messages.warning(request,(form._errors)) return render(request, 'points/k8_points_classroom.html', {'form': form} ) else: return render(request, 'points/k8_points_classroom.html', {'form': form} ) -
django rest_framework serializers inheritance
i'm Django new-bi my serializers code : class ProjectSerializer(serializers.ModelSerializer): class Meta: model = models.Projects fields = ('id', 'content', 'title', 'created') class TalkSerializer(serializers.ModelSerializer): class Meta: model = models.Talk fields = ('id', 'content', 'title', 'created') views code : class TalkViewset(viewsets.ModelViewSet): queryset = models.Talk.objects.all() serializer_class = serializers.TalkSerializer class ProjectViewset(viewsets.ModelViewSet): queryset = models.Projects.objects.all() serializer_class = serializers.TalkSerializer I think this method is too stupid. I want to reuse it as a class. What should I do? -
Email body sent in HTML
I am sending email from tinymce to all subscribed users using this view: def send_newsletter(request): form = NewsLetterEmailForm(request.POST or None) if form.is_valid(): instance = form.save() newsltr = NewsLetterEmail.objects.get(id=instance.id) print(newsltr.status) if newsltr.status == 'Published': subject = newsltr.subject body = mark_safe(newsltr.body) from_email = settings.EMAIL_HOST_USER for newsletter_obj in NewsLetter.objects.all(): send_mail(subject=subject, from_email=from_email, message=body, recipient_list=[newsletter_obj.email]) return render(request, 'newsletter/send-email.html', {'form': form}) but content of email is sent in html: <p><span style="font-family: 'arial black', sans-serif; font-size: 18pt;"><strong>Completely optimize efficient internal</strong></span></p> <p>or "organic" sources with fully tested schemas. Enthusiastically aggregate mission-critical infrastructures via top-line content. Objectively matrix cutting-edge bandwidth before viral action items. Objectively matrix viral users after sticky processes. Dramatically harness adaptive meta-services rather than scalable e-commerce.</p> I used mark_safe() method hoping it will work, but it didn't. How do I solve it? -
How can you filter model objects by attributes of their supermodel?
To get started with Django I did the intro provided by Django itself. In part 5 of it, you write some tests for views and models. After that, they provide you with ideas for more tests. There is where my problem starts. They suggest you to only show Questions with a number of Choices greater than 0. I have no idea how to do that. My current code can be found at https://github.com/byTreneib/django.git. The Django tutorial can be found at https://docs.djangoproject.com/en/3.0/intro/tutorial05/ -
Angular i18n integration with Django REST
Following those tutorials https://dev.to/angular/deploying-an-i18n-angular-app-with-angular-cli-2fb9 and https://devarea.com/building-a-web-app-with-angular-django-and-django-rest/ I manage to deploy angular within django. How can I rework the homePageView to serve index based on language? Expectation for internationalization: We will include a language prefix on each url that will tell Django which language to use. For the Home page it will be something like: myappsite.com/en myappsite.com/fr HomePageView class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) index.html {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>My App</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <!-- index.html --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> <link rel="stylesheet" type="text/css" href="{% static 'fontawesome/css/all.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}" /> </head> <body> <app-root>Loading...</app-root> <script src="{% static 'runtime-es2015.js' %}" type="module"></script> <script src="{% static 'runtime-es5.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es5.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es2015.js' %}" type="module"></script> <script src="{% static 'scripts.js' %}" defer></script> <script src="{% static 'main-es2015.js' %}" type="module"></script> <script src="{% static 'main-es5.js' %}" nomodule defer></script> </body> </html> -
how to update many to many fileds when i'm using request.post or get?
Lab Class class Lab(models.Model): laboratory = models.CharField(max_length=50, unique=True) group = models.ForeignKey(Lab_Group, on_delete=models.CASCADE) LabRequest Class class LabRequest(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) lab_test = models.ManyToManyField(Lab) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) This is how it looked like when I was saving data @login_required def LabRequestToGenerateView(request, pk): lab_group = '' doctor = Doctor.objects.filter(user_id=request.user.id, active='Yes') for doc in doctor: ticket = get_object_or_404( Ticket, pk=pk, has_cancelled=0, is_active=0, doctor=doc.id) lab_group = Lab_Group.objects.all() if request.POST.getlist('lab_test'): lab_test = request.POST.getlist('lab_test') laboratory = Lab.objects.filter(id__in=lab_test) lab_test_id = LabRequest.objects.filter(examined=0, paid=0, lab_test__in=lab_test, ticket__patient=ticket.patient.id) if lab_test_id: messages.success( request, 'Some lab tests have not been examined.') return redirect('/dashboard/lab-request') else: instance = LabRequest.objects.create( ticket=ticket, created_by=request.user.id) instance.lab_test.add(*laboratory) messages.success( request, 'Lab Request has been sent successfully.') return redirect('/dashboard/lab-request') context = { 'title': 'Laboratory Request', 'valueBtn': 'Save', 'lab_group': lab_group } return render(request, 'dashboard/laboratory_request.html', context) This is the way I'm trying to update LabRequest class but it's not complete because I have no idea how to update: @login_required def LabRequestUpdateView(request, pk): doctor = Doctor.objects.filter(user_id=request.user.id, active='Yes') for doc in doctor: lab_request_id = get_object_or_404(LabRequest, pk=pk, ticket__doctor=doc.id) context = { 'title': 'Update Request Lab', 'valueBtn': 'Update', 'lab_request_id': lab_request_id } return render(request, 'dashboard/laboratory_request.html', context) This is my template and I'm using the same template for saving data <form action="." method="POST"> {% csrf_token %} <div … -
Admin form to select existing object and related to existing object
I have a basket object, each basket could have many balls and a ball could be on many baskets, moreover each ball has many colors but one color is for one ball only. Models example: class Basket(models.Model): name = models.CharField(max_length = 100) class Ball(models.Model): basket = models.ManyToManyField(Basket, ) class Color(models.Model): ball = models.ForeignKey(Ball, on_delete = models.CASCADE) Each object has many other fields, not relevant I want in admin site when create a basket, select which ball and which color per ball. I tried inline, but it adds a new ball, i want just select existing ball and related color. PS:IMHO This is not a duplicate of this question because select Basket is covered but not select Color per ball. Thanks all -
JWT python Token Call in function
We are implementing authentication using OTP. And authorization using the JWT token. What we want to save is a call to API to fetch the bearer token. So we have a user with a user_name of 99999-99999. 1. And he sends a login request 2. We send him the OTP through SMS 3. He sends another request with the OTP for verification At this point as we have an event, we want to generate the token from JWT library and send it to the app -
What is the design handoff when working with Developers?
How can designers work with developers to deliver an excellent project? -
from django.contrib.auth.forms import UserCreationForm causing django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
So I see a lot of questions about the infamous "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." yet I cannot find anyone solving my problem as it doesn't have anything to do with my INSTALLED_APPS and it only goes away when I comment out the UserCreationForm.I am trying to create a basic signup page and UserCreationForm is the best way to do that. So does anyone know what I need to do to fix this? My lack of knowledge of this situation and of Django doesn't seem to help either but this seems as if it is a simple fix. Thank you for the help :). Here is all code I believe is relevant. In settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello.views',] urls.py from django.contrib import admin from django.urls import path from hello.views import myView from hello.views import myHome from hello.views import home from hello.views import index from hello.views import game from hello.views import main from hello.views import signup from django.contrib.auth import views as auth_views from django.views.generic.base import TemplateView from django.conf.urls import url, include urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^hello/',include('hello.urls')), path('sayHello/', myView), path('home/',home,name='Home'), path('game/',game,name="Game"), path('home/game.html',game), path('home/home.html',home), path('game/game.html',game), path('game/home.html',home), path('main/',main), path('signup/',signup, name="signup"), url(r'^login/$', auth_views.LoginView.as_view(template_name= 'login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(template_name= 'logged_out.html'), name='logout'), … -
vscode keeps asking for debug config
vscode asks me for my debug config file everytime I run the server, how can I get it to see it? here is my current config that keeps being ignored. { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true } ] } I'm using Anaconda 4.7.12 mac running mohave python3.7 django2.2 -
Django 2.x filter and sort calculated boolean field
I am trying to figure out how to enable sorting by a calculated boolean field. I have seen some other related posts, but I cannot figure them out. I tried to add a custom manager for Files, but it did not work. I want to be able to sort and filter values according to calculated fields like exists. class File(models.Model): archive = models.ForeignKey("Archive", on_delete=models.CASCADE) file_name = models.CharField(max_length=2000, unique=False, validators=[validate_is_file]) comment = RichTextField() title = models.CharField(max_length=2000, default='') def __str__(self): return basename(self.file_name) def save(self, *args, **kwargs): self.title = basename(self.file_name) super(File, self).save(*args, **kwargs) def preview(self): return bs4(self.comment).get_text() def exists(self): return isfile(self.file_name) exists.boolean = True def size(self): return getsize(self.file_name) def created(self): return convert_ctime(time.ctime(getctime(self.file_name))) def modified(self): return convert_ctime(time.ctime(getmtime(self.file_name))) class FileAdmin(admin.ModelAdmin): readonly_fields = ['file_name', 'archive'] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'style': 'width: 90%;'})}, } fieldsets = [ (None, {'fields': ['title', 'comment', 'file_name', 'archive']}) ] list_display = ['exists', 'file_name', 'size', 'created', 'modified', 'title', 'preview',] search_fields = ['title', 'file_name', 'comment', 'created', 'modified'] list_filter = ['exists'] # This does not work admin.site.register(Archive, ArchiveAdmin) admin.site.register(File, FileAdmin) -
Django: Improve page load time by executing complex queries automatically over night and saving result in small lookup table
I am building a dashboard-like webapp in Django and my view takes forever to load due to a relatively large database (a single table with 60.000 rows...and growing), the complexity of the queries and quiet a lot of number crunching and data manipulation in python, according to django debug toolbar the page needs 12 seconds to load. To speed up the page loading time I thought about the following solution: Build a view that is called automatically every night, completeles all the complex queries, number crunching and data manipulation and saves the results in a small lookup table in the database Build a second view that is returning the dashbaord but retrieves the data from the small lookup table via a very simple query and hence loads much faster Since the queries from the first view are executed every night, the data is always up-to-date in the lookup table My questions: Does my idea make sense, and if yes does anyone have any exerience with such an approach? How can I write a view that gets called automatically every night? I also read about caching but with caching the first loading of the page after a database update would still … -
Can we use django with pybuilder efficiently
I want to add a tool in my django project which will run test cases and create an alert if code coverage is less on newer commit. To handle this issue, one way is to use a test runner with a coverage tool in Django or I can use pybuilder. But, it didn't get much about pybuilder combination with django over the net. -
models.CharField Is being removed when I'm trying to add models.DateTimeField(auto_now=True) in a new migration
When I migrate this Search model it is migrated successfully and CharField is created against search field search = models.CharField(max_length=20, default="ping pong"), and can be seen in admin panel. class Search(models.Model): search = models.CharField(max_length=20, default="ping pong") def __str__(self): return '{}'.format(self.search) class Meta: verbose_name_plural = 'Searches' But the question is when I add a DateTimeField to this Search model class see the code class Search(models.Model): search = models.CharField(max_length=20, default="ping pong"), created = models.DateTimeField(auto_now=True) def __str__(self): return '{}'.format(self.search) class Meta: verbose_name_plural = 'Searches' so when I migrate again for the second field to update changes in database, it says - Remove field search from search - Add field created to search And the CharField of search that I was able to see in admin panel is no longer visable. Actually I want to store the search text and the time of that search in my database. -
Creating a django form that collects data and post in in the admin
I really am not posting any code here because this question is somewhat strait to the point... I need to create a form that collects phone numbers from users and post them in the admin....thanks anyone -
how to import all django models and more in a script?
I've put the following code at the top of my script file os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'momsite.conf.local.settings') django.setup() Now I can import my django apps and run small snippets (to mainly test stuff) I'd like to import all the models registered through settings.INSTALLED_APPS I know https://github.com/django-extensions/django-extensions does this when running manage.py shell_plus it automatically imports all the models and more. I'm looking at their code. not sure if I'll make sense out of it. https://github.com/django-extensions/django-extensions/blob/3355332238910f3f30a3921e604641562c79a0a8/django_extensions/management/commands/shell_plus.py#L137 -
Django. How to count the number of queries in a queryset that has been filtered and append that number as an attribute to another model?
I'm new with Python and Django. I have three models Post, Vote and VoteModel: class Post(VoteModel, models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=150) description = models.TextField(max_length=3000) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Vote(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) vote_choice = models.PositiveSmallIntegerField(default=0) #0 - none, 1 - yes, 2 - no date = models.DateTimeField(auto_now_add=True) class VoteModel(models.Model): num_vote_yes = models.IntegerField(default=0, db_index=True) num_vote_no = models.IntegerField(default=0, db_index=True) class Meta: abstract = True Now, I want to calculate the total number of yes and no votes for each post. I do it like this: yes_votes = Vote.objects.filter(post=post_instance, vote_choice=1).count() I want to save the yes_votes number in the abstract VoteModel class num_vote_yes attribute. How? I want to access num_vote_yes and num_vote_no by post_instance.num_vote_yes and post_instance.num_vote_no. Certainly, everytime I create a new instance of a Vote class I want the num_vote_yes and num_vote_no to be automatically updated. How? Been struggling for a long time now but I learned a lot! The time has come to outreach! Thanks! -
Document path parameters in REST API documentation
I am using REST's inbuilt API documentation tool and I can't figure out how to document the path parameters that I pass in my URLs. I think an image explains best what I mean: When I send data with a post method I can fill the description field by adding help_text in my mode or in my Serializer. But has anyone an idea how to document these path parameters? I can't find anything in the scarce documentation. Thanks in advance! Very much appreciated! Docs are created like this: from rest_framework.documentation import include_docs_urls from rest_framework.permissions import IsAdminUser API_TITLE = "..." API_DESCRIPTION = "..." urlpatterns = [ path('docs/', include_docs_urls( title=API_TITLE, description=API_DESCRIPTION, permission_classes=[IsAdminUser]) ), -
celery logging to django site page
What's the best practice of logging celery tasks into django's page. I have a django project and some periodic tasks powered by celery. Those tasks are located in tasks.py. I want to have a page on my site, named something like ".../tasks" where all the celery logs are being stored. So every time a periodic task was called by celery, the log information about the status of this task would show on mentioned page. Sorry for repeating myself, just want to make my question clear. Right now I have a default celery logger. Hope you'd help me. -
getting all products from parent category django rest
I have products related to child category for example: I have category like that Toys, Toys -> ChildToys, Toys -> ChildToys -> Cars I have related products to Toys -> ChildToys -> Cars and I can get all products by Cars but How can I get the products by filtering Toys category. What I have done so far class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True, unique=True) icon = models.ImageField(upload_to='category_icons', null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='children', null=True, blank=True) class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) class ProductList(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): slug = self.request.query_params.get('slug', None) parent_id = Category.objects.get(slug=slug) cats = Category.objects.filter(parent_id=parent_id) qs = Product.objects.filter(category_id__in=parent_id) print(qs) return qs -
how to capture the number of downloads of a specific file in django
i have been working on a project that involves downloading files. i have been tasked to create a report of how many downloads per file. here is my code reports.py def dataset_download(request): download = DataSet.objects.annotate(numdownload=Count('name'),) return render(request, "my_admin/dataset_download.html", {"download":download}) my models.py class DataSet(models.Model): name = models.CharField(max_length=255) description = models.TextField() purpose = models.TextField() temporal_scope = models.TextField() taxonomic_scope = models.TextField() my urls.py path('dataset_download/', reports.dataset_download, name='dataset_download'), and finally my html {% for d in download %} {% if d.name != "" %} <tr> <td>{{ d.name }}</td> <td>{{ d.numdownload }}</td> <td> <a href="/dataset/?name={{ d.name }}" class="btn btn-primary btn-xs"> <i class="fa fa-eye"></i> View Details </a> </td> </tr> {% endif %} {% endfor %} -
DRF: can you deserialize one JSON key:value pair into multiple fields
In my API I have a module, which collects JSON objects obtained via POST request. JSON objects I'm receiving look more or less like this: { "id": "bec7426d-c5c3-4341-9df2-a0b2c54ab8da", "data": { "temperature": -2.4, // some other stuff is here as well ... } } The problem is requirement that I have to save both: records from data dictionary and whole data dictionary as a JSONField. My ORM model looks like this: class Report(BaseModel): id = models.BigAutoField(primary_key=True) data = JSONField(verbose_name=_("Data"), encoder=DjangoJSONEncoder, blank=True, null=True) temperature = models.DecimalField( max_digits=3, decimal_places=1, ) # other properties Is there any neat way to get both properties in one attempt to deserialize JSON object? Currently I use nested serializers formed like this: class DataSerializer(serializers.ModelSerializer): temperature = serializers.DecimalField( source="temperature", write_only=True, max_digits=3, decimal_places=1 ) class Meta: model = Report fields = ("temperature") class ReportSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source="uuid", read_only=True) data = DataSerializer(source="*") class Meta: model = Report fields = ("id", "data") which obviously does not pass whole data dictionary to validated_data, which means I have to update the JSON field elsewhere (not good since I would like to have both data and temperature at null=False in ORM model). Any good ideas on how to fix this using DRF serializers would be … -
How can I create a model that adds objects from other models to it
I am using Django 2.2 and am trying to create a model that takes information from another model. I am aware of ForeignKey however this doesn't add all of the object attributes such as title, price etc for me to call upon from my templates. I am selling a product. This product can be for women, or it can be for men. I have a category selection within the model that allows me to select for men or for women. If the category selection is 'for women' then I would then like this product to become available as an object to be added to my 'for women' model. Here are my models: product, and, for women. TOY_CATEGORY_CHOICES = ( ('FW', 'For Women'), ('FM', 'For Men') ) class Product(models.Model): slug = models.SlugField(max_length=40) image = models.ImageField(upload_to='media') title = models.CharField(max_length=150) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) stock_quantity = models.PositiveIntegerField() in_stock = models.BooleanField(default=True) category = models.CharField(choices=TOY_CATEGORY_CHOICES, max_length=2, default='FW') brand = models.CharField(choices=TOY_BRAND_CHOICES, max_length=2, default='NB') on_sale = models.BooleanField(default=False) def __str__(self): return self.title class ForWomen(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) Here are my views: def WomenOnlyView(request): obj = ForWomen.objects.all() context = { 'object':obj } return render (request, 'products/forwomen.html') This is my URL file: urlpatterns = [ path('products/for-women/', … -
Django Custom Widget for Materialize can't find Template
We are using Django 3 and Materialize CSS in our project and when rendering a form checkboxes don't show up. This is because Materialize needs to style them a special way (reference) and our Django model form doesn't play ball. As we don't want any dependencies for a simple checkbox but we need to do this over and over again in different forms, we thought it would be a good idea to create a custom widget, just using a separate template for rendering the checkboxes: class MaterializeSwitch(forms.widgets.CheckboxInput): template_name = os.path.join(STATICFILES_DIRS[0], 'widgets', 'cb_materialize.html') def __init__(self, attrs={}, *args, **kwargs): super().__init__(attrs) If I understood correctly this is how it is done in Django internally and I just replaced the default template_name with our custom one: <div class="switch"><label>On<input type="{{ widget.type }}" name="{{ widget.name }}" {% if widget.value != None %}value="{{ widget.value|stringformat:'s' }}"{% endif %}>Off</label></div> When using one field with this widget the error message: TemplateDoesNotExist at [...] comes up. This is a pretty long question already I didn't want to spam it with more paths and information. If there is any more info needed to solve this I will add it on request.