Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dajngo OneToMany relationship using ForeignKey queryset
I use in model in django framework OneToMany relationship using ForeignKey. that I need now and I don't know how to do it is to create a queryset to take for any id in table Order how ids have as fk key in table Line,thst I want to show in html page. for example o want to show in html template something like this: id_order | id_line 1 | 2 2 | 3,4,8 10 | 7 that confused me because I think we need to reverse foreign key here the model : django.db import models class Order(models.Model): order_name = models.CharField(max_length=254) class Line(models.Model): f= models.ForeignKey(Order, blank=True, null=True,verbose_name='order') name = models.CharField(max_length=254) def __unicode__(self): return self.name any idea how to do that ? -
How to redirect the URL without using Protocol(http, https or ftp) in Python?
I am trying to convert PHP code to Python for the payment gateway integration. In PHP, there is a code "header("Location: " . $url);" and the URL is "gatewaysdk://asdzxc?summaryStatus=SUCCESSFUL&3DSecureId=XXXXXX" (without protocol - http, https or ftp). In PHP, the code is working fine. Is there any way to do it in Python. I have tried using redirect and HttpResponseRedirect - return redirect(redirect_url, allow_redirects=True). The error I got was "django.core.exceptions.DisallowedRedirect: Unsafe redirect to URL with protocol 'gatewaysdk'". After debugging the error I found HttpResponseRedirect supports only with protocol (http, https or ftp). -
How to Serve static Media Files in Django?
I'm beginner with Web Server Apache. I want to ask your guys how to Serve Media Files in Django. I read this: https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/#serving-files This example sets up Django at the site root, but serves robots.txt, favicon.ico, and anything in the /static/ and /media/ URL space as a static file. All other URLs will be served using mod_wsgi: Alias /robots.txt /path/to/mysite.com/static/robots.txt Alias /favicon.ico /path/to/mysite.com/static/favicon.ico Alias /media/ /path/to/mysite.com/media/ Alias /static/ /path/to/mysite.com/static/ <Directory /path/to/mysite.com/static> Require all granted </Directory> <Directory /path/to/mysite.com/media> Require all granted </Directory> WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py <Directory /path/to/mysite.com/mysite> <Files wsgi.py> Require all granted </Files> </Directory> If you are using a version of Apache older than 2.4, replace Require all granted with Allow from all and also add the line Order deny,allow above it. I ask Web Server supporter, they said my server have supported mode mod_wsgi already and they said to me that I can config it in .htaccess. But I really have no knowledge about this. Please help me rewrite URL: Rewrite URL mydomain.com/served/ to folder with path /home/mydomain.com/public_html/media. All files in /home/mydomain.com/public_html/media/filename.jpg will access with mydomain.com/served/ -
how to call pdf dynamically and render in pdf.js with django
I want help in using pdf.js with django. when i fetch pdf from server using post and add url to my pdfview.js which generally comes with pdf.js files, it throws exception Uncaught (in promise) Typeerror: Cannot read property 'scrollLeft' of null what i did is just pass a variable in line 4352 of pdfview.js and before calling js i add path to variable , it work fine before adding to project in which i am using djago framework but after it create an exception as shown above. -
DISTINCT ON fields is not supported by this database backend
I am using distinct to get the distinct latest values but it is giving me error - DISTINCT ON fields is not supported by this database backend views.py class ReportView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/clock/report.html' def get_context_data(self, **kwargs): context = super(ReportView, self).get_context_data(**kwargs) context['reports'] = TimesheetEntry.objects.filter( timesheet_jobs__job_company = self.request.user.userprofile.user_company, ).distinct('timesheet_users') return context Basically i want to query on TimesheetEntry model where there will be lots of entry of user which is a foreign key in User in-built model.\ So i want to query with distinct user so that latest entry of the user will be displayed. It is very important for me to get lastest entry of user Models.py class TimesheetEntry(models.Model): timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs') timesheet_clock_in_date = models.DateField() timesheet_clock_in_time = models.TimeField() -
How to use Admin Lte theme in python-django (userside-frontend side)?
I am developing website for crud operation and i want to set it in admin lte theme and also want theme set in front end side ,i already install admin lte library but its only provide base template, i cant use require component. -
ESP8266 connection with a locally hosted server
I have a Django server hosted locally. I ran my server using python manage.py runserver 0.0.0.0:8000 so that it is accessible from any devices that are connected to my WiFi. Any computers or smartphones in my network can simply go to my computer's IP Address 192.168.0.0:8000 via their browser to see my Django page. I would like to use an ESP8266 module to send a GET request to the locally hosted Django page. The following AT Commands are used. AT+CWMODE=1 AT+CWJAP="SSID","PASS" AT+CIPMUX=1 AT+CIPSTART=0,"TCP","192.168.0.0",80 <--Problem arise here, hence I could not move on with my GET request All but the last command was executed successfully. When I run the last AT Command to establish a TCP connection with my local server, I get an error. ERROR 0,CLOSED Currently, I'm still not super proficient with networks and backend. Any long explanation and/or answers will be well appreciated! -
How to embed csv in iframe if excel did not have embed function-Django
I wish to embed CSV/Excel in Iframe, which allow user to edit and save the content, but in my server, the embed function have being turn off, anyone can share me ideas? -
How to get data (and not log in) from a person's google account, using Google OAUTH 2.0 in Django?
I've been working on a social networking website and want to implement google login. However, the login will create a user object, while my website stores data in 'Member' objects which are one-to-one linked with corresponding User objects. What I want to do is to just fetch a person's information from google API and then use that information to create a corresponding User and a Member object, and then log in as that user. How can I do this? Also, is there a better way to handle this? models.py- from django.db import models from django.contrib.auth.models import User from django.core import validators from django.conf import settings import re class Member(models.Model): username = models.CharField(max_length=40) name = models.CharField(max_length=40) user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE) number_of_followers = models.IntegerField(default=0) bio = models.TextField(blank=True) follows = models.ManyToManyField("self", related_name='followers', symmetrical=False, blank=True) subscribed_to = models.ManyToManyField("self", related_name='subscriber', symmetrical=False, blank=True) profile_picture = models.ImageField(upload_to='propic', blank=True) email = models.EmailField(max_length=60, blank=True) def __str__(self): return self.username -
Django-graphene add data with a foreign key in that model?
Unable to add data to table which contains foreign key init,when i run the query to add data error is through out that category_id(foreign key) cannot be null.I tried to post the code what i have but its throwing errors so please the image links for source code.enter image description here models schema -
how to schedule mass emails for about 30000 users according to user timezones
How to schedule bulk emails for about 30,000 people across the world using django. The emails should be sent to users as per their respective timezones. I am using Django==2.0 on RHEL 7. -
Django | Static files served by nginx not used by Client
I have a django app, with the following settings for static files: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] STATIC_ROOT = '/opt/static/' I am running django using the follwoing gunicorn command: gunicorn evee.wsgi -b 0.0.0.0:8000. I have configured nginx to serve the static files and ssl using the following conf: server { keepalive_timeout 5; listen 443 ssl; server_name api.home.com; client_max_body_size 4G; error_page 500 502 503 504 /500.html; # path for static files root /opt; location / { # checks for static file, if not found proxy to app try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header Host $host; proxy_set_header X-Forwarded-Ssl off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Port 80; proxy_set_header X-Forwarded-Proto $scheme; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; proxy_pass http://evee:8000; } } Interesting part is that I am able to see the CSS in the client. For example, the request to https://secapi.ril.com/static/admin/css/base.css is successful and returns a 200 response. I can view all the static files at the URL mentioned, but django does not seem to use them. Have tried changing clients as well as private mode. Am I doing something terribly wrong? … -
OAuth2 from Android to my Django API requires to go to /accounts/login
So I was trying to implement a feature on my android app where users can register and login to the app. I made it where the user credentials are stored to an external and can be validated with the Django REST API I made. So before I can let my app access that API page, I have to make sure it goes with OAuth2 rules. However, it requires me to login to an /accounts/login page. Do I need to make that page or can I change the url if don't want that path or maybe not login as admin at all? It keeps me wanting to login before I can authorize my app. login.java public class Login extends AppCompatActivity { Button LoginButton, RegButton; EditText uUserName, uPassWord; WSAdapter.SendAPIRequests AuthHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn); LoginButton = (Button) findViewById(R.id.LoginButton); RegButton = (Button) findViewById(R.id.LoginRegister); uUserName = (EditText) findViewById(R.id.LoginUserBox); uPassWord = (EditText) findViewById(R.id.LoginPassBox); //AuthHelper = new WSAdapter().new SendDeviceDetails(); // Moves user to the main page after validation LoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // gets the username and password from the EditText String strUserName = uUserName.getText().toString(); String strPassWord = uPassWord.getText().toString(); //startActivity(new Intent(Login.this, Posts.class)); // … -
Django AllAuth: Hiding Error Fields in Form
I do not like the way the AllAuth form error field message is showing up when a user logs in with an incorrect password on my site. To fix this, I added a new error field to be outside the login form. There are now two error field messages that appear when a bad form post occurs. How do I go about hiding the original error message within the AllAuth form. In the code below I am trying to append the error field and add display: none; but it is not working HTML page <form class="login" method="POST" action="{% url 'account_login' %}" style="list-style-type: none;"> {% csrf_token %} {{ form|crispy }} {% for field in form %} {% for field in field.errors %} {% render_field field style+="display: none;" %} {% endfor %} {% endfor %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="primaryAction btn btn-primary shadow mt-2" style="width: 100%;" type="submit">{% trans "Sign In" %}</button> </form> -
Django - Defining ?next page from Admin
Is it possible to direct a user back to the previous page coming from the admin dashboard? I have an "edit" button, and since the "users" who will be able to edit data are savvy enough, I'd rather just have this direct to a change page in admin. Here is my link: <td><a href="/admin/inv/lifesafety/{{life.pk}}/change/?next=/stores/{{store.pk}}" target="_blank"><i class="icon ion-md-create"></i></a></td> Use of ?next= from admin doesn't seem to work. For now I'm just having it opened in a different tab, but I'd like to at least know if there is a direct restriction, or if there's more to it when interacting with admin. -
Dynamic Models Django 2019
Okay, I know there are threads all over the place from outdated ways to make dynamic django models meaning, they are altered by a user at runtime of the application. I am not finding a solid solution outside of using custom SQL to make dynamic tables in my project, so I am hoping there is a way to dynamically create a model during runtime, so it can be used in Django's ORM. So far in the last few weeks of checking, this seems either overly complicated or impossible for my situation For example and in brevity, I have a unit_declaration model, which holds column names. I then take those column names of columns and currently create a custom SQL query to build a unit table based on those columns. I want to be able to not use custom SQL to generate the creation of client tables at runtime, how is this possible (and I need a real example because nothing is making sense to me elsewhere)? I can certainly provide code as to what I am doing so far, and I completely unvderstand this is the point of SO, but I am hitting a block and need a suggestion and … -
I can't configure my gunicorn service for my project
I am new to deployment, trying to learn this deployment with gunicorn and nginx on ec2 AWS Amazon. I have a django web app which i want to deploy. Here's my gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/toDo_list ExecStart=/home/ubuntu/toDo_list/MyDjangoEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/toDo_list/toDo_list.sock toDo_list.wsgi:application [Install] WantedBy=multi-user.target After that when the status giving me an error. Here's the error I am getting. ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2019-01-18 01:38:54 UTC; 14min ago Main PID: 11683 (code=exited, status=200/CHDIR) Jan 18 01:38:54 ip-172-xx-xx-xxx systemd[1]: Started gunicorn daemon. Jan 18 01:38:54 ip-172-xx-xx-xxx systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jan 18 01:38:54 ip-172-xx-xx-xxx systemd[1]: gunicorn.service: Unit entered failed state. Jan 18 01:38:54 ip-172-xx-xx-xxx systemd[1]: gunicorn.service: Failed with result 'exit-code'. I know I probably couldn't configure the gunicorn service file properly. Could you please help me figure out where did I go wrong and what would be the possible solution. Thanks -
how to use a queryset expression in a then clause in conditional annotation in Django
i have two models, one of organizations and one with the membership and rol of an user in the organization class Organization(models.Model): name = models.CharField(blank=False,null=False,max_length=100, unique=True) class Member(models.Model): user_request = models.ForeignKey('accounts.User',on_delete=models.CASCADE,related_name="member_user_request") user_second = models.ForeignKey('accounts.User',on_delete=models.CASCADE,blank=True,null=True, related_name="member_user_second") role = models.ForeignKey(RoleOrganization,on_delete=models.CASCADE, verbose_name=_('Rol')) status = models.ForeignKey(Status,on_delete=models.CASCADE, verbose_name=_('Status')) organization = models.ForeignKey(Organization,on_delete=models.CASCADE, verbose_name=_('Organization')) and im trying to use a annotate with case clause where i want to get the role of an user in the organization with this expression: my_organizations = Member.objects.filter( Q(user_request_id=self.request.user.id, status__name="accepted", type_request__name="request") | Q(user_second_id=self.request.user.id, status__name="accepted", type_request__name="invitation") ) Organization.objects.annotate( rol=Case( When(id__in=list(my_organizations.values_list('organization_id', flat=True)), then=Value(my_organizations.get(organization_id=F('id')).role.name)), default=None, output_field=CharField() ) ) the problem here is that the then expression doesn't get the id of the object in the main queryset, if i return in the then just the F('id') the expression gets the value of the id in the main queryset, but i can use a filter or any queryset expression with some values of the main object. its there a way to accomplish this. PS: im just putting part of the code here for cleanliness, but if you need to know more please let me know -
How to change header of bootstrap4 django-tables2
I defined the table as below class MyTable(tables.Table): class Meta: template_name = "django_tables2/bootstrap4.html" model = Mymodel attrs = {"class": "table table-hover"} I want to change the table head to make appear light or dark gray, like this. -
Intermittently Getting : Could not load Boto3's S3 bindings
In AWS Code Pipeline intermittently getting "Could not load Boto3's S3 bindings" around the integration testing stage clicking retry a couple of times seems to resolve this however it is starting to get more frequent now using boto3==1.7.5 botocore==1.8.48 Django==2.0.10 django-storages==1.6.5 any suggestions from anyone else who may have run into this issue ? More details below File "/code/web/authutils.py", line 10, in get_storage from web.storage import UserUploadsEncryptedStorage File "/code/web/storage.py", line 1, in from storages.backends.s3boto3 import S3Boto3Storage, SpooledTemporaryFile File "/usr/local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 27, in raise ImproperlyConfigured("Could not load Boto3's S3 bindings.\n" django.core.exceptions.ImproperlyConfigured: Could not load Boto3's S3 bindings. -
django permissions to restrict view based on groups
I currently have an order management app. But the team I am creating this for has two departments the office and the factory who'll be using the same app but with each team having access to what they need. I'm confused if I should create two different apps to login into the same system (but that would redundant code) or if there's any other way I can set permissions. I have tried using the django admin permissions and they don't seem to work. -
How do I use npm packages and ES6 features with Django?
I am currently building out the front-end of a Django app and I want to use the official material design components. However, I am running into trouble finding ways to integrate this; I want to be able to import the npm packages directly into javascript files and/or Django templates. Does anyone know how to do this? -
issue designing a template handling inlineformset_factory manually in django
My inlineformset_factory was working dandily until I decided to mess with the layout. I've created an image based form that works off the already uploaded images (and a default image in case the spaces are not occupied) instead of the somewhat boring, grey input="file" button, and I get the error: "['ManagementForm data is missing or has been tampered with']" whenever I try to either upload a new image or delete an old one, eg. it somehow broke as a result of tampering with the HTML..? In my template I have: <form method="POST" enctype="multipart/form-data"> {% for item in formset %} {% csrf_token %}½ <div class="media context"> <input type="file" id="formolator" accept="image/*" style="visibility:hidden;" /> <label for="formolator"> {% if item.extra_img.value != 'media/default.jpg' %} <img src="/media/{{ item.extra_img.value }}" class="img-box" /> delete: {{ item.DELETE }} {% else %} <img src="/media/default.jpg" class="img-box" /> {% endif %} </label> </div> {% endfor %} <div class="form-group"> <button class="btn btn-secondary ml-2 mb-2" type="submit">update</button> </div> </form> Bonus conundrum: Aside from that, I've been trying to make the forms which show up in the template (in views I've set a limit at max_num=9) do a float:left; in a few different ways. Wrapping another div around the whole shebang like I've done in the … -
deploying django app with heroku: "remote:! No such app"
I'm trying to deploy my django app with Heroku. It creates the project when I do heroku create command, but it says 'no such app found' when i try to push to heroku. I have all the required files such as Procfile and requirements.txt Please help this newb Thank you -
what enctype do I choose to keep option value as an object and keep the support type app/json?
I am trying to send the value of an option as an object in a POST form, So I am using enctype='text/plain' to get an object instead of string. At the same time the supported media type is 'application/json' Here the template: <form class="" action="/api/meal_planner/" method="post" enctype='text/plain'> {% csrf_token %} <h3> Starters </h3> {% for food in foods %} {% if food.type == 'starter' %} <div id="f{{ forloop.counter }}"> <h3> {{ food.display_name }} </h3> <div class="details"> <ul> <li>calories: {{food.cal}}</li> <li>carbs: {{food.carbs}}</li> <li>carbs: {{food.carbs}}</li> <li>fibers: {{food.fibers}}</li> <li>proteins: {{food.proteins}}</li> <li>lipids: {{food.lipids}}</li> </ul> </div> <div class="image"> <img src="{{food.imgUrl}}"> </div> </div> {% endif %} {% endfor %} <div class="select"> <select name='starter'> {% for food in foods %} {% if food.type == 'starter' %} <option value='{"display_name":"{{food.display_name}}","cal":{{food.cal}}}'>{{ food.display_name }} </option> {% endif %} {% endfor %} </select> </div> Option as you see is : <option value='{"display_name":"{{food.display_name}}","cal":{{food.cal}}}'>{{ food.display_name }} </option> So I can have the body like this : Body of POST And this the Django API : @api_view(["POST"]) def FoodResponse(foodData): try: #defining variables calMoy=500 percentage=0.1 calSum=0 donnee = json.loads(json.dumps(foodData.data)) print (donnee) calSum= calSum + donnee["starter"]["cal"]+ donnee["dish"]["cal"]+ donnee["desert"]["cal"] if ( (calSum < calMoy*(1-percentage)) or (calSum > calMoy*(1+percentage)) ): return JsonResponse({ "status": "KO", "food": donnee }) else: return …