Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve this django webpage issue
I'm new to Django. I created an App called Programador related with another App called Proceso, when I try to run the App Programador in the Admin website shows me the next error: 'builtin_function_or_method' object is not subscriptable 15 {% endif %} 16 </label> 17 <div class="{% if not line.fields|length_is:'1' %} col-auto fieldBox {% else %} col-sm-10 {% endif %} 18 {% if field.field.name %} field-{{ field.field.name }}{% endif %} 19 {% if not field.is_readonly and field.errors %} errors{% endif %} 20 {% if field.field.is_hidden %} hidden {% endif %} 21 {% if field.is_checkcard %} checkcard-row{% endif %}"> 22 {% if field.is_readonly %} 23 <div class="readonly" style="margin-top: 7px;">{{ field.contents }}</div> 24 {% else %} 25 {{ field.field }} 26 {% endif %} 27 <div class="help-block red"> 28 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 29 </div> 30 {% if field.field.help_text %} 31 <div class="help-block">{{ field.field.help_text|safe }}</div> 32 {% endif %} 33 <div class="help-block text-red"> 34 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} 35 </div> This is the code from Programador: import uuid from django.db import models from core.GestionTareasProgramadas.models.Proceso import Proceso class Programador(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) organizacion = models.CharField(verbose_name='Organización', max_length=100, null=True, blank=True) estado … -
How to display images from other places in django template
I am fairly new in Django and developing a book recommendation system using Django and PostgreSQL. I have my dataset with some field that also keeps corresponding book images URL (not the images itself) where images reside in other places, not in my static files or database. i want to access that images online and display them in my Django template here is how I tried to do but didn't work and doesn't access the image. <img src= {{ book.image_url.url }} style="display:block;" width="100%" height="100%" alt=""> and also tried this: <img src="{{ book.image_url.url }}" style="display:block;" width="100%" height="100%" alt=""> where book is dictionary and images_url is simply a url string for image residing somewhere in the web. can you help me out how to access this string of url on the web and display it on django template ? -
how to get html element by the value given to an attribute jQuery
to a div element inside forloop ,i have given an attribute called 'prod_id',and i have set the value of that attribute to current product id html {% for product in products %} <div prod_id={{product.id}}> ..... </div> <button prod={{product.id}}> {% endfor %} jquery let product = $(button).attr('prod') let fade_prod = $('div[prod_id = product]') fade_prod.fadeOut('slow') in second line of jQuery i want to equate prod_id to the value of product. and i've tried equate but the logic isn't working as expected -
Django project without models and data base
It is possible to build a project in Django without models ? I have a views, templates(html), css and urls. That site is looking very good in a browser. It is a hairdressing salon website. Greetings -
How can I implement incremental wait time for django axes?
I'm looking to implement django axes for brute force protection for my application. I want to implement something like this "lockout for 5 minutes after 5 failed attempts, lockout for 10 minutes after another 5 attempts" Seems like the example in the doc is more straightforward with a fixed wait time, so I want to know if it's possible to implement something like this. -
how can i convert django template code into javascript?
first time i am using javascript. i want to convert django html code into javascript. i also create django rest api. i want to render out api data into template using javascript. without if condition javascript rendering data fine. but i am using some if condition in django template i want to use these condition in javascript but i don't know how can i define these if conditions in javascript side. please can anybody know how can i define it and use it in javascript? and how can i use these link in javascript? {% url 'news-detail' pk=object.pk %} {% url 'prompter-view' pk=object.pk %} {% if request.path == '/rundown-list/' %} index.html <table id="approvedData"> <thead> <tr> <th>ID</th> <th>Story</th> <th>Created By</th> <th>Timestamp</th> <th>Priority</th> <th>Action</th> </tr> </thead> <tbody id="approvedList"> {% for object in data_list %} <tr> <td>{{object.id}}</td> <td><a href="{% url 'news-detail' pk=object.pk %}">{{ object.title}}</a></td> <td>{{object.author.username}}</td> <td>{{object.created_on | naturaltime}}</td> <td> {% if object.story_status == "sn" %} <span class="badge badge-danger">Not Done</span> {% elif object.story_status == "sf" %} <span class="badge badge-warning"> Done</span> {% elif object.story_status == "fr" %} <span class="badge badge-success">Approved</span> {% endif %} </td> {% if request.path == '/rundown-list/' %} <td><a class="btn" href="{% url 'prompter-view' pk=object.pk %}">Prompter view</a></td> {% else %} <td> <div class="table-btns"> <a … -
Django filter a floatfield with a value equals or less
I need to filter all the values of the radius less than the data value but django querys only allows me to check if they are equal How can I implement something like this response =item.objects.filter(radius<data) def home (request , data=None): response =item.objects.filter(radius=data) response_vector=[] for response in response: response_vector.append(response) if len(response_vector)>0: return HttpResponse(response_vector[0].items) else: return HttpResponse(401) I do not want to do something like this: def home (request , data=None): response=[] for x in range(0, data): response.append(item.objects.filter(radius=x)) response_vector=[] for response in response: response_vector.append(response) if len(response_vector)>0: return HttpResponse(response_vector[0].items) else: return HttpResponse(401) -
django-ckeditor richtext content can't display normally in the page
i ran into a problem,i intergrated the django-ckeditor5 in my django admin and it worked.but as i tried to display the content that i saved from the editored,it went wrong. for example,i put a centered image in the content,but it displayed differently. enter image description here in the editor enter image description here how it is displayed i noticed that none of the classes in the html codes generated by the editor is loaded,so i tried to load the styles.css in the django-ckeditor5 static directory,but it didn't work. -
Django- How to hide a button from a superuser or admin but show it to regular or active users
I want to hide a button from a Django Admin or superuser but I want to display it if the user is not an Admin or superuser. How to do it? -
No module named 'fcntl
I am using gunicorn on windows to deploy a Django app to heroku, When I run heroku local. The is the a port of the message error that I get line 9, in 5:50:12 PM web.1 | import fcntl 5:50:12 PM web.1 | ModuleNotFoundError: No module named 'fcntl' [DONE] Killing all processes with signal SIGINT 5:50:12 PM web.1 Exited with exit code null ( Can someone help -
Django Model Manage UNIQUE constraint error in save method
this is with Python 3.8 and Django 3.1.3 I have a model with an unique field class SomeModel(models.Model): name = models.CharField(max_length=200, unique=True) i'm searching a way to automatically change the field value if there is an UNIQUE constraint violation If i create a new instance with name ="kevin" while another instance already exists with the same name ="kevin", it would change the name of the new instance with a suffix when save() is called eg : database is empty >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() # again >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() # and again >>> foo = SomeModel() >>> foo.name = "kevin" >>> foo.save() >>> for foo in SomeModel.objects.all(): >>> print(foo.name) kevin kevin_01 kevin_02 didn't find the way to do this, i suppose i have to override the save method and catch the unique constraint error to do that. any ideas ? Thanks -
How to fetch a csrftoken from a django server?
I'm reconfiguring my CDN and I want to begin caching pages that use csrf tokens for form submission. Currently, I'm submitting the csrf token with javascript in a post request with: axios.defaults.headers.post['X-CSRFToken'] = getCookie('csrftoken') This works pretty well locally and allowed me to remove the csrf tokens from the templates. This obviously will not work if I'm accessing cached pages from the CDN. So is it possible for me to fetch a csrf token from the server using Axios and subsequently set it in a post request? If so how do I do this? An alternative approach would be to disable csrf which I tried already but I couldn't fully disable it. If you are signed into admin csrf protection is automatically enabled even on your frontend forms, I couldn't figure out how to remove this not sure if it's a wagtail or django thing. I'm using Django 2.2 + Wagtail 2.11. -
Apache + Django + Ubuntu, client denied by server configuration
I am trying to run a Django project with Apache in an Ubuntu EC2 server that I got from AWS. I think I got pretty much everything done, I can run it with manage.py runserver and see the project on my public DNS. However, I can't seem to get it to run with Apache. I keep getting a 403 error that says "You don't have permission to access this resource." whenever I try to access it via my internet browser. When I check the error logs, I see the error: AH01630: client denied by server configuration:/home/ubuntu/myproject/swe681server/server/server/wsgi.py Even though I am pointing to the wsgi.py file correctly. My conf file looks like this: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host … -
Recurring For Loop
I have a project where I use nested for loop to filter items, but the result keeps recurring the item which is not supposed to be so. Pls, where did I get it wrong? def order_list(request): orders = Order.objects.all() current_user = request.user user_list = orders.filter(user=current_user.id) success = orders.filter(paid=True) fail = orders.filter(paid=False) return render(request, 'orders/order/order_list.html', { 'orders': orders, 'success': success, 'fail': fail, 'user_list':user_list, 'current_user':current_user, }) html {% for ls in orders %} {% for x in user_list %} {% for od in success %} <div class="card mb-3" style="max-width: 540px;"> <div class="row no-gutters"> <div class="col-md-3"> <img alt="product img" class="card-img" src="..."> </div> <div class="col-md-9"> <div class="card-body" style="position: relative;"> <h5 class="card-title">Product {{ od.id }}</h5> <a href="#" style="position: absolute; top: 5px; right: 5px;">View Details</a> <p class="card-text">Transaction ID</p> <p class="card-text"><small class="text-muted">Delivered at {{od.reference_id}}</small></p> </div> </div> </div> </div> {% endfor %} {% endfor %} {% endfor %} the actual result should be as it is in the screenshot below But I get this; Pls, check the images Thanks. -
React Native, Axios GET call throws [Unhandled promise rejection: Error: Network Error]
I am wiring up the backend and frontend of my application with React Native, using Docker with Django. I am trying to fire a basic axios get call like this: Axios.get(`https://127.0.0.1:8000/products/inventory/1`) .then((response) => { setData(response.data) }) .catch((error) => { console.log(error) }) console.log(data) }, []) I just want to get the data and get this wired up. The backend is running in a Docker container on http://127.0.0.1:8000/, but from the frontend I cannot reach this address, and axios is throwing an unhandled promise rejection. Now, I don't know if I am missing some crucial passages but this would not work in any way. If you need some additional info I can provide them to you. -
RelatedObjectDoesNotExist at /register/ User has no profile for Extended User Model and Profile
When user registers the registration is done but a profile is not created and the error is thrown. In the database the user is created but without a profile. the error is highlighted at "p_reg_form = ProfileRegisterForm(request.POST, instance=credentials.profile)" The bellow are the .py files for the project. This code use to work but has suddenly stopped. models.py: class User(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( "username", max_length=150, unique=True, help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", validators=[username_validator], error_messages={"unique": "A user with that username already exists.", }, ) first_name = models.CharField("first name", max_length=30, blank=True) last_name = models.CharField("last name", max_length=150, blank=True) email = models.EmailField("email", blank=True, unique=True) is_staff = models.BooleanField( "staff status", default=False, help_text=["Designates whether the user can log into this admin site."], ) is_active = models.BooleanField( "active", default=True, help_text=( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField("date joined", default=timezone.now) objects = UserManager() EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = () class Meta: verbose_name = "user" verbose_name_plural = "users" def clean(self): """Try … -
Find /home/user in python as root user
When I want to get user directory as normal user in Python, then i can simply do this: os.path.expanduser('~') --> /home/user But, when I run this command as the root user, then it shows this result. Running as root: os.path.expanduser('~') --> root Is there any way to get /home/user directory as root user in python3? Thanks for your help. -
Why does my Django CreateView not recognise form_valid
I am using the django allauth module to create a user. In views,py I am subclassing CreateView, but I cannot get form_valid to work. It seems not to be being called (I have not imported HttpResponseRedirect but it doesn't complain class SignupPageView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def form_valid(self, form): print('form_valid') return HttpResponseRedirect(self.get_success_url()) What am I doing wrong? -
Filter instantly a field in different form in django
In this simplified order, i want to choose the country on Order and instantly filter only cities of this country in OrderItem. Models class Company(models.Model): company = models.ForeignKey('User',on_delete=models.CASCADE) name = models.CharField(max_length=240) class Country(models.Model): company = models.ForeignKey('Company',on_delete=models.CASCADE) name = models.CharField(max_length=240) class City(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE) name = models.DecimalField(max_digits=20, decimal_places=0) class Order(models.Model): company = models.ForeignKey('Company',on_delete=models.CASCADE) country = models.ForeignKey('Country',on_delete=models.CASCADE) class OrderItem(models.Model): order = models.ForeignKey('Order', on_delete=models.CASCADE) city = models.ForeignKey('City',on_delete=models.CASCADE) Forms : class OrderForm(ModelForm): class Meta: model = Order def __init__(self, company , *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['company'] = forms.ModelChoiceField(queryset=Company.objects.filter(name=company), initial = company) class Order1ItemForm(ModelForm): class Meta: model = Order1Item OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=3) Views : class OrderCreate(CreateView): form_class = OrderForm model = Company template_name = "order_form.html" def get_success_url(self): return reverse_lazy('order_list') def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = OrderForm(company_instance) formset = OrderItemFormSet(form_kwargs={"company":company_instance}) return self.render_to_response( self.get_context_data(form=form,formset=formset)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = OrderForm(company_instance, self.request.POST) formset = OrderItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) In this simplified order, i want to choose the … -
Python server side code generating from OpenAPI and easy to update
I want to convert OpenAPI 3 to django or other server side codes. I know some converters such as swagger-django-generator. https://github.com/praekelt/swagger-django-generator But some solutions are only generate STUB server. The stub server is very nice but the STUB server is not assuming the modification. I seem swagger-django-generator doesn't assume the modification. I want to write OpenAPI documents and generating Typescript client codes and Python server codes. And I modify the logic based on its generating codes. Please tell me about the solution in my situation. -
Checking presence of element in a multiple field value in django template
Let us consider a database values as: name works_in band 1 band 2, band 3 band 2 band 3 band 1, band 2 now let us consider user_band as band 3 in template: {% if user_band in works_in %} Continue next process {% endif %} {% if name == user_band %} Same bands {% endif %} I don't know why conditions are not working if user_band is present in works_in message should be displayed -
How do you create a event model for a group and count hosted and attended event amount per groupmember with Django?
I recently learned how to django with a nice udemy tutorial. So I'm able to create groups and users can join and leave groups. Now I added a feature to the groups where a user can create/host a dinner and others of the group can join the dinner. on top of that I want to keep track of which groupmember hosted how many dinners and which groupmember joined how many dinners, however now when I call the amount of dinners attended by a user, I also get the total amount of dinners a user joined including those of other groups. Ideally a GroupDinner contains all group members with status='unknown' and a groupmember can than choose to attend or decline. So per Dinner there is overview of the groupmembers haven't reacted yet and those who have. So currently I have my models defined like so: Model.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User, through="GroupMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class Meta: ordering = ["name"] class GroupMember(models.Model): group = models.ForeignKey( … -
xhr.send() post request don't pass data
on the typescript side, i have this code that should send post request. note that getCookie function is copied from Django docs exactly like it is. const xhr = new XMLHttpRequest(); xhr.responseType = "json"; xhr.open("POST", `http://localhost:8000/create/`); xhr.setRequestHeader("Content-Type", "application/json"); const coockie = getCookie("csrftoken"); if (coockie) { xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-with", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", coockie); } xhr.onload = function () { callback(xhr.response, xhr.status); }; xhr.onerror = function (e) { console.log(e); callback({ message: "The request was an error" }, 400); }; xhr.send('{"content":"new text"}'); in views.py @api_view(["POST"]) @permission_classes([IsAuthenticated]) def post_create_view(request, *args, **kwargs): print(request.data) serializer = CreateTweeSerializers(data={request.data}) # raise_exception= if form.error reutnr error and status400 if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data, status=201) return Response({}, status=400) `print(request.data)` return `<QueryDict: {}>` -
How to send error message to the Django generic DeleteView Confirmation Page using JsonResponse
I am trying to use Django generic DeleteView using the confirmation page. The setup is working as intended. Later the business logic was changed to prevent deletion if there are child instances assigned to the object being deleted, using on_delete=models.PROTECT in the model. And the DeleteView has been modified to the following: class TerritoryDeleteView(LoginRequiredMixin, DeleteView): template_name = ".../trty_delete.html" model = Territory success_url = reverse_lazy('territories_list') # THE FOLLOWING MODIFICATION DONE: def delete(self, request, *args, **kwargs): self.object = self.get_object() try: self.object.delete() return HttpResponseRedirect(success_url) except ProtectedError: error_message = "This object can't be deleted, as an Outlet is already assigned to the Territory..." return JsonResponse(error_message, safe=False) The above (modified) view works fine. However, in case it encounters the ProtectedError, the error_message is shown in a blank browser page. How could I display the error_message in the confirmation page (template) itself? -
Issue with showing all videos from DB (QuerySet object has no attribute)
I am uploading a video file to my webpage, which I can also play. However, the moment I want to show all the video files on different page and play them, I get QuerySet object has no attribute I can't figure out what I am doing wrong. Models.py: models.py class VideoModel(models.Model): name = models.CharField(max_length=500) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) Views.py: views.py class ShowVideosView(View): def get(self, request): form = VideoForm() lastvideo = VideoModel.objects.last() videofile = lastvideo.videofile return render(request, 'videos.html', {'videofile': videofile, 'form': form}) def post(self, request): form = VideoForm(request.POST or None, request.FILES or None) lastvideo = VideoModel.objects.last() videofile = lastvideo.videofile form = VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): name = form.cleaned_data['name'] videofile = form.cleaned_data['videofile'] new_video = VideoModel(name=name, videofile=videofile) new_video.save() context = {'videofile': videofile, 'form': form} return render(request, 'videos.html', context) class ListOfVideosView(View): def get(self, request): all_videos = VideoModel.objects.all() videofile = all_videos.videofile context = {'all_videos': all_videos, 'videofile': videofile} return render(request, 'all_videos.html', context) all_videos.html: all_videos.html {% for video in all_videos %} <video width='400' controls> <source src='{{MEDIA_URL}}{{videofile}}' type='video/mp4' Your browser does not support the video tag. </video> {% endfor %}