Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Vue - Vue variable in Django Tag
On a Django-Html Template I need to render this line of code: <form action="{% url 'meal:submit_comment_rating' meal_id=meal.id comment_id=[[ comment.comment_id ]] %}" method="post"> Inside of a Vue for-loop: <div v-for="comment in comments" id="comment_[[ comment.pk ]]"> ... </div> Where [[ comment.comment_id ]] is replaced with the corresponding Vue variable: meal_comments_sort = new Vue({ delimiters: ['[[', ']]'], el: '#meal_comments_section', data: { comments: [ { "meal_id":1, "user_id":1, "username":"admin", "comment_id":1, "comment_type":"mealcomment", "date":"2020-09-01T14:18:24.563Z", "content":"time for comment", "rating":-1 }, ], }, }); As-is I receive the Django error Could not parse the remainder: '[[' from '[[' which I expected, but cannot find a work-around for. What is the best way to do this? I have tried wrapping the [[ comment.comment_id ]] variable in {% verbatim %} tags, but it does not help (probably because that's not how those tags are supposed to be used). -
How to add common fields in django models?
I am preparing db schema using django for an application school management system. A little confusion happened while making the relationship between three tables i.e. User, Staff and Student. User table stores primary user fields such as first_name, last_name, email etc. Staff fields stores staff qualification, department, designation etc and a foreign key of User to store the primary details of the staff. And Student also has Foreign key with User to store its primary info and rest other student related fields such as registration details, guardian details etc. To add contact details of Student and Staff, I came up with below approach of storing a contact field in both the tables: models.py # from 'common', A separate django application to store common database tables such as Contact, User, Language, Timezone, etc. from django.contrib.auth.models import User, Group class Contact(models.Model): address = models.TextField(_("Permanent Address"), blank=True, null=True) landmark = models.CharField(_("Landmark"), blank=True, max_length=80) city = models.CharField(_("City/Town"), blank=True, max_length=80) ... models.py # From 'students', separate django application to handle student details such as student admissions, and corresponding other tables. class Student (models.Model): reg_number = models.CharField(_("Reg. Num"), max_length=20) member = models.OneToOneField(User, verbose_name=_("Student"), related_name="students", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE, ...) ... models.py # from 'staff', separate … -
Django date with event
I've got model: class LinkShortener(models.Model): long_url = models.URLField('Long URL', max_length=2000, blank=False) usage_count = models.PositiveIntegerField(default=0) I've got function in view: @login_required(login_url='/accounts/login/') def redirection(request, token=None): # noqa: D103 #zmienionno z Home na home if not token or token is None: return redirect('shortener:generate') else: try: check = LinkShortener.objects.get(shortcut=token) if check.active: check.usage_count = check.usage_count + 1 else: check.usage_count_inactive = check.usage_count_inactive + 1 check.save() url_to_redirect = check.long_url if check.active: return redirect(url_to_redirect) else: return redirect('shortener:generate') except LinkShortener.DoesNotExist: return redirect('shortener:generate') So every time when URL adress (LinkShortener object) is clicked, usage_count increments by 1. Does Django saves somewhere date of such action/click or i have to create some field in my LinkShorener model where dates of every click will be added ? Is there any query command that can give me date of such click ? -
How to render a 3D object to HTML file by using pythonOCC in Django?
I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. Normally, when I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. However I need to display the files in a Django template. That's why I have extended the X3DomRenderer Class such as below. My custom X3DomRenderer class: class CustomX3DomRenderer(x3dom_renderer.X3DomRenderer): def render_to_string(self): self.generate_html_file(self._axes_plane, self._axes_plane_zoom_factor) return open(self._html_filename, 'r').read() the HTML codes that returned from render_to_string() function: <html lang="en"> <head> <title>pythonOCC 7.4.0 x3dom renderer</title> <meta name='Author' content='Thomas Paviot - tpaviot@gmail.com'> <meta name='Keywords' content='WebGl,pythonOCC'> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://x3dom.org/release/x3dom.css"> <script src="https://x3dom.org/release/x3dom.js"></script> <style> body { background: linear-gradient(#ced7de, #808080); margin: 0px; overflow: hidden; } #pythonocc_rocks { padding: 5px; position: absolute; left: 1%; bottom: 2%; height: 38px; width: 280px; border-radius: 5px; border: 2px solid #f7941e; opacity: 0.7; font-family: Arial; background-color: #414042; color: #ffffff; font-size: 14px; opacity: 0.5; } #commands { padding: 5px; position: absolute; right: 1%; top: 2%; height: 65px; width: 180px; border-radius: 5px; border: 2px solid #f7941e; opacity: 0.7; font-family: Arial; background-color: #414042; color: #ffffff; font-size: 14px; … -
Django annotate Avg of foreign model
Two models, article and review, relationship is one to many (one article has many reviews). Some articles don't have any review. I want to order articles by review ratings, therefore I use the annotate with AVG: ArticleQueryset.annotate(rating=models.Avg('reviews__rating')).order_by('-rating') The issue is that the articles without reviews the rating value is False and somehow that comes before the maximum rating. The result is that the first results don't have any rating, then the highest rated articles show up. -
django uploading multiple images with one submit button
I'm new to django I want to upload multiple pictures by clicking one submit button I've saw people using formsets but it is limiting the number by using extra = # but I don't want to limit the number and some people are using filefield but I want people to only upload images. Is there a way to upload multiple picture by clicking one submit button without limiting the number of image files and only allowing image file? -
Django Rest Framework Filter not Working, The filter button is not showing on browsable API
Good day I am new with django and django rest framework. I am trying to do some filtering. I followed the steps on the docs https://www.django-rest-framework.org/api-guide/filtering/ but nothing is working, it doesnt even show the filter button on browsable api. hope someone can help. thank you -
How can I store non exist value of multiselect field into database in Django?
I am working on a project and I have a problem like whenever I create a tag that is not exist in my Tag table which is mapped to as foreign key in this form, It shows me like tag not exist validation error I tried to store it in forms.py file. ''' def save(self, commit=True): tags = self.cleaned_data['tag'] for tag in tags: if tag not in Tag.objects.values('title'): obj=Tag(title = tag) obj.save() instance = super().save() if commit: instance.save() return instance ''' I have used select2 jquery for crating dynamic tag.how can i add dynamic tag to database called Tag -
Apscheduler runs with Django but not running with gunnicorn
I am setting my scheduler using apscheduler inside a file called Scheduler.py - def start_scheduler(): scheduler = BackgroundScheduler() scheduler.add_job(xyz_job, trigger='cron', hour=21, minute=0) scheduler.start() Now inside my apps.py - from. Scheduler import start_scheduler class AppNameConfig(AppConfig): name = 'appname' start_scheduler() Then from cmd I use - python manage.py runserver My scheduler works fine and everyday at 9pm, scheduler started working in background. P.S. - This was an API with entry and end points. I tested it using postman. I was getting the output correctly. Now on my linux server, I am doing the same thing, but instead of using django, I am using gunicorn to expose my api. I am using the command - gunicorn -b server_ip:port project.wsgi --workers=2 --daemon Using the above gunicorn command, my api is still working fine and I am getting the output but my scheduler isn't working. Can anyone give some insight on what can be the possible solution for this? -
Is it possible to load django admin inlines dynamically?
i.e, load the inlines only when clicked on it. If possible, how can this be achieved. I have gone through various answers but could not find what I was looking for. -
Django model, how to allowing only two booleanfield to be True
How to allow that only 2 objects can be true? class Book(models.Model): is_active = models.BooleanField( default=False, verbose_name='is active' ) def save(self, **kwargs): if self.is_active: Book.objects.exclude(pk=self.pk).filter(is_active=True).\ update(is_active=False) super().save(**kwargs) -
Capture an arbitrary number of values from url
I created a url pattern in Django which captures a category in the url and passes it in the view. For example the url mysite.com/category/shoes/ matches the path: path('category/<category>/', views.Feed.as_view(), name='feed'), And it will pass to the view a variable called category with the value "shoes". Now I want also to capture subcategories. Categories and subcategories will be organized as a tree structure, and a subcategory may have more subcategories within it. How could I write a url path pattern which captures an arbitrary number of nested subcategories, for example: mysite.com/category/shoes/winter/leather/... and how would this be passed to the view? -
Add Radio button in default Django form:
I think I have written the correct code. But this gender radio button is not appearing in my form. This is my model view. class Charter(models.Model): CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) created_at = models.DateField() First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) address = models.CharField(max_length=200, unique=True) Cell_no = models.CharField(max_length=200, unique=True) created_at = models.DateField() This is my forms.py from django.forms import ModelForm from .models import * class CharterForm(ModelForm): class Meta: model= Charter fields = '__all__' widgets = { 'Gender': forms.RadioSelect() } -
How to override/exempt django's django.middleware.clickjacking.XFrameOptionsMiddleware option
Hello I am making a website, which includes me having to embed Disqus comment system in the views But the thing is I use django==3.1.1 which includes the option django.middleware.clickjacking.XFrameOptionsMiddleware in the middleware That is fare enough for security, but what I want is just for the home view that renders the template to be excluded from django.middleware.clickjacking.XFrameOptionsMiddleware protection Also if possible how can I prevent the same issue in the django-admin I knew this in the web browser console saying X-Frame-Options is set to deny -
Elastic search in Django with no query, only filter
I have a Django project for which I'm converting the regular DB search to elastic search. What currently happens is that there is a select to retrieve data from the DB based only on a date, basically to retrieve the most recent items. I'm trying to reproduce this behaviour with the django_elasticsearch_dsl but it keeps failing. I need a queryset because of how the whole app is structured. The method to_queryset() works just fine if I have a query term, but I get an error object of type 'Search' has no len() if I there is no query term. Something I tried: search = document.search() if query: search = search.query("multi_match", query=query, fields=["title", "body", "excerpt"]) search = search.filter("range", modified_at={"gte": date_from}) search = search.filter("range", modified_at={"lte": date_till}) object_list = search.to_queryset() This is inside a django arctic app, if that's relevant. I also tried using search = search.query() (with no params) and then adding the filters, but I get the same error. It sounds silly but is this possible to do? -
how to access the header and data which is send with the url in django?
This below code calls the django url with the data and the header. ''' return new Promise((resolve, reject) => { $http({ url: servicesUrl + "testapi/", method: "POST", data: { reportStandardName: moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime: moment(fromReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), toReportTime: moment(toReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), reportID, phononUUID, attemptID, requestID, queueIds, flowIds, callStatus, sourceOfRequest: "API", priority: 1, reportTime: new Date().toLocaleTimeString(), } ''' and below is the django urls file code. ''' urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^testapi/', views.getResponse) ] ''' so how to access the header and the data send with the URL? -
Passing variable value in url via views django
Not sure how to pass variable param value in url View.py def show_email(request, param): param = 'abc@oranization.com' return render(request, 'abc.html') HTML <a class="btn btn-primary" href="/url/<param>">Check Inbox</a> -
Why Django form_valid is calling twice?
I am using form_valid() to save my data from form and redirecting to specific page using a condition in get_success_url but form_valid() is calling twice. i saw some people resolved with: return HttpResponseRedirect(self.get_success_url()) and return HttpResponseRedirect(self.request.META['HTTP_REFERER']) But found no help with my condition. My code from views.py def form_valid(self, form): form.instance.closed_date = timezone.localtime(timezone.now()) context = self.get_context_data() invites = context['meetinginvites'] with transaction.atomic(): if invites.is_valid(): self.object = form.save() invites.instance = self.object invites.save() # Notification meeting = Meeting.objects.get(pk=self.object.id) guests = RSVP.objects.filter(meeting=meeting.id).values_list('responder__user', flat=True) users = User.objects.filter(pk__in=guests) notify.send(self.request.user, recipient=users, verb="Closed Meeting") return super().form_valid(form) def get_success_url(self): if self.request.POST.get('page') == 'meeting': id = self.request.POST.get('pass_id') return reverse_lazy('Event:meeting-detail', kwargs={'pk': id}) else: return reverse_lazy('Event:allmeeting_view') -
why are my django forms not showing up on my site
what i want to do: i want to have a login form that when details are entered they are saved on the admin side. my problem: the forms are not showing up on my local host page. see image below: here is the code from the login form app: admin.py: from django.contrib import admin # Register your models here. from .models import Contact admin.site.register(Contact) from apps.py: from django.apps import AppConfig class ContactConfig(AppConfig): name = 'contact' from forms.py from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('username', 'password') from models.py: class Contact(models.Model): username = models.CharField(max_length=100) password = models.CharField( max_length=100, ) def __str__(self): return f'{self.username} {self.password}' ``` from views.py: ``` from django.shortcuts import render # Create your views here. from .forms import ContactForm def contact(request): template = "home2.html" if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() else: form = ContactForm() context = { 'form': form, } return render(request, template, context) ``` then finally from the login page: ``` {% load crispy_forms_tags %} {% load static %} <form method="post" class="form"> {% csrf_token %} {{ form }} <button type="submit" class="btn"><a href="£">Log In</a></button> </form> another thing forms ar connected to admin side but just do not appear on … -
How do I make my django application run on specific devices only?
I have created a django application, now I want to make sure that some of the pages in the application is not accessed by anyone who has the IP to the app. I want to make a list of devices by either giving them specific ID(the first time the app is run on the device) or by making a list of IP that are allowed to visit the application. How should I go about this? -
POST data only if you are authenticated and only to your user using django-rest-framework
i'm new to Django so sorry if this seems stupid. i want to add an item to a database only if the user is authenticated . here are the models: class SaleItems(models.Model): product_name = models.CharField(max_length=50) price = models.IntegerField() product_type = models.CharField(max_length=25) description = models.CharField(max_length=250 ,default='', blank=True) brand = models.CharField(max_length=25, null=True,blank=True) image_path = models.ImageField(upload_to='images/product_image') date_added = models.DateField(auto_now_add=True) in_stock = models.BooleanField(default=True) def __str__(self): return f"{self.product_name}, price={self.price}" class SaleHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(SaleItems, on_delete=models.RESTRICT, default=None) date_bought = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.date_bought}, {self.product}, {self.user}' the serializers: class SaleItemSerializer(serializers.ModelSerializer): class Meta: model = SaleItems fields = '__all__' class SaleHistorySerializier(serializers.ModelSerializer): class Meta: model = SaleHistory fields = '__all__' urls: routes = routers.DefaultRouter() routes.register('api/saleitems', SaleItemViewSet, basename='saleitem') routes.register('api/salehistory', SaleHistoryViewSet, basename='salehistory') urlpatterns = [ path('',include(routes.urls)) ] and finally the apis class SaleItemViewSet(viewsets.ModelViewSet): queryset = SaleItems.objects.all() permission_classes = [permissions.AllowAny] serializer_class = SaleItemSerializer class SaleHistoryViewSet(viewsets.ModelViewSet): # queryset = SaleHistory.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = SaleHistorySerializier def get_queryset(self): user = self.request.user return SaleHistory.objects.filter(user = user) so the problem, when i post to 'api/salehistory' i am able to add content to any user not only as the authenticated user. (using knox authtoken for authentication). Say for example i am authenticated as user1 and i have my auth token. Now … -
Django models create() and save() not persisting in database (pk / id attribute on instance is not set)
I am using Django 2.2 This is my model models.py class WebPage(models.Model): breadcrumb = models.CharField(blank=False, null=False, max_length=128, unique=True) slug = models.SlugField(blank=False, null=False, max_length=128, unique=True) content = RichTextField() creator = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) is_published = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.breadcrumb def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.breadcrumb) ./manage.py shell >>> wp=WebPage.objects.create(breadcrumb='hello/there', content='<span></span>') >>> wp.id >>> wp.save() >>> wp.id >>> wp.slug 'hellothere' >>> wp.save(persist=True) >>> wp.id >>> Why is the object not being saved to the database - and how do I fix this? -
<int:pk> url mapping error , <int:pk> not passing
here is my html link from where i want to use int:pk <a href= "/main/profile/edit/{{ user.myprofile.id }}" >Edit Profile</a> when i click on the link i get a url mapping error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/main/profile/edit/ Using the URLconf defined in lunarcodes.urls, Django tried these URL patterns, in this order: main/ home/ main/ profile/ main/ feed/ main/ profile/edit/<int:pk> here is my urls.py, urlpatterns = [ path('profile/edit/<int:pk>', views.MyProfileUpdateView.as_view(success_url="/main/profile")), ] this is my views.py, @method_decorator(login_required, name="dispatch") class MyProfileUpdateView(UpdateView): model = MyProfile fields = ["name", "description", "pic"] this is my models.py, class MyProfile(models.Model): name = models.CharField(max_length = 100) user = models.OneToOneField(to=User, on_delete=CASCADE) description = models.TextField(null=True, blank=True) pic= models.ImageField(upload_to = "images\\", null=True) def __str__(self): return "%s" % self.user i myself couldn't understand the problem properly as i am begginer. -
Django + React + Babel + Heroku deployment error: "App not compatible with buildpack: ... /heroku/python.tgz"
I have Django + React app I'm building to learn the latter framework better. It uses Django, ReactJS and Webpack and the folder structure is the following my-project-root-folder/ frontend/ /src/ /static/ ... .babelrc package.json webpack.config.js django-main-project/ ... settings.py wsgi.py other-django-app/ ... views.py manage.py Procfile requirements.txt it's all set up for auto deployments from Git on Heroku, where I have the following Buildpacks installed However, whenever I try to deploy, I get the following build error: -----> Subdir buildpack app detected -----> Subdir buildpack in frontend/ creating cache: /tmp/codon/tmp/cache created tmp dir: /tmp/codon/tmp/cache/subdirDtoAM moving working dir: frontend/ to /tmp/codon/tmp/cache/subdirDtoAM cleaning build dir /tmp/build_c9788563_ recreating /tmp/build_c9788563_ copying preserved work dir from cache /tmp/codon/tmp/cache/subdirDtoAM to build dir /tmp/build_c9788563_ cleaning tmp dir /tmp/codon/tmp/cache/subdirDtoAM -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I understand, I think, that Heroku expects certain files to exist within the project's root folder (hence why I installed Subdir Heroku Buildpack) but I don't understand what's wrong with the Python buildpack, since I'm providing Procfile and requirements.txt correctly (as usual). Any chance to make it work with this project's folder structure or do I have to deploy everything from the same folder? How would I go … -
Unable to delete object when using generic relationship and proxy model
I'm unable to delete object when using generic relationship and proxy model. Error snapshot Here is my model class GenericCategory(MPTTModel): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) banner_image = models.ImageField(upload_to="category_images", null=True, blank=True) name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] and here is my proxy model class Category(GenericCategory): class Meta: proxy = True verbose_name = 'Category' verbose_name_plural = 'Categories' def save(self, *args, **kwargs): self.content_type = ContentType.objects.get(app_label='award', model='category') return super().save(*args, **kwargs)