Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set Permission for custome module in drf
I am trying to set permission from my custome module. Here is my model classes: class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) role = models.CharField(max_length=30, default='manager') status = models.IntegerField(default=1) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email Now I want to set permission based on role(such as manager,customer,admin etc) value from the Account class. I am using function based view in this project. So now How I can do this? -
Recieving error when use Process and works fine when use Thread in Django Python
I am developing a solution in Django 2.2 in which I need to save some objects for each request until user is connected. When I am using threading.Thread its works fine, but I want to use the terminate() method of multiprocessing.Process also. When I test the same code with Process then it raise extension that it cannot import some modules. Here are code samples for Thread and Process: Code with Thread users_resources[request] = [] users_resources[request].append(DriverHandlerDotMed(request)) Thread(target=users_resources[request][0].run_until_connected).start() Code with Process users_resources[request] = [] users_resources[request].append(DriverHandlerDotMed(request)) Process(target=users_resources[request][0].run_until_connected).start() Error Details Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandlerDotMed.py", line 1, in <module> from .DriverHandler import DriverHandler File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandler.py", line 3, in <module> from .settings import BASE_DIR, users_resources File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\settings.py", line 118, in <module> from .DriverHandlerDotMed import DriverHandlerDotMed ImportError: cannot import name 'DriverHandlerDotMed' from 'src.DriverHandlerDotMed' (C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandlerDotMed.py) -
Switch database based on login or company credentials django rest framework on the fly
I want to have multiple database containing all tables, data etc and when user enters company credential. The settings will change to that company db I am using rest framework. I am using dosier for login register but they are saving data in the same master database. Is it possible to do the same in django. but before that user needs to add company. One approach i can think of is If a separate api is created with flask or whatever how can we change db settings on the fly in django -
How to checked multiple checkbox over loop
In One Array I am getting array like : ['1','2','3','4','5','6'] And In another array i Am getting array like : ['1','6'] In template i am doing like : <div class="col-md-10"> {% if edit_data.features %} {% for feature in edit_data.feature %} {% for features in edit_data.features %} {% if feature.id == features.feature_id %} checked='checked' {%endif%} {%endfor%} <input type="checkbox" name="features" value={{feature.id}} {{checked}}> {{feature.name}}</option> {%endfor%} {%endif%} </div> After This i am getting Like: How Can i select the checkbox over the loop i am not able to create variable inside if condition. i am newbe please let me now how can i make checkbox to be selected [1]: https://i.stack.imgur.com/LzVV4.png -
django+celery+redis,app. Control. Inspect ()
Now I want to use the app. Control. Inspect () to collect the list of pending tasks, and the waiting time of task in the queue, don't know how to get and write the code, is there any relevant snippet that I can see ?Thanks. -
hello can you help me
i hava an error as Unable to create process using 'C:\Users\Mr.M\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' i cant fint any solution -
Ckeditor convert images to html tags
I am using CKEditor with Django. I faced an issue. When I upload an image in the CKEditor image looks good in the editor. But when I save images are converted to HTML tags. How can I fix it? -
Django: Related Objects for Authenticated User
In Django we can create related models: class User(models.Model): pass class TaskSet(models.Model): user = models.ForeignKey(User, related_name='tasksets') title = models.Charfield() class Task(models.Model): user = models.ForeignKey(User, related_name='tasks') taskset = models.ForeignKey(TaskSet, related_name='tasks') Makes sense, I can call request.user.tasksets– but what's the correct way to get the tasks in the taskset? request.user.tasksets.first().tasks will return all of the tasks for the entire task set– but how can I get the tasks for that user only? -
Multiple web frameworks in single AWS instance?
This is an infrastructure design question. Is it better to: Run multiple web frameworks on a single AWS instance? Run each framework in separate AWS instances? Here are the web frameworks used: Backend: Django + PostgreSQL Frontend: NodeJS Forum: Ruby on Rails + PostgreSQL Option 1 pros: No need to worry about AWS instance type (just use a powerful one) Easy to maintain when everything is in one place, only 1 instance Option 2 pros: Better allocation of AWS resources depending on load (backend / frontend / forum). Easier to scale? I am not sure what's the better option. Would love to hear your experience and opinion on this. Thanks. -
Default migrate table name rename
Since my project would like to create all the table into an old database, It would be a problem if I use the default name from Django. Is there any way to rename all the table like the JPG below? -
Video dialog not rendering properly using summernote-django in django website
I am using summernote for rich text editing . It is working fine with text but during video uploading/Inserting video url, it is fixing the width and height during posting and during rendering it is not showing proper dialog, In my case video dialog 20% cuts . for example it sets the width 640px during posting and during rendering it is showing same 640px which is not good as per page design and page requirement less than 450px . So I mean to say that it is not response in video dialogs. Please anyone help me for that . I add an image please check it Thank you . -
How do I call a Python function with parameters from an HTML page (alongside Django)?
I'm in the process of writing a Django app, but I've hit a slight roadblock. You see, I have the backend return an HTML page, and that works just fine. What I am having trouble with though is going the other way around. I am trying to call a function on the backend once the user clicks a button. Now, I've already searched to see if anyone else has asked this question before, but all the posts that came up had a different scenario linked to them. All of them were for GET requests, but I need to be able to POST some data instead. Does anyone know how I can do this? -
Django Python save database blog posts to a zipfile?
I have a django blog and want to download a backup zipfile with all the entries. The blog post text content is stored in the database. I have written this code with the goal of trying to get the zipfile to save a bunch of .txt files in the main zip directory, but all this code does is outputs a single corrupted zip file. It cannot be unzipped but for some reason it can be opened in Word and it shows all of the blog post text mashed up. def download_backups(request): zip_filename = "test.zip" s = BytesIO() zf = zipfile.ZipFile(s, "w") blogposts = Blog.objects.all() for blogpost in blogposts: sio = StringIO() sio.write(blogpost.content) filename = blogpost.title + ".txt" zf.writestr(filename, sio.getvalue()) resp = HttpResponse(s.getvalue()) resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp Any help is appreciated. -
chained event after dropdown option select
I want to add a column that will only be shown when I select some specific options from dropdown menu. I had written the dropdown menu part(in django template) and also retrieved the option value in the backend. I can create a field after submitting the form by using that value but I want to dynamically change the form. What I thought should be the process is, is to take the value from the dropdown and apply an if condition on its value. What I want to know is how can I dynamically take its value without submitting the form -
Mocking django Form clean_data field
I have a simple django form like this: class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) My view uses it like this: def my_view(request): form = ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data ... I want to test my view and don't care about what the form actually does. This is what my test looks like so far @patch.object(ContactForm, 'is_valid') def test_my_view(mock_is_valid): is_valid.return_value = True ... assert response.status_code == 201 However, this doesn't work because form.cleaned_data is not set until form.is_valid() is called. How do I mock out the form.cleaned_data attribute if it doesn't exist in the first place? -
Flask Cache Clear on Refreshing the page
I need to clear the cache for proj1 template while refreshing the page as it loads image processing contents whereas home template has static images where I need to maintain cache. I have tried with below code but it doesn't work. Could anyone help me to improvise this model? cache_config = Cache(app, config={'CACHE_TYPE': 'null'}) app.config["CACHE_TYPE"] = "null" @app.route('/proj1/') def proj1(): return render_template('proj1.html') @app.route('/home/') def home(): return render_template('index.html') -
How to create abstract model in Django?
I am new to Django framework and in my project I have a model called Layer. class Layer(models.Model): name = models.CharField(max_length=255) I would like layer to have a relationship with an abstract model called "Geometry", more specifically, one layer should have one or no Geometry and one Geometry should be owned by one layer. The problem is that I have for types of Geometries and they all have different properties, so I decided to create multiple geometries: class Circle(models.Model): radius = models.CharField(max_length=255) class Rectangle(models.Model): height = models.CharField(max_length=255) width = models.CharField(max_length=255) I would like to have a data structure where both models are of the same type (Geometry). I would like to call layer.geometry and be able to get either a circle or a rectangle, or a cross and so on. Is that possible? And how is the database shape going to be like? Is Django going to create two different tables or one table with merged properties? Thanks in advance -
How to secure malicious PNG uploads on django?
I am hosting a Django application using Nginx which is serving media and static files on the same domain. In the Django docs, they warn about a vulnerability for malicious PNG uploads: Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for ImageField image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server. Serving my static and media files on S3 for example is not an option in my case.. Also, I am not sure if I fully understand their second recommendation. It is recommended to white list files by its extensions, but what should keep out of my white list? .html or .png? In nginx.conf, I changed from default_type application/octet-stream; to default_type text/plain;. Is it safe enough? I just want to make sure that I will be able to serve static and media files by myself, … -
What is URL of my django deployed on gcp compute engine?
I am sorry to ask this beginner question but all results I can find is for Google App Engine deployment of Django and none for Google Compute Engine. Context I build a django app and tested locally. When I run it locally with "python manage.py runserver", it works when I enter "127.0.0.1:8000" it works. My Setup Now I bought a compute engine and created an instance. Installed my django app and now I run "python manage.py runserver" then it runs my website showing "Starting development server at http://127.0.0.1:8000/". But now I don't know what URL should I use to access my site over web!? My configuration for Google cloud compute: - Allowed HTTP/HTTPs while creating gcp instance - Added firewall ingress/egress for tcp 8000 Things I tried What URL should I now use to see my website over web? Say my external ip address is 35.243.41.52 , then I have already tried "35.243.41.52:8000" and "35.243.41.52/127.0.0.1:8000" but it doesn't shows my site. Then I tried to run "python manage.py runserver 35.243.41.52:8000" but it shows that this IP cant be assigned. It is my external ip of instance so it should be assigned? I think it should be a simple solution but … -
Understanding Database Locking during bulk_create() in Django
I'm using Django with Postgres as the DB. I have a table that has new entries getting created at a fairly high rate (average 4000 entries per minute). I'm now planning to move to a batch-write approach using the bulk_create() option. I'd like to understand if that's the correct thing to do. I'm worried about the database getting locked up in case the single batch write takes a long time, leaving other processes unable to read other entries from the table. Is this correct? Or is the lock a row-level lock, and the other entries are free to be read/updated? Also, if I should go ahead with it, how do I choose the correct batch size? TIA. -
Using setinterval to update Django Table
This post is based on a previous thread which seem to have a nice solution on how to reload table data in Django without refreshing the page. What it does: We use setInterval to make a GET AJAX request every 5 seconds to my view which renders a separate HTML file using this new context and then sends it as a response back to the main HTML table. It is working but it messes up the table structure and also creates duplicates. Issue 1: I do not use a table structure in the second HTML file, this messes it up since there is no styling once inserted into the main HTML file. But If I add a table structure the will be inserted for each row. The insertion also seem to insert all data from get_more_tables into the first column in the main HTML. Issue 2: It also creates duplicates, it keeps running despite only 2 rows. Is there any way to prevent this? Any help would be much appreciated! Main HTML & JS script <table class="table table-sm table-hover table-striped" id="_appendHere"> <thead class="thead-dark"> <tr> <th scope="col">Created</th> <th scope="col">Transaction</th> <th scope="col">Publisher</th> </tr> </thead> <tbody id="myBody"> {% for item in data %} … -
is it possible to target an object with a numeric variable and display it with the slug
I think it's useless to exclude the use of a numeric variable it has more flexibility and utility than a slug but a slug is better visually then all works well in my project but I would like to change that to be able to increase what is possible to do -
How to save Quill.js Rich text editor in Database MySQL, using Django?
I want to send the edited articles on my blog using the Quill Text Editor to the database and then retrieve the blog post when required. <div id="toolbar"></div> <div id="editor"></div> <button id="saveDraft">SAVE DRAFT</button> <script> var toolbarOptions = [ ['bold', 'italic', 'underline', 'strike'], // toggled buttons ['blockquote', 'code-block'], //[{ 'header': 1 }, { 'header': 2 }], // custom button values [{ 'list': 'ordered'}, { 'list': 'bullet' }], [{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript [{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent ['link', 'image','video','formula'], [{ 'direction': 'rtl' }], // text direction [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme [{ 'font': [] }], [{ 'align': [] }], ['clean'] ]; </script> <script> var quill= new Quill('#editor',{ modules:{ toolbar:toolbarOptions }, theme: 'snow' }); $('#saveDraft').click(function () { var draft = quill.getContents(); console.log(draft); }); Above code puts the editor on the page and last 2 lines saves the data in certain variable. From some searching i got found that data is JSON. The pictures below shows the variable it store data in. With Addition of New … -
Django Filter Choice Field displays correct values but wont filter
I'm using the Django filter app: https://github.com/carltongibson/django-filter I'm making a web-comic app and what I'm trying to accomplish is a drop-down filter field that displays the distinct values for that field. In this case, the series field. After reading their docs. And stack overflow questions like this one or this one . I can make the filter form display the correct drop down values. But when I attempt to filter by them, my result queryset returns no values! There must be something in the docs I'm not understanding. Here's my hopefully relevant code. filters.py import django_filters from .models import ComicPanel # Grab Distinct values for series def getUniqueSeries(): series_dicts = ComicPanel.objects.all().values_list('series').distinct() series_list = [] i = 0 for item in series_dicts: series_list.append((i,item[0])) i = i+1 return series_list class ComicPanelFilter(django_filters.FilterSet): series = django_filters.ChoiceFilter(choices = getUniqueSeries()) class Meta: model = ComicPanel fields = ['chapter', 'episode'] views.py def view_archive(request): comic_list = ComicPanel.objects.all() comic_filter = ComicPanelFilter(request.GET, queryset=comic_list) paginator = Paginator(comic_filter.qs, 8) page = request.GET.get('page', 1) try: comics = paginator.page(page) except (PageNotAnInteger, TypeError): comics = paginator.page(1) except EmptyPage: comics = paginator.page(paginator.num_pages) return render(request, 'comics/comic_archive.html', context = {'filter': comic_filter, 'comics': comics}) template.html ... <form class="form" method="GET"> {% csrf_token %} <table class="my_classes"> <thead> <tr> <th scope="col">Filter Comics: … -
Enter a valid date/time in Django Forms
Anytime I try to input datetime into my form, it always says Enter a valid date/time I tried different datetime formats; the one i speified and the default ones, they all did not work. I have tried different solutions on Stack Overflow, but they all do not seem to work. The field I have this issue with is due_date NOTE: I didn't show any imports Also, i need recommendations for nice datetime pickers. All the ones I tried didn't work for some reason or the other. views.py: @login_required def task_create(request): data = dict() #, data=request.POST if request.method == 'POST': form = TaskForm(request.user, data=request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = TaskForm(request.user) context = {'form': form} data['html_form'] = render_to_string('partial_task_create.html', context, request=request ) return JsonResponse(data) forms.py: class TaskForm(ModelForm): due_date = forms.DateTimeField(input_formats=['%I:%M %p %d-%b-%Y']) parent = forms.ModelChoiceField(queryset=Task.objects.all(), empty_label="---None---", required=False) #widget=DateTimePickerInput(format='%I:%M %p %d-%m-%Y') class Meta: model = Task fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent'] widgets = { #'due_date': DateTimeInput() } def __init__(self, user, *args, **kwargs): super(TaskForm, self).__init__(*args, **kwargs) self.fields['categories'].queryset = Categories.objects.filter(Q(user_id__isnull=True) | Q(user_id=user.id))