Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django @login_required causing issue when submitting forms
I am passing a some information to view function by submitting a form and view requires has @login_required decorator. Here is the template where i'm passing email ID using a from <form action="{% url 'become_booster' %}" method="post"> {% csrf_token %} <input type="hidden" name="email" value="{{ profile_user.email }}" /> <div class="form-group"> <div class="col-md-12 col-sm-12"> <input type="submit" class="btn btn-success btn-sm" value="Become a Booster"> </div> </div> </form> Here is the view function @login_required def become_booster(request): if request.method == "POST": email = request.POST.get('email') user = CustomUser.objects.filter(email= email)[0] tiers = Tiers.objects.filter(user=user) form = SubscriptionForm return render(request,'select_tier.html',{'tiers':tiers,'form':form}) This is working fine when the user logedin already. When user didn't login, @login_required sends them to login and when it comes back request.method is no longer POST. It no longer has that email info. Can someone help me with this. Thanks! -
django-summernote: how to get the created object by django?
I have a django form with a SummernoteInplaceWidget() and the summernote editor is correctly created. But i need to execute the following command to the editor: $('#summernote').summernote('editor.insertText', 'hello world'));, like the documentation (https://summernote.org/deep-dive/#basic-api). But this command doesn't work. I've tried this: $('#id_content').summernote('editor.insertText', 'hello world'); but other editor was created. I need to insert the text in the first editor that was created by django-summernote and don't create anymore. There is my form: class ParagrafoForm(ModelForm): content = forms.CharField(widget=SummernoteInplaceWidget()) There is my settings.py: SUMMERNOTE_CONFIG = { 'iframe': False, 'lang': 'pt-BR', 'toolbar': [ ['style', ['bold', 'italic', 'underline', 'strikethrough']], ['script', ['superscript', 'subscript']], ['clear', ['clear']], ['font', ['fontname', 'color']], ['para', ['ul', 'ol', 'paragraph', 'height']], ['table', ['table']], ['view', ['fullscreen', 'codeview', 'help']], ], 'disable_attachment': True, 'summernote': { 'width': '100%', 'height': '480', }, } In my template I've: {{ form.content|safe }} So, how to insert text in editor without creating anymore? Or how get the element in javascript to do this? Which's the identificator for the django-summernote created object? -
Views function: saving a form field value into the profile model attribute
I am writing a code for my views function in a django app "colortest" and my Profile model is in django app "users". I want to add a form field data into the Profile Model attribute. When I save the variable I get an IntegrityError I have searched every site but I can't understand colortest/views.py from users.models import Profile def testreport(request): if request.method == "POST": test_result = request.POST.get('test_result') p = Profile(user=request.user, test_result=test_result) p.save() messages.success(request, f'Your account has been Updated!') return render(request, 'colortest/test1.html') return render(request, 'colortest/result.html') users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.TextField(max_length=1000, default="") test_result = models.CharField(max_length=100, default="") def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I want data to be saved in the test_result field of the Profile Model but it keep giving the error IntegrityError at /colortest/result/testreport UNIQUE constraint failed: users_profile.user_id Request Method: POST Request URL: http://127.0.0.1:8000/colortest/result/testreport Django Version: 2.2.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: users_profile.user_id C:\Users\Osama E.Khan\Desktop\website\colortest\views.py in testreport p.save() … ▶ Local vars C:\Users\Osama E.Khan\Desktop\website\users\models.py in save super(Profile, self).save(*args, **kwargs) -
How can i send a information in Html to Django(backend)?
How do I send a clicked link in html or selected information in the ComboBox to Django? views.py def musicList(request): musics = Song.objects.filter() print(musics) con = sqlite3.connect(str(request.user)+".db") cursor = con.cursor() cursor.execute("Select name From sqlite_master Where type='table';") tables = list() for i in cursor.fetchall(): tables.append(i[0]) context = { "musics":musics, "tables":tables, } return render(request,"musicList.html",context) musicList.html {% for music in musics %} <tr> <th scope="row">{{music.id}}</th> <td>{{music.artist}}</td> <td>{{music.song_name}}</td> <td>{{music.song_type}}</td> <td>{{music.owner}}</td> <td> <div class="dropdown"> <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown"> Choice a Music List </button> <div class="dropdown-menu"> {% for table in tables %} <a class="dropdown-item" href="add_to_list/{{music.id}}" value="{{table}}">{{table}}</a> {% endfor %} </div> </div> </td> </tr> {% endfor %} What do I do to return the value corresponding to the "value" of the link that the user clicked from the "dropdown-menu" to a different function in views.py -
Pass a element from a query using django filters between two forms
I asked this question, but i got not response probably because is a big problem so i try to figurate with baby steps. I want to pass the variable product between two forms. Like in this from block 1 to block 2. {% extends 'base.html' %} {% block content %} <div class="list-product"></div> <form method="GET"> {{ filter.form }} <button type="submit" class="btn btn-primary">Search</button> </form> <form action="" method="POST"> {% for product in filter.qs %} <input type="radio" name="product" value="{{product.name}}" unchecked> {{product.name}}<br> {% endfor %} <input type="submit" value="Add> </form> </div> <div class = "list-buy"></div> <form method="GET"> <ul> <li>{{product.name} from {{product.brand}} with cost: {{product.price}}</li> </ul> <input type="submit" name="Finish" > </form> </div> {% endblock content %} My product is modeled by: class Product(models.Model): name = models.TextField(blank=False, max_length=25) brand = models.TextField(blank=False, max_length=25) price = models.PositiveSmallIntegerField(default=200) And can be searched by brand and for price. But I get an error that i need to use csrf-token correctly. Why? -
How can I make a Model field value unique (unique=True) but only comparing it to other models from that User?
I have a Tag model, that must have a name field that needs to be unique, but only for that user's tags. So that one user can't create two 'tagname' tags, but many different users can (create a tag with the same name). The field must be unique inside the models that relate to the User. This is the Model. class User(AbstractUser): email = models.EmailField(unique=True) class Tag(models.Model): name = models.CharField(max_length=30, unique=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='tags') -
Show a leaflet map in a geodjango form added by javascript
I'm using Django, with PostGIS, and I have a Plant.geometry field, declared as django.contrib.gis.db.models.PointField(null=True, blank=True) I'm writing a single-page web client using bootstrap and leaflet, and the user may ask for a form to update a Plant record, this goes in a Bootstrap modal div. The form is automatically generated, based on this ModelForm class: from django import forms from django.contrib.gis import forms as geoforms class PlantForm(geoforms.ModelForm): class Meta: model = Plant fields = '__all__' widgets = { 'geometry': geoforms.OSMWidget(attrs={'map_height': 240}), } the url for this form coming from this line: path("plant/<str:code>/form/", PlantForm.as_view(), name="plant-form"), my javascript client asks for the form, then uses jQuery to put the html into the document: $(modal_form_body).empty(); $.getJSON(form_url, function(data) { $(modal_form_body).append($(data.form)); I'm having two problems, one I which solved brutally, the other for I need help, and it's the reason for my asking here. Comments on the first are welcome, too. 1: media I don't manage to put the form.media into the html, and have it used by my javascript client. So what I did was to inspect what was the value of the form.media, copy it in my static files, and refer to them in my global head element, like this: <link href="{% static … -
In Home component of react+redux app, this.props.posts is undefined after calling action getPosts() on componentdidmount
I am trying to make a blog-style application. I am running a django server and trying to make a react-redux frontend. I am using redux-devtools and when I comment out the error code, redux seems to have the data in the state. Not sure what is going wrong. Also, I am using redux-thunk and axios to communicate with the backend. I am pretty much copying from a youtube tutorial. This is the reducer reducers/posts.js import {GET_POSTS} from "../actions/types"; const initialState = { posts: [] } export default function(state = initialState, action) { switch (action.type) { case GET_POSTS: return { ...state, posts: action.payload } default: return state; } } this is the action actions/posts.js import axios from "axios"; import {GET_POSTS} from "./types"; export const getPosts = () => dispatch => { axios.get('/get/posts/').then(res => { dispatch({ type: GET_POSTS, payload: res.data }) }).catch(error => {console.log(error)}) } this is reducers/index.js import {combineReducers} from 'redux'; import posts from "./posts"; export default combineReducers({ posts }); this is store.js import {createStore, applyMiddleware} from 'redux'; import {composeWithDevTools} from 'redux-devtools-extension'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const initialState = {}; const middleware = [thunk]; const store = createStore( rootReducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ); export default store; this is … -
infinite scrolling using django
I am fairly new to web development and I am building a blog style website. I use pagination to split posts into seperate pages but now i want to rather go for infinite scrolling like facebook does. I have watched countless videos and read a whole bunch of docs regarding this but to be honost, I get lost in all of them. I use django and python for my backend and all sources seem to use other languages etc like JS and ajax etc. All these mentioned sources start from the ground up which somehow confuses me as i already have pagination in place. Is there a way i can just tweak my current pagination to enable infinite scrolling instead of rebuilding the whole thing in different languages? or just help me get this done the right way. I've been struggling with this for weeks now so now i come here as a last resort. No point in running straight here if no effort was put in before hand Here is my current pagination code: views.py: from django.shortcuts import render, get_object_or_404 from .models import Post from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models … -
When saving many uploaded files to db save() method only really works for the last file in the query
I am using CreateView and in the template, I am uploading multiple files to store in the database. I get all file from the request by files = self.request.FILES.getlist('file') and loop it to create an object for each one. However, object creation only works for the last object in the list. def form_valid(self, form): files = self.request.FILES.getlist('file') allowed_file_extensions = ['xls', 'xlsx', 'doc', 'docx', 'pdf'] for file in files: file_converted_to_string = str(file) file_regex = re.search(r"([a-zA-Z0-9-_\s]+)[.](\w+?)$", file_converted_to_string) file_name, file_extension = file_regex.group(1), file_regex.group(2) if file_extension in allowed_file_extensions: self.object = form.save(commit=False) self.object.file = file self.object.file_name = file_name self.object.file_extension = file_extension self.object.department_belonged = self.request.user.profile.department print(self.request.user.profile.department) self.object.creator = self.request.user self.object.save() return super().form_valid(form) Even more interesting, when I replace: self.object = form.save(commit=False) self.object.file = file self.object.file_name = file_name self.object.file_extension = file_extension self.object.department_belonged = self.request.user.profile.department self.object.creator = self.request.user self.object.save() with: self.model.objects.create(file=file, file_name=file_name, file_extension=file_extension, department_belonged=self.request.user.profile.department, creator=self.request.user) It create a new object for each file in the list but raise error in upload_to function in models.py. file = models.FileField(upload_to=file_path) def file_path(instance, filename): return f'{instance.creator.profile.department}/user_{instance.creator.id}/{filename}' Error: Exception Value: 'NoneType' object has no attribute 'profile' -
Running manage.py collectstatic with PyCharm running creates Permission Denied errors under windows
When running manage.py collectstatic for my Django project with PyCharm running I get a "Permission Denied" error. This is true whether I run manage.py from within PyCharm or from a command windows. The error goes away if I close PyCharm before I run collectstatic. My question: is there a way to get PyCharm to release its hold on the static files so that I can run collecstatic without closing and opening PyCharm? -
How to create custom django validation for authentication
Hi everyone) I'm new in Django. I need to do a really simple validation for sign in form. In my app can sign in only one user, with a specific username and password, for example, "my_username" and "my_password". And superuser can't sign in. I don't know do I even need a table in a database for only one user? By now I write a simple login form with django.contrib.auth.views LoginView and this work, but for everyone who is in database and superuser. -
Link html page or jsp page to multiple django apps
I am still new to django, and I have spent 2 hours on looking on how to connect html sites and jsp sites to multiple apps. For example, I have index.html, calculator.jsp, login.jsp, register.jsp, and 2 other django apps. The index.html can link to 3 jsp sites, and 2 django apps. The problem is how to run multiple django servers for multiple apps simultaneously. Can sb help me ? I think I should use these: uswgi, nginx or django apache. Nevertheless, I get lost while following the API documentation. Also, there is no youtube video that show how to run multiple django servers. -
How to use variables in ModelChoiceField queryset
I am trying to use a specific list of data in my form with Django. I am using ModelChoiceField to retrieve from the model the data I need to display in the form (to let the users select from a scolldown menu). My query is complicate because need two filters based on variables passed by views I've tried to use the sessions but in form is not possible to import the session (based to my knowledge). form.py def __init__(self, pass_variables, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['initiative'] = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.filter(company=pass_variables[1], username=pass_variables[0]).values_list('initiative', flat=True)) view.py pass_variables = ((str(request.user), companyname)) f = Issue_form(pass_variables) If I don't pass the variable the process works. The problem is with the code above as the form don't provide any error but it doesn't pass the if f.is_valid(): Thanks -
How to convert Template tags from normal django to the one django-hosts use
I have just added django-hosts to setup subdomains for my site which works perfectly. Next step is just to convert all the normal django URL's in my template to the one django-hosts like. I know how to link pages , but once I need to add variables to my URL's i'm not sure how to construct the code for it. Normal django URL that works {% url 'golemstats:nodeinfo' node.Node_id node.Node|slugify %} How do I convert that to a URL that django-hosts like? I've tried the following: {% host_url 'nodeinfo' host 'golemstats' 'node.Node_id' 'node.Node|slugify' %} hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'golem', 'golemstats.urls', name='golemstats'), ) golemstats.urls from django.urls import path from . import views app_name = 'golemstats' urlpatterns = [ path('', views.index, name='index'), path('node', views.searchNode, name='searchNode'), path('node/<nodeid>/<node>', views.nodeinfo, name="nodeinfo"), path('version-notifier', views.notifierIndex, name="notifier"), path('ports', views.portScanner, name="portscanner"), path('scoreboard', views.scoreboard, name="scoreboard"), path('tools', views.tools, name="tools"), path('troubleshooting', views.troubleshooting, name="troubleshooting"), path('network', views.networkOverview, name="networkOverview"), ] -
How to select data from a query set and pass it to the same page to perform an insert in a database with django
I try to implement sort of a simple sales app in my django webpage, I try to select some data from a filter I implemented from this video video, I need to add select buttons infront of the element and a button to add. This is what I want to implement image, after I select one element and press ADD, then the element should be added in the second block and then when I press finish then it should be added to my database. The table where i should the products is model with the following code class Product(models.Model): name = models.TextField(blank=False, max_length=25) brand = models.TextField(blank=False, max_length=25) price = models.PositiveSmallIntegerField(default=200) I know how to login and start session. So I would like to add from the second block (like in the image) with the button finish to a table defined with: class Sale(models.Model): user = models.TextField(blank=False, max_length=25) # The current log in user product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField(default=200) # The price This is for personal use, so it don't matter that is not bootstrap or look badly. Preferably I would like to know if there is a tecnique to do this and how is called or if I … -
UnboundLocalError: local variable 'team_members' referenced before assignment
i am getting below error UnboundLocalError: local variable 'team_members' referenced before assignment slug values in model by default are 1 . This is the function def single_slug(request, single_slug): team = [c.infraTeam_slug for c in infraTeam.objects.all()] if single_slug in team: team_members = TeamMember.objects.filter(infra_team__infraTeam_slug=single_slug) series_urls = {} for m in team_members.all(): part_one = vulnerability.objects.filter(member_name__member_name=m.member_name).earliest("vulnerabilty_date") series_urls[m] = part_one.vulnerability_slug return render(request=request, template_name='main/category.html', context={"member_name": team_members, "part_ones": series_urls}) Please help how cann i solve this problem -
Run a python script just after run server django
I have a python script with indefinite loop it keeps in checking for the data, now I am confused how do I execute it so that it keeps running if the server is running. I think the script should run just after I run server in django but how do I run this script? Any suggestions? -
How can I exclude an object from my model?
I need to exclude 1 size from my model Good with field: Size = models.ManyToManyField('Size') Size model: class Size(models.Model): size = models.CharField(max_length = 15) def __str__(self): return self.size I try do this in views.py: good1 = Good.objects.get(id = good_id) choosen_good_size = good1.Size.get(size = 'XS') choosen_good_size.exclude() good1.save() But I get an error: Exception Value: 'Size' object has no attribute 'exclude' In another cases I get AttributeError: Manager isn't accessible via Good instances What should I do to make it works? -
How to change column name and alignment
Hi I am using TabluarInLine in my Django ModelAdmin. How can I rename DELETE? column, and center those checkboxes in the cell (I want them and delete column to create a line). -
TypeError: string indices must be integers When Checking array with dictionaries
When checking if a key with certain value exist, I get a Type Error: string indices must be integers. if not any(dObj["date"] == wholeDay for dObj in userPunchCard.clock): status = "Clock In" content = { "name" : user.name, "title" : user.title, "status" : status } This is the db for userPunchCard class StaffMember(models.Models): name = models.CharField(max_length = 255) title = models.CharField(max_length = 255) email = models.ChardField(max_length = 255) password = models.ChardField(max_length = 255) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) objects = UserManager() class PunchCard(models.Model): clock = models.CharField(max_length = 9999) employee = models.ForeignKey(StaffMember, on_delete=models.PROTECT) I'm positive that userPunchCard.clock is indeed an array with at least one dictionary present because of this code. if userPunchCard.clock is None: print ("if was hit in dashboard") else: if not any(dObj["date"] == wholeDay for dObj in userPunchCard.clock: status = "Clock In" content = { "name" : user.name, "title" : user.title, "status" : status } When Creating a Django db table, the table will have null when empty and None works for me all the time to check for it. So the else in this code is running instead of the if. Also, when a user does clock in, this is the code … -
Annotating with aggregation from another model
I have 4 models class SingleDonation(models.Model): name = models.CharField( max_length=255, ) email = models.EmailField() transaction = models.OneToOneField(Transaction) class RecurringDonation(models.Model): name = models.CharField( max_length=255, ) email = models.EmailField() subscription = models.OneToOneField(Subscription) class Subscription(models.Model): raw_amount = models.PositiveIntegerField() interval = models.CharField( max_length=10, ) class Transaction(models.Model): raw_amount = models.PositiveIntegerField() subscription = models.ForeignKey( to=Subscription, on_delete=models.SET_NULL, null=True, blank=True ) I'm trying to annotate both Donations querysets with the total amount donated by the email to get the correct amount for API for let's say SingleDonation, I do it in serializer this way def get_transaction_sum_for_email(self, obj): single_donation_sum = SingleDonation.objects.filter(email=obj.email).aggregate(Sum('transaction__raw_amount')).get('transaction__raw_amount__sum') recuring_donation_sum = RecurringDonation.objects.filter(email=obj.email).annotate(transaction_sum=Sum('subscription__transaction__raw_amount')).aggregate(Sum('transaction_sum')).get('transaction_sum__sum') or 0 return single_donation_sum + recuring_donation_sum Yet I want to order_by() this amount, so I have to annotate my queryset with this number, and this is where I have a problem. How do I do it? -
Django Pagination Error. Which object to use as page_obj?
I am trying to make a quiz where each question will be displayed on a different page. But I guess attributes like has_previous and has_next are not working. views.py def instructions(request): ques = Questionm.objects.first() context = {'ques': ques} return render(request,'events/instructions.html', context) def ques_detail(request,pk=Questionm.objects.filter(marks=10).order_by("pk").values().first()): ques = get_object_or_404(Questionm, pk=pk) context = {'ques': ques} paginate_by = 1 return render(request, 'events/ques_detail.html', context) def ques_detail2(request, pk): ques = get_object_or_404(Questioni, pk=pk) context = {'ques': ques} paginate_by = 1 return render(request, 'events/ques_detail2.html', context) ques_detail.html {% block title %} <div class="round1"> <h1>ROUND-1</h1> </div> <div class="ques"> <h2>Q. {{ ques.question }}</h2><br><br><br><br> <p><input type="checkbox" name="opt1">{{ ques.opt1 }}<br><br> <input type="checkbox" name="opt2">{{ ques.opt2 }}<br><br> <input type="checkbox" name="opt3">{{ ques.opt3 }}<br><br> <input type="checkbox" name="opt4">{{ ques.opt4 }}<br><br></p> <div class="pagination"> {% if is_paginated %} {% if ques.has_previous %} <a class="btn btn-outline-info mb-4" href="?page={{ ques.previous_page_number }}">Previous</a> {% endif %} {% for num in ques.paginator.page_range %} {% if ques.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if ques.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ ques.next_page_number }}">Next</a> {% endif %} {% endif %} </div> </div> {% endblock %} I am just able to see question and four options. Not the previous and next buttons. Someone kindly help. -
How to setup django shell kernel for jupyter notebook running in separate docker containers
I have several Django projects, each running in a docker container (each one having its own) on a single machine. I want to setup a Jupyter Notebook in a new container, and be able to have kernels for all these django projects (kernels that use their shell and environment). Any ideas? I came across this answer but this can only be used for when the django project and the jupyter notebook are running on the container :( -
How can I combine bootstrap cards with lightbox?
I have a page where users will be able to upload many images and view them in the page with other data so i wanted to use Bootstrap cards under the other data and combine lightbox with bootstrap. Here's the code I wan to make a for loop to repeat it. <div class="row"> <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg> <div class="card-body"> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">View</button> <button type="button" class="btn btn-sm btn-outline-secondary">Edit</button> </div> </div> </div> </div> </div> </div> I tried this : <div class="row"> <div class="col-md-12"> <div class="mdb-lightbox"> {% for image in Patient_detail.images.all %} <figure class="col-md-4"> <img alt="picture" src="{{ Patient.UploadedImages.pre_analysed.url }}" class="img-fluid img-thumbnail"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="card-body"> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <!-- <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> --> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </div> </form> </figure> {% endfor %} </div> </div> </div> The images Number is shown (places for the …