Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i check whether a Stripe customer already has a specific card before adding a new one in django python
I want to store multiple card on stripe for customer.In this, customer try to add new card on stripe at that time check if this card store or not in django python I use below code to add customer card on stripe card = stripe.Customer.create_source( 'customer_stripe_id' source =request.POST['stripeToken'] ) -
How to chain filters / filtering two object lists in Django?
Need some help in writing a filter query. I have the following Models: class Product: pid name class WishList: user items = models.ManyToManyFields(Product) class Stock: storeid product = models.ForeignKey(Product) aisle segment I need to : Get the Current Logged in USER Get the Products in the User's WishList Search for those Products in the 'Stock' for a Particular StoreID passed as argument and display them along with their Aisle This is what I did: user = request.user wish_list = get_object_or_404(WishList, user=user) list_items = wish_list.items.all() store_stocks = Stock.objects.filter(storeid=(passed StoreID)) list_stocks store_stocks.filter(store_stocks.pid=list_items.pid) But it doesn't work and I need some help. I get the Error as: list_stocks = store_stocks.filter(store_stocks.pid=list_items.pid) | SyntaxError: keyword can't be an expression -
Django allauth social signup with custom user-model + form
I'm trying to use django-allauth package to handle my social login/signup with google oauth2 authentication. What I'm trying to do is after the google authentication pass the new user to a custom signup form with some custom fields to my user model and only after that to save the user model. Everything I try just ignore my custom form and save the user without passing my form. It would be awesome if you can list the necessary elements in the project to make this thing work. Thanks in advance, Itai -
How do I make <a href> link to open in a new tab but in an iFrame part of another template?
I have created a Django web app which throws document recommendation to users based on their search query; the next thing I am trying to achieve is to able to make users open these recommended documents in a new tab but in an iFrame which would part of another template. Also, I just want to use HTML and Python to achieve this result. Till now, I am just able to open the documents in a new tab which is not part of my Django framework <html> <body> {% for document in Documents %} <a href = "{link to the corresponding document on my system}" target = "_blank"> <p><font color = "blue"><b>{{ document }}</b></font></p> </a> {% endfor %} </body> </html> The above code loops through the list of recommended documents generated by model and prints their hyperlinked names on an HTML page. These links just open the document in a new tab but I want them to open in an iFrame on a new template which is part of my Django framework. -
Easiest and fastest way to migrate boto based django-photologue collections on S3 to the newer boto3?
There is a bug (https://github.com/boto/boto/issues/3837) in boto that prevents it from functioning properly with S3 in production (althought it does work in development). How would one go about installing a forked version of boto to the existing project or perhaps migrating the populated storages to boto3? Is it even possible without reuploadin/retaggint my entire collection? and even so, does django-photologue work with boto3? I'm linking to this code from my settings.py, as described in the tutorials for django-photologue s3 storage: # S3Boto storage settings for photologue example project. import os DEFAULT_FILE_STORAGE = 'example_storages.s3utils.MediaS3BotoStorage' STATICFILES_STORAGE = 'example_storages.s3utils.StaticS3BotoStorage' AWS_S3_HOST = 's3-us-west-2.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } try: # If you want to test the example_project with S3, you'll have to configure the # environment variables as specified below. # (Secret keys are stored in environment variables for security - you don't want to # accidentally commit and push them to a public repository). AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] except KeyError: raise KeyError('Need to define AWS environment variables: ' 'AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_STORAGE_BUCKET_NAME') # Default Django Storage API behavior - don't overwrite files with same name AWS_S3_FILE_OVERWRITE = False MEDIA_ROOT = … -
Django + Python failed connecting to PostgreSQL server in a local machine in same network
I have a PostgreSQL running in a linux machine inside my local network. The IP address of this machine in my local network is 192.168.0.115. I am able to connect to this server using the Valentina Studio client on my Macbook Pro with username postgres and password postgres, and IP address 192.168.0.115 (address of the linux machine running the PostgreSQL server in my local network). Also in my Macbook Pro, I have a Django application setup to connect to the PostgreSQL server using the same IP address, username and password as the Valentina Studio, but when I run python3.7 manage.py migrate, I get an error message saying it could not connect to server: When I change my Django application database configuration to use SQLite, the migration runs well and everything works well. I disabled the firewall of the linux machine running the PostgreSQL server, just to make sure. (I don't think this is the problem though, because my Macbook Pro is able to connect to that server using the Valentina Studio client). If I run the same Django application INSIDE THE POSTGRESQL SERVER LINUX MACHINE, using 127.0.0.1 IP address, it works. If I change the IP address to 192.168.0.115 (IP … -
I can't submit the form even if it is valid
I have used CreateView for a form, but the form is not being submitted even when it is valid. It just redirects to the same page again.I am using the form_id for from fields, and it even submitted once or twice but now it is just not working. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) views.py class centre(CreateView): fields = ('name','address','contact','phone',) model = Centre success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): form.save() return super(centre, self).form_valid(form) template : <form method="POST"> {% csrf_token %} <div class="col col-md-12"> <div class="fieldWrapper" > {{ form.name.errors }} <div class="form-group col col-md-3"> <label for="{{form.name.id_for_label}">Centre Name</label> <input type="text" placeholder="Centre Name" name="name" maxlength="250" id="id_name" style="box-sizing: border-box; width:500px;"> </div> </div> <div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%"> <label for="{{form.address.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Centre&nbsp;Address</label> <input type="text" placeholder="Centre Address" name="address" maxlength="250" id="id_address" style="width:500px; margin-left:200px;"> </div> </div> <br> <br><br><br> <div class="col col-md-12"> <div class="form-group col col-md-3" style="float:right; margin-top=-80px;"> <label for="{{form.contact.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">Contact&nbsp;Person</label> <input type="text" placeholder="Contact Person" name="address" maxlength="250" id="id_contact" style="width:500px; margin-left:200px;"> </div> {{ user_form.non_field_errors }} <div class="fieldWrapper" > <div class="form-group col col-md-3" > <label for="{{form.phone.id_for_label}" style="white-space:nowrap;">Contact&nbsp;Number</label> <input type="text" name="phone" … -
django-zappa: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory
When trying to deploy a Django project using django-zappa, I get the following error in the zappa tail output: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory I've made sure to include the psycopg2 module in the requirements file: psycopg2==2.8.3 It's installed in the virtual environment that's active while running the zappa deploy command. I'm running on Linux and had to install libpq-dev via apt before even being able to pip install psycopg2 as I received an error before, saying that libpq was missing on the system (similar to the above error, I guess). How can I overcome this error? Thanks! -
"Is there any repository or documentation with instructions to run docker created by django oscar?"
I am working with Django oscar docker and in the meantime found that Django oscar sandbox not installing as expected. So I want to get rid of all hassles and want to run it in docker. When I went through Django oscar GitHub repository and their docker hub profile I found no instructions and guideline to run it. I have also created an issue to their GitHub profile and they suggested me to ask questions on StackOverflow or google group. For a faster response, I am asking help from this community. Hope you guys will come up. This is my github issue link https://github.com/django-oscar/django-oscar/issues/3051 -
How to automatically substitute a variable in the admin page at Django 1.11?
There is a City model. It has a name field. I need to somehow substitute this variable in the admin page in the text field at another models. Suppose need to write the phrase "Your location is Paris", but it is necessary that the name of the city was substituted by itself (since there are many cities, and prescribing for each is not an option at all). That is, there must be something like "Your location - {City.name}" - that is, a certain city is pulled out of the database and substituted into this line. Writing a prepared phrase in templates is not an option. I need to do this through the admin panel. Using selects is also not an option, since the number of variables, their location and phrases are not known in advance. For example, the phrase "The capital of France - Paris" (The capital of {Country.name} - {City.name}). I understand, need to create a shortcode_name field and somehow process it in the view? I'm use Django 1.11 -
Unknown interpreted text role "setting" with Django docstring and Sphinx
I'm documenting a Djagno 2.2 application. The Django documentation states linking to the settings as Add :mod:`django.contrib.auth` to your :setting:`INSTALLED_APPS`... In my documentation, The statement is The length is defined in the :setting:`URL_ID_LENGTH` When generating the documentation using Sphinx make html Gives WARNING :docstring of app.models.Class.function:4: WARNING: Unknown interpreted text role "setting". I have sphinx.ext.intersphinx added to the conf.py of Sphinx. -
How can I filter related field in django?
Say I have the model User which has a many-to-many relation with the model Company; and the model UserType, which is connected to both User and Company. Like this: class User(models.Model): name = models.TextField() class Company(models.Model): name = models.TextField() users = models.ManyToManyField(User, related_name="companies") class UserType(models.Model): name = models.TextField() company = models.ForeignKey(Company, related_name="user_types") users = models.ManyToManyField(User, related_name="user_types") I wanna find all Users in a Company, which is simple enough: User.objects.filter(companies=some_company). However, I also wanna filter the user_types field on the returned users objects, so that only UserType objects connected to the given Company is returned. To explain it with code, this should return true: def check_user_types(users, company): for user in users: for user_type in user.user_types: if user_type.company != company: return false return true How would I do this? -
Edit a cell in the table save to the django model
I have a table of employees. I am loading data using $http and using ng-repeat to print it on the webpage. I want to edit each row content. HTML: tbody ng-repeat="list in data" > <tr ng-hide="edit" ng-click="edit=true"> {% verbatim %} <td> {{$index + 1}}</td> <td>{{ list.associate_nbr }}</td> <td>{{ list.per }}%</td> <td>{{ list.count }}</td> <td>{{ list.sample_per }}%</td> <td>{{ list.sample}}</td> <td><input type="text" value="{{ list.focused }}"></td> <td><input type="text" value="{{ list.random_field }}"></td> </tr> {% endverbatim %} MAIN.JS (function(){ 'use strict'; angular.module('sampling.demo',[]) .controller('SamplingController', ['$scope','$http',SamplingController]); function SamplingController($scope,$http) { $scope.data = []; $http.get('/sample/').then(function(response){ $scope.data = response.data; }); } }()); I want to edit the last two fields when user clicks on it. -
Django media files not loading
I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below. models.py from django.contrib.auth.models import User from django.db import models from django.contrib.auth.models import AbstractUser class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='media/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' profile.html <!DOCTYPE html> {% extends 'base2.html' %} {% load crispy_forms_tags %} {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>profile</title> </head> {% block content %} <body style="margin-left: 300px"> <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png"> </div> </div> </body> {% endblock %} </html> settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' print(MEDIA_ROOT) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] urls.py(the main urls.py, not of app users) from django.contrib import admin from django.urls import path, include from users.views import profile from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls'), name='index'), path('profile/', profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Django: bulk_destroy returns "400: Bad request"
I have a Django viewset MyModelViewset that extends MultipleDBModelViewSet (from the base viewsets). The base viewset contains the following method that is not overwritten in MyModelViewset: def bulk_destroy(self, request, *args, **kwargs): ids = json.loads(request.query_params.get("ids")) if not ids: return super().destroy(request, *args, pk=kwargs.pop("pk"), **kwargs) else: return super().bulk_destroy(request, *args, **kwargs) I am assuming that this method means I can pass a parameter called ids and all of the objects with those ids will be deleted? I've tried sending a delete request to the associated URL: v1/mymodel?ids=["4cea187e-56af-439c-96a7-e001d85c5000","3d7bd2ac-bc27-4a1b-acfd-9b651852114e"] -> this returns a 200 response and behaves like a GET request v1/mymodel?ids=["4cea187e-56af-439c-96a7-e001d85c5000","3d7bd2ac-bc27-4a1b-acfd-9b651852114e"]/ -> this returns a 400 response "Bad request" MyModels with these ids do exist in my DB. What am I doing wrong? -
django rest framework serialize a dictionary without create a model
My data is like this, I want to serialize them without creating model for them. [ {'form': 1, 'count': 1}, {'form': 2, 'count': 3} ] serilize to [ {'form': 'my form name 1', 'count': 1}, {'form': 'my form name 2', 'count': 3} ] I want to serialize it with serializer, get form name form model by pk. class EavForm(models.Model): name = models.CharField(max_length=300) order = models.IntegerField(default=1) # serializer class CustomSerializer(serializers.Serializer): form = serializers.PrimaryKeyRelatedField(queryset=EavForm.objects.all()) count = serializers.IntegerField() Some error like 'int' object has no attribute 'pk' -
Perform CRUD operations on product class?
I'm a newbie to Django-oscar and I'm trying to develop a simple CRUD operation on Product. I've forked the catalogue app and created a views.py file I fired the query Product.objects.create(title='Hello') and a product does get created with the following error: AttributeError: 'NoneType' object has no attribute 'attributes' product_title = 'MyPhone' upc=987654321 product_class = ProductClass.objects.get_or_create(name='Phone') def createProduct(request): line1 product.name = product_title product.product_class = product_class product.upc=upc product.save() When I put product=Product() in line1 I get the following error: Cannot assign "(, False)": "Product.product_class" must be a "ProductClass" instance. When I put product = Product.objects.create(upc=upc) I get the following error : NoneType' object has no attribute 'attributes' Anyone guide me on how to write a simple create operation? -
Template not rendered when request made from java script to view function using ajax
The django template calls a java-script function on click of a submit button.This java-script function redirects the request to a django view function where a template is to be rendered. The java-script function is being called but the the django view function doesn't render the template even though both the functions are found to be called when debugged. Django template: <button type="submit" id ="b" name="b" onclick="edit(document.myform.checks,5)" formmethod="get" class="btn btn-danger" disabled>&nbsp &#9998; &nbsp</button> Django view function: def edit(request,i,unique_key): add=False template ='pms_app/form.html' form=Myform(instance=(Mymodel.objects.get(id=unique_key))) if request.method=="POST": form=Myform(request.POST,instance=( Mymodel.objects.get(id=unique_key))) if form.is_valid(): form.save() return redirect ('pms_app:display',i=i) else: print(form.errors) return render(request, template, context={'form':form,'unique_key':unique_key}) Javascript function: function edit(chk, i) { var len = 0; var x=0; for (j = 0; j < chk.length; j++) { if (chk[j].checked == true) { len++; if (len > 1) { break; } x = chk[j].value; } } var edit_url = 'edit/' + i + '/' + x; if (len > 1) { alert("Please select only one record to edit!") } else { alert(edit_url); $.ajaxSetup({ data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ url: edit_url, type: "GET", success: function () { alert("requested access complete"); }, error: function () { alert("requested access failed"); } }) } } Any idea/help on why the … -
How to convert user selected date time to milliseconds
How to convert user selected date time to milliseconds. I am rendering date time from HTML page and stored into datetime_obj variable. How to convert variable date to milliseconds.Help me to do that. views.py def datetime1(request): if request.method == 'POST': form = DatetimeForm(request.POST) if form.is_valid(): datetime_obj = request.POST.get('datetime') dt = datetime(datetime_obj) milliseconds = int(round(dt.timestamp() * 1000)) print(milliseconds) return render(request, 'datetime.html', {}) return render(request, 'datetime.html', {}) datetime.html <form action="#" method="post"> {% csrf_token %} <input type="datetime-local" name="datetime" > <button type="submit">Submit</button> </form> urls.py urlpatterns = [ path('datetime/', views.datetime1, name="datetime1"), ] -
ProgrammingError at / relation "Django-Personal-Website_project" does not exist LINE 1: ..."Django-Personal-Website_project"
So for heroku i couldn't use dbsqlite3 as my database, so I tried switching it to Postgre and I encountered a problem which I also received from deploying my Personal Website on Heroku. I have had so much trouble and have no idea how to fix it. I am trying to add a projects panel to my Website but whenever I add this HTML to the site I get an relation does not exist error. I believe it is because I switched to PostgreSQL but dont know why the problem is what it is. Someone please help!! DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django', 'USER': 'chrisrosales', 'PASSWORD': 'notgonnashowlol', 'HOST': 'localhost', 'PORT': '5432', } } The problem is this portfolio... <section id="portfolio" class="pfblock"> <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <div class="pfblock-header wow fadeInUp"> <h2 class="pfblock-title">My works</h2> <div class="pfblock-line"></div> <div class="pfblock-subtitle"> </div> </div> </div> </div><!-- .row --> <div class="row"> {% for project in list_projects|slice:":2" %} <div class="card col-xs-12 col-sm-5 col-md-5"> <div class="grid wow zoomIn"> <figure class="effect-bubba"><a href="{{ project.url }}" target="_blank"> {% with 'Django-Personal-Website/images/'|add:project.img_name as image_static %} <img class="card-img-top" src="{% static image_static %}"></a> {% endwith %} </figure> <div class="card-block"> <h2 class="card-title">{{ project.title }}</h2> <p class="card-text">{{ project.description }}</p> <div class="tools"> {% … -
How can i put values in a modelformset field?
I have a modelformset which takes attendance of students. The models.py looks like: class Attendance(models.Model): Student = models.CharField(max_length=100, blank=False) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' And my views.py: ef academics(request): if request.user.is_staff: formset = modelformset_factory(Attendance, fields=('__all__'), extra=60) if request.method == "POST": form=formset(request.POST) form.save() form = formset(queryset=Attendance.objects.none()) return render(request, 'console/academics.html',{'form':form}) else: context = { 'attends': Attendance.objects.all().exclude(Date=timezone.now()), 'todays': Attendance.objects.filter(Date=timezone.now())[:8] } return render(request, 'student/academics.html',context) How can I set the values of Students field values to the names of the User.objects.filter(profile__Year='SY',profile__Department='CSE'), which contains the names of the students of a department and a year. -
installed django-redis in python virtualenv, redis-cli command not found
I just install redis-cli using pip in python virtualenv,but when I type redis-cli, shows me redis-cli command not found. I'm pretty much sure redis-cli has been installed sucessfully. need your help thx in advance -
django redirects not working in electronjs
I am creating an account management app for my father's company. I integrated Django with electron like this=> mainWindow.loadURL('http://localhost:8000') And in package.json. I did this in scripts => "start": "start python manage.py runserver && start electron ." In my createView, DetailView, DeleteView. I added this => success_url = reverse_lazy('home') If i open this in chrome browser it works absolutely fine no worries. But if i do this in electron. It show this msg => Page not found (404) Request Method: GET Request URL: http://localhost:8000/delete/11 Raised by: accounts.views.EntryDeleteView plz help! -
ModuleNotFoundError psycopg2 when deploying in heroku even though psycopg2 is installed
I migrated my website from sqlite3 to postgresql. I'm deploying my website in heroku but this error came up when I'm executing command push heroku master -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.3 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.7.2 -----> Installing pip -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) 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 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
in Django where we call function or class
def display(request): return render(request, 'base.html') I have curiosity about where we call this is working why not need to call the function