Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix 'Image Source Url is missing' issue when using Django CkEditor
I installed djnago-ckeditor and followed the installation guide.Using RichTextUpload() for my models which are imported from ckeditor_uploader.When I try to upload an image it is saying that 'Image Source Url is missing'. I'm using python, django latest versions basesettings.py INSTALLED_APPS=[ ...... 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR, MEDIA_ROOT, 'ckeditor_media') CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': '100%', }, } urls.py path('ckeditor/', include('ckeditor_uploader.urls')), models.py from ckeditor_uploader.fields import RichTextUploadingField ...Model about = RichTextUploadingField() -
Ajax with primary key in url of Django cannot work
all, i am using Django to do a social website and now i am trying to do friend network. The problem i encountered now is when i am using ajax to pass user id in url and it throw url cannot be found error, maybe see code the will be much clearer. the code is as following i tried to take awayid, that is , take away all id in ajax, url, and method, then it can work. but if i add id parameter in, then it cannot work html template <button class="add-friend-btn" id="add-friend"> Add friend <script src="{% static 'account/js/friends.js'%}" type="text/javascript" ></script> <script type="text/javascript"> var userprofilePk = "{{userprofile.pk}}"; // other user's id(primary key) </script> {% endif %} javascript friend.js $(document).ready(function() { var addFriend = document.getElementById('add-friend'); addFriend.addEventListener("click", function (event) { $.ajax({ type: 'POST', headers: { "X-CSRFToken": csrftoken }, url: "ajax/friend-request/send/"+userprofilePk+"/", data: { "test": "test", }, dataType: 'json', success: function (data) { }, error: function (error) { }, }); }); }); Django url urlpatterns = [ re_path("ajax/friend-request/send/<pk>/", views.send_friend_request, name="user_send_request"), ] views.py def send_friend_request(request, id): print("send_friend_request") payload = {"test": "test"} return HttpResponse(json.dumps(payload), content_type='application/json') the error message is: Not Found: /account/profile/sm10547/ajax/friend-request/send/2/ app_1 | HTTP POST /account/profile/sm10547/ajax/friend-request/send/2/ 404 [0.01, 172.18.0.1:38852] -
How to test email confirmation?
I'm trying to make a test for the email confirmation view with django-rest-auth. Here is what I have: def test_verify_email(self): # Verify email address username = 'userTest' payload = { 'email': 'test@example.com', 'password1': 'TestpassUltra1', 'password2': 'TestpassUltra1', 'username': username, } res = self.client.post(REGISTER_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(email='test@example.com') # TODO retrieve the confirmation key from the user resp = self.client.post(VERIFY_USER_URL, {'key': ''}) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.client.post(REGISTER_USER_URL, payload) will send an email with the confirmation code in it and while I know I could retrieve that code with django.core.mail.outbox in the code I rather not do that as I will have to parse the email content to look for the confirmation code (which can kill my test if the email changes). I couldn't find this code stored anywhere in the DB, it seems to really exist only inside the body of the email sent. My question is: Is it possible to recover this verification code in my test without parsing the email? I just want to retrieve it to launch my self.client.post(VERIFY_USER_URL, {'key': ''}) with it. Here is the example of the content of an email: Hello from example.com! You're receiving this e-mail from NomadSpeed because user detro1 has given yours as … -
Neo4j + Django: Where do I write the top-level Driver object?
It is written in the documentation that For general applications, it is recommended to create one top-level Driver object that lives for the lifetime of the application. For example: from neo4j import GraphDatabase class Application(object): def __init__(self, uri, user, password) self.driver = GraphDatabase.driver(uri, auth=(user, password)) def close(self): self.driver.close() Where do I write this code? I want to use neo4j as a database in views.py. -
How do you find the source of a related_name in Django in large codebases?
Take these two models for example (pseudo code) class House(): Pass class Cat(): house = Foreignkey(to=House, related_name=“cats”) Now say if this is a massive codebase that I’m not familiar with with these definitions in different files. I see an instance of House being called with the method “cats” house1.cats And I want to investigate and see where cats came from. But when I go to the definition of House, there is no mention of cats. There is no way I can figure this out just by looking at House, and names are not always as simple to follow as this example(sometimes the related name is not similar to the class name). I do use fuzzy finding and search for related_name=cat In the codebase and that usually works, but it does not work for models where the related_name was generated through an base class such as class Base(models.Model): m2m = models.ManyToManyField( OtherModel, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) It’ll be basically impossible to figure out what model is the source of relation other than hunting it down manually by looking at every single file, which is quite difficult in a large codebase My question is, is there a way or workflow to figure this … -
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).