Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to configure a link to open a page that contains an iframe, and have that iframe query an URL?
I am setting up a registration confirmation email system. The sign-up process usually takes place on my platform, and upon receiving the confirmation email, the link redirects to the same website the new user has signed-up on. But the sign-up page I'm having trouble with is contained in an iframe on a website that I have no control over. I can only change what's inside of the iframe. I would need the link sent through email to redirect to the page that contains the aforementionned iframe, while still activating the user in the iframe. I work with django templates. I can change the body of the email, the registration page and the confirmation page, that's about it. -
Django with Datatables Edits Database in Front End
I am trying to build a page that user can select and edit multiple/all rows. I am able to replicate the check button for each row and select all button according to https://www.gyrocode.com/projects/jquery-datatables-checkboxes/. But I am unable to replicate the submit button. My guess is because the example uses ajax. I use pandas data frame. I have limit knowledge to html and js, so what I did is basically try to understand what the code is doing.. python code def test(request): df = pd.DataFrame(list(Test.objects.all().values())) var1 = df.to_html(justify='center', index=False) var1 = re.sub('table border="1" class="dataframe"', 'table id="example" class="table table-striped table-bordered" style="width:100%"', var1) return render(request, 'main/test.html', {'dfs': var1}) html code <form id="frm-example"> {{dfs|safe}} <p> <button>Submit</button> </p> <p> <b>Selected rows data:</b><br> <pre id="example-console-rows"></pre> </p> <p> <b>Form data as submitted to the server:</b><br> <pre id="example-console-form"></pre> </p> </form> <script src="https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.11/js/dataTables.checkboxes.min.js"></script> js code $(document).ready(function (){ var table = $('#example').DataTable({ paging:false, 'columnDefs': [ { 'className': 'dt-body-center', 'targets': 0, 'checkboxes': { 'selectRow': true } } ], 'select': { 'style': 'multi' }, 'order': [[1, 'asc']] }); // Handle form submission event $('#frm-example').on('button', function(e){ var form = this; var rows_selected = table.column(0).checkboxes.selected(); // Iterate over all selected checkboxes $.each(rows_selected, function(index, rowId){ // Create a hidden element $(form).append( $('<input>') .attr('type', 'hidden') .attr('name', … -
Use custom `Manager` for "default values" creation and fetching
I have and Employee model and an EmployeeType model, with Employee having an attribute called Employee.employee_type which is of type EmployeeType. Currently on the creation of a client, we run something to create "default" values for the EmployeeType. Right now, that logic is in a method within the module that handles a new client being created... but I was thinking a better place for this would be to be with the EmployeeType model. My question is - would it be appropriate to make a custom Manager attribute on the EmployeeType that does the creation and/or fetching of these default types? See the following for what I believe I am trying to accomplish: class DefaultValueEmployeeTypeManager(models.Manager): def get_or_create_default_values(self): first_type = self.model.objects.get_or_create(name='First Type') second_type = self.model.objects.get_or_create(name='Second Type') third_type = self.model.objects.get_or_create(name='Third Type') return (first_type, second_type, third_type) class Employee(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) defaults = DefaultValueEmployeeTypeManager() # Code in another file, handling the setup of a new client from models import EmployeeType def create_new_client(client): # make sure the default values are there EmployeeType.defaults.get_or_create_default_values() My question is whether or not this is acceptable/expected behavior for a Manager object to handle? Or should this just be some sort of @classmethod (or similar) on the EmployeeType … -
How to add dropdown list which contains all element in my product list
I can iterate over different products using All {% for c in categories %} {{ c.name }} {% endfor %} this is my code for dropdown list ,but is is not showing anything after books. Categories All Electronics Books All {% for c in categories %} {{ c.name }} {% endfor %} -
SyntaxError: unexpected EOF while parsing [django python manage.py runserver do not work]
I am currently taking tutorials on Django framework using one of this playlist videos on youtube, i am following this video step by step but any time i add new codes using my text editor [visual studio code] one syntax Error or another keeps coming up, am just trying to run the django web server using the code python manage.py runserver the error message gotten is File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\Desktop\djangoproject\djangoproject\urls.py", line 13 ^ SyntaxError: unexpected EOF while parsing please help me thank you -
On selecting one item of <datalist> other datalist should open according to the selected item of first datalist
"I am making an inquiry model form. I have created datalist widget already. Now what I want is that on selecting the item from datalist, one more datalist should appear on the basis of the item selected in first datalist. " forms.py from django import forms from .fields import ListTextWidget class FormForm(forms.Form): data = ('Mexico', 'USA', 'India', 'France') char_field_with_list = forms.CharField(required=True) char_field_with = forms.CharField(required=True,widget = ListTextWidget(data_list=data,name='data')) def __init__(self, *args, **kwargs): _country_list = kwargs.pop('data_list', None) super(FormForm, self).__init__(*args, **kwargs) self.fields['char_field_with_list'].widget = ListTextWidget(data_list=_country_list, name='country-list') field.py (where a widget is created) from django import forms class ListTextWidget(forms.TextInput): def __init__(self, data_list, name, *args, **kwargs): super(ListTextWidget, self).__init__(*args, **kwargs) self._name = name self._list = data_list self.attrs.update({'list':'list__%s' % self._name}) def render(self, name, value, attrs=None, renderer=None): text_html = super(ListTextWidget, self).render(name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + data_list) views.py from django.shortcuts import render # Create your views here. from .forms import FormForm def country_form(request): # instead of hardcoding a list you could make a query of a model, as long as # it has a __str__() method you should be able to display it. country_list = ('Mexico', 'USA', 'China', 'France') form = … -
How to make all the delete href tags make work with java scripts if clicked in Django
I have written a java script for the conformation box before deleting the comments. If user clicks delete, it should pop the box for delete conformation. If i have series of comments of same user, as i am printing the comments in loop the java script logic is staying with the first delete comment itself until i delete it. If i say no, and try to delete second comment, the java script logic is not function. Can any one help me with this issue. Should i need to place the java script logic some where else in the code. Does that recognize? <div class="container"> <h2 class="text-center">User Comments</h2> {% for comment in comments%} <p class="text-secondary text-center">{{ comment.created }}</p> <p> {{ comment.body }} </p> {% if comment.user == request.user.username %} <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a> <a class="btn btn-danger btn-sm mt-1 mb-1" id="delete-object" >Delete Comment <script type="text/javascript"> document.getElementById("delete-object").onclick = function(){ if (confirm('Delete the comment')){ alert('hi'); #Link to delete comment}} </script> {% endif %} -
Can django @login_required be used on APIs used by a mobile app?
We're using django-notifications-hq to provide users with persistent notifications in our app. Until recently, they lived only in the web app, however now we want to show the notifications in the mobile app as well. Also, our server is set up with CSRF. All the endpoints provided by django-notifications-hq use @login_required annotation to verify that user is authenticated. However, when we're trying to call any of those endpoints from our mobile app, we get 403 response. To be specific, the first OPTIONS request returnd 200, but then the following request for those APIs always results in 403. This is not a problem when we're using i.e. django-rest-framework's permissions.IsAuthenticated. The 403 returns this in the response: <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> Suggesting it's a CSRF problem, even though mobile app obviously doesn't provide cookies in their requests (it's token-based authorization). Is this a general … -
Using a base.html file but modifying more than just the body
First of all, I have no problems with my code. This question is more of a "Is this possible and if so/not what is the right way of doing it ?" I have a website where every page has the same look, the differences between them are as follows: The homepage has an interactive leaflet map (javascript) The titles vary on every page The elements in the head tags change from one page to another but not always The background image doesn't change Within the body tag, I have a div tag containing a page footer common to all pages What I would like to know is if it is possible to use a base.html template for these pages knowing the above constraints and also, if it is, how I would go about modifying the said pages to do so. As I said, the code isn't really an issue here but for clarity and for you to be able to see what changes from one page to another, here is the Github repository for the project. (The project is a university project and therefore some parts of the code is in French since my university is a french University) https://github.com/MaxMichel2/PWEB … -
How to filter queryset for serializing a nested serializer using instance in django rest framework?
My serializers.py file from rest_framework import serializers from diagnosisApp.models import Question, Option class OptionSerializer(serializers.ModelSerializer): class Meta: model = Option fields = ('id', 'content') class QuestionSerializer(serializers.Serializer): content = serializers.CharField() options = OptionSerializer( Option.objects.filter(optiongroup__question=**insert instance value here**).distinct(), many=True ) I'm trying to create a nested OptionSerializer inside QuestionSerializer but I need to filter the queryset based on the question instance which will be passed during initialization in this section: optiongroup__question=**insert instance value here**. How do I do this? P.S: Please don't tell me to use ModelSerializer or SerializerMethodField because options is not directly related to Question and the options field needs to be writable. -
Cannot access admin panel after setting up django-oauth-toolkit
I had a pet-api (testing api) without authentication. I'm trying to learn how to implement oath2 to add security to my app. I'd like to access the models of my app through a request call using the API but also through the Django Admin Panel. I'm following this tutorial: https://medium.com/@halfspring/guide-to-an-oauth2-api-with-django-6ba66a31d6d for setting up: django-oauth-toolkit Tutorial says I should add this code to settings: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend' # To keep the Browsable API 'oauth2_provider.backends.OAuth2Backend', ) But when I run server, and try to access /admin, I get: ModuleNotFoundError at /admin/login/ No module named 'django.contrib.auth.backends.ModelBackendoauth2_provider'; 'django.contrib.auth.backends' is not a package If I comment: # 'django.contrib.auth.backends.ModelBackendoauth2_provider'; I can access the interface for the login, but says my user or password are wrong (they are not). Commenting both lines I can access the admin panel without problems: #AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.ModelBackend' # To keep the Browsable API # 'oauth2_provider.backends.OAuth2Backend', #) -
How to set environment variables for different domains in one docker-compose file
I am trying to run multiple simple one-page sites using docker-letsencrypt-nginx-proxy-companion. For each domain I have to run a separate docker container with environment variables: VIRTUAL_HOST: site.com LETSENCRYPT_HOST: site.com LETSENCRYPT_EMAIL: foo@site.com That is, as many domains / subdomains I have - so many containers I should run. Is there a way to specify these variables to run a single container with app serving my sites? I want to run my sites using Django Sites framework in a single container. -
Obtaining host url of sftp server from a docker container
I am running django project in docker container. I have a sftp server running on another container, and wish to sftp into it from web container. Using python library paramiko from shell I can manually sftp into container by finding IP of server using docker inspect. I wish to save sftp url in settings.py file and reference it later when needed. Currently my docker-compose file has sftp image: sftp: image: atmoz/sftp container_name: sftp volumes: - /host/upload:/home/ ports: - "22:22" command: - foo:pass:::upload And web container has following environment variables: environment: SFTP_USERNAME: foo SFTP_PASSWORD: pass SFTP_HOSTNAME: sftp SFTP_PORT: 20 Then in settings.py I constructed url as follows: SFTP_URL = 'sftp://' + SFTP_USERNAME + ':' + SFTP_PASSWORD + '@' + SFTP_HOSTNAME + ':' + SFTP_PORT + '/' this is used in tasks.py in a simple function for now, mostly just creating the sftp connection def sftp(): transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT))) transport.connect(username = settings.SFTP_USERNAME, password = settings.SFTP_PASSWORD) sftp = paramiko.SFTPClient.from_transport(transport) return sftp However instead of connecting, get following error message: Traceback (most recent call last): File "<console>", line 1, in <module> File "/opt/django/CustomerData/tasks.py", line 34, in sftp transport = paramiko.Transport((settings.SFTP_URL, int(settings.SFTP_PORT))) File "/opt/venv/lib/python3.5/site-packages/paramiko/transport.py", line 357, in __init__ hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM File "/usr/lib/python3.5/socket.py", … -
Remove from user permissions list if user group have the same permissions
I'm looking a way to filter user permissions from UserChangeForm, if I'm editing an user that belongs to a group that has X permission, how I can filter and don't show permission "X" in the permission field? There is some Django helper about this? Thanks! -
Extreme latency in Django API running on EKS
I have deployed a Django Rest API container on Amazon EKS (Kubernetes) but a simple HttpResponse took around 4-8 seconds. def home(request): return HttpResponse("Homepage") Here is my stack: EKS with 3 worker nodes each running on t2.medium (2cpu, 4GB ram) ELB: L7 application load-balancer directing requests to 2 different services echoserver: to test simple response time DjangoAPI Containers: DjangoAPI Redis - cache echoheaders: Simple echo server (gcr.io/google_containers/echoserver:1.4) NAME READY STATUS RESTARTS AGE pod/djangoapi-65799dd6dc-gkpfp 1/1 Running 0 1h pod/echoheaders-5cff747d7d-n4jnt 1/1 Running 0 1h pod/redis-7d9fbf54cd-lpffv 1/1 Running 0 1h NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/djangoapi-svc NodePort 10.100.41.163 <none> 8000:30327/TCP 11d service/echoheaders NodePort 10.100.94.85 <none> 80:30317/TCP 12d service/kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 35d service/redis ClusterIP 10.100.210.207 <none> 6379/TCP 35d NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE deployment.apps/djangoapi 1 1 1 1 11d deployment.apps/echoheaders 1 1 1 1 12d deployment.apps/redis 1 1 1 1 35d When the same DjangoAPI image was deployed to my local setup (minikube), the average response time is around ~200ms. Things I've tried Adjusting EC2 instance size from t2.small to t2.medium Adding more DjangoAPI replicas on Kubernetes deployment (from 1 to 3) Setting and removing resources limits on each deployment. resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: … -
Django can't find model property
In my Django project, I have a models.py that looks like this: from django.db import models class Battle(models.Model): def __str__(self): return self.battle_name battle_name = models.CharField(max_length=200) start_time = models.DateTimeField() end_time = models.DateTimeField() password = models.CharField(max_length=50) When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties. $ python manage.py shell Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from battles.models import Battle >>> Battle.objects.all() <QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]> >>> Battle.objects.filter(battle_name='my first battle') <QuerySet [<Battle: my first battle>]> >>> import datetime >>> Battle.objects.filter(end_time<datetime.datetime.now()) Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'end_time' is not defined >>> Battle.objects.filter(end_time < datetime.datetime.now()) Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'end_time' is not defined Am I missing something? -
How to get the last two registration on xml with jinja2
I receive a webservice in XML, I change it to dict with xmltodict. Then in the submit.html I use jinja2 to read the dict and get the values. The problem is I get a lot of entries with: <institution code="A15"> <transition type="credit" code="N" href="https://.../739"></transition> <transition type="credit" code="N" href="https://.../741"></transition> <transition type="credit" code="N" href="https://.../759"></transition > I want to read the last 2 entries and only the "important_id" part. Like: 741 759 -
DRF file download according to extensions
I am a fresh to DRF I am confused how to download files in django rest framework according its extensions. [ { "id": 1, "name": "Tech", "images": [ { "image": "http://localhost:8000/media/path/Overlooking_by_Lance_Asper.jpg", "size": "1425.6 kb", "imagetype": "jpg" }, { "image": "http://localhost:8000/media/path/Scenery_in_Plateau_by_Arto_Marttinen.png", "size": "835.8 kb", "imagetype": "jpg" } ] }] here is list of pictures to download users can add as many as wishes but there are might be the same pics with different ext like jpg, png,ai etc. However, users can download one of them according to file extensions. Honestly speaking, I do not have idea how to do... for the view views.py class ImageViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializers queryset = Category.objects.all() can you give me advice how to do it please? Thanks a lot -
Two generated images in a django page... one never loads
This is a bizarre one. I have a view which creates two png files in the static directory for my django app, then serves a template which shows them. One of the images loads correctly; the other never loads (but the browser is waiting for it). It appears to be random whether it is the first or second image. Things I have verified: - Both images exist in the static directory and look fine from an image browser. - The URL to the images appear to be correct. Here is the view which uses matplotlib to create two images in the static/ directory: nii_image_list = [] for desired_file, desired_tag in desired_image_list: if not os.path.isfile(desired_file): continue desired_name = scan_name + "_" + desired_tag nii_image_list.append((save_nii_preview_to_static_file(desired_file, desired_name), desired_tag)) plt.clf()The # print(nii_image_list) template = loader.get_template('server/scan_deep.html') context = { 'scan': scan, 'nii_image_list': nii_image_list } return HttpResponse(template.render(context, request)) def show_nii(filename): nii = nib.load(filename) dimensions = nii.header.get_data_shape() data = nii.get_dTheata() slice_0 = data[round(dimensions[0] * 0.5), :, :] slice_1 = data[:, round(dimensions[1] * 0.5), :] slice_2 = data[:, :, round(dimensions[2] * 0.5)] show_slices([slice_0, slice_1, slice_2]) def save_nii_preview_to_static_file(nii_filename, name): filename = os.getcwd() + "/static/" + name.replace(' ', '') + ".png" html_static_filename = name.replace(' ', '') + ".png" show_nii(nii_filename) plt.savefig(filename) … -
how to create form with agrument in django
i have a class in my form and its creating a form))) so i whant to pass there id and create a form with that item in my db my form class Order_form(forms.Form): def __init__(self, product_id,*args,**kwargs): self.add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all()) that form doesn't create anything but this form: class Order_form2(forms.Form): add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = 1).add_option.all()) creating exactly what i need but i need to pass there product_id not 1 -
Django: Update Model-Field everytime a Foreign-Key is associated with said model?
Lets suppose we have the following classes: class Cart(models.Model): total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) and class CartItem(models.Model): cart = models.ForeignKey(Cart, related_name='items', on_delete=models.CASCADE) I'd like to update the total everytime a Cart-Item is added to the Cart. When/ How can I call my addItUp() method here? Thought about using a signal like this, but this doesn't trigger: @receiver(post_save, sender=CartItem, weak=False) def post_save_cartItem_receiver(sender, instance, *args, **kwargs): print("inside signal") Here's my very simplified addToCart() method: def add(self, request, product_id, cart_obj): product = get_object_or_404(Product, id=product_id) CartItem.objects.create(cart=cart_obj, ...) cart_obj.save() return True This is my first question here, if i can better my explanation please tell me. -
where could i get this model "base"?
When i enter "python manage.py runserver" i got "django.core.exceptions.ImproperlyConfigured: Cannot import 'base'. Check that 'django_ai.base.apps.BaseConfig.name' is correct." please help to fix this bug. I just download this codes and want it run. from here:https://github.com/math-a3k/django-ai -
Updates doesn't take affect in django orm, Is there something wrong in my code? Thanks in advance
I need to update multiple rows in a url_field in one of my models, Each product_id has its own corresponding new values to be loading. What's wrong with my code? No errors returned I do everything i can but non of them works idlist= ["",""] url = ["https://www.sample.com","https://www.sample2.com"] i = 0 while i < len(item_idlist): Model.objects.filter(item_id=idlist[i].update(product_url=url[i])) i += 1 I expect that every iterations will update my data inside the model -
nginx stopped serving static folder for django app by using WSL
I am using WSL to run nginx to serve django app on "d" partition, yesterday it worked just fine, today stopped working correctly. this is my conf file: upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server xxx.xxx.x.xxx:8000; } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name xxx.xxx.x.xxx; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django static location /static { alias /mnt/d/backend/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } } server and domain name are the same as allowed host in settings. STATIC_ROOT = os.path.join(BASE_DIR,"static")] I am not sure if I am referring to the right path for the static files. as they are in different location, I am little confused about using virtual environment, wsl at the same time. (venv) root@DESKTOP-XXXXXX:/mnt/d/backend the problem is that the server doesn't load the static files. -
Django app only runs on https even after removing SECURE_HSTS_SECONDS setting
I had set SECURE_HSTS_SECONDS=3600 in my settings.py in order to improve my app security. It has been more than 1 hour since I did that and I have removed the line now but still whenever I execute python manage.py runserver with DEBUG = False on http://127.0.0.1:8000/ it gives me Server Error (500). The browser console displays the following message: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. Please Note that my app runs perfectly when: DEBUG = True , in which case the app runs on my localhost as expected. I open my app via the HTTPS URL with DEBUG = False on my Heroku domain. I read the warning in the Django Docs which states: Setting this incorrectly can irreversibly (for some time) break your site. And the the following suggestion from the Docs: When enabling HSTS, it’s a good idea to first use a small value for testing, for example, SECURE_HSTS_SECONDS = 3600 for one hour. Each time …