Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'google' in GCP app
I have a Django app that I am trying to deploy to GCP. The app works perfectly fine when I run it locally, and it deploys with no issue to GCP (via gcloud app deploy). When I open the webpage, I get this error "502 Bad Gateway 502 nginx" due to "ModuleNotFoundError: No module named 'google'". I haven't been able to find how to properly import google into my GCP app. More details below, any help is appreciated. Here is the parsed stack trace (via GCP debugger): ModuleNotFoundError: No module named 'google' at <module> (/srv/socha_web/settings.py:14) at _call_with_frames_removed (<frozen importlib._bootstrap>:219) at exec_module (<frozen importlib._bootstrap_external>:728) at _load_unlocked (<frozen importlib._bootstrap>:677) at _find_and_load_unlocked (<frozen importlib._bootstrap>:967) at _find_and_load (<frozen importlib._bootstrap>:983) at _gcd_import (<frozen importlib._bootstrap>:1006) at import_module (/opt/python3.7/lib/python3.7/importlib/__init__.py:127) at __init__ (/env/lib/python3.7/site-packages/django/conf/__init__.py:142) at _setup (/env/lib/python3.7/site-packages/django/conf/__init__.py:63) at __getattr__ (/env/lib/python3.7/site-packages/django/conf/__init__.py:76) at setup (/env/lib/python3.7/site-packages/django/__init__.py:19) at _call_with_frames_removed (<frozen importlib._bootstrap>:219) at exec_module (<frozen importlib._bootstrap_external>:728) at _load_unlocked (<frozen importlib._bootstrap>:677) at _find_and_load_unlocked (<frozen importlib._bootstrap>:967) at _find_and_load (<frozen importlib._bootstrap>:983) at _gcd_import (<frozen importlib._bootstrap>:1006) at import_module (/opt/python3.7/lib/python3.7/importlib/__init__.py:127) at import_app (/env/lib/python3.7/site-packages/gunicorn/util.py:358) at load_wsgiapp (/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py:39) at load (/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py:49) at wsgi (/env/lib/python3.7/site-packages/gunicorn/app/base.py:67) at load_wsgi (/env/lib/python3.7/site-packages/gunicorn/workers/base.py:144) at init_process (/env/lib/python3.7/site-packages/gunicorn/workers/base.py:119) at spawn_worker (/env/lib/python3.7/site-packages/gunicorn/arbiter.py:583) And here is my settings.py file (I wiped any secret keys): import os from google.oauth2 import service_account # … -
How to upload a big size folder to GCS using angular 9?
I have to upload a huge size of the folder(approx 150GB ) to GCS. I am using Angular 9 as front-end and Django for the backend. Please tell me the best approach for this. The approach in my mind is: Take a token from the back-end and upload the file one by one(using GCS API). Upload all the files one-by-one in the Django server than upload it to GCS. Zip the folder and upload it to Django and then extract and upload it to GCS(but I have no idea,how to upload a big zip file using angular). Please suggest to me what can I do and how? -
Onchange missing AJAX validation with django
I've been trying to validate the title field using AJAX.(If the title exist in the table display the error "Title already exists"). I looked at many examples, but some are old and do not work, while others I do not understand.Below is the code, please help with the implementation. Here is my code:- forms.py class postForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'description' ) widgets = { 'title': forms.TextInput(attrs={'id': 'title', 'required': True,}), 'description': forms.TextInput(attrs={'id': 'description', 'required': True}) } views.py def validate_title(request): title = request.GET.get('title', None) data = { 'is_taken': Post.objects.filter(title=title).exists() } return JsonResponse(data) class postClass(CreateView): template_name = 'create_post.html' form_class = postForm def create_post(self, request): posts = Post.objects.all() response_data = {} form = postForm() if request.POST.get('action') == 'post': title = request.POST.get('title') description = request.POST.get('description') response_data['title'] = title response_data['description'] = description Post.objects.create( title=title, description=description, ) return JsonResponse(response_data) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('create/', postClass.as_view(), name='create'), path('validate_title', views.validate_title, name='validate_title'), ] create_post.html <body> <form method="POST" id="post-form"> {% csrf_token %} <div class="row" style="margin-left: 400px;margin-top: 50px"> {{ form }} <button type="submit" style="margin-left: 20px" class="btn btn-primary">Submit</button> </div> </form> <div> {% for i in posts %} <label>{{ i.title }}</label> {% endfor %} </div> <script type='text/javascript'> $(document).ready(function () { $(document).on('submit', '#post-form', function (e) { e.preventDefault(); … -
Is it possible to access database from command prompt in Django?
I'm searching for the way to access database from command prompt without using Django admin. Thanks in advance. -
What are the diffences between django-dash and django-plotly-dash?
I am building a web app using Django. It will display network graphs and others data visualization and I am investigating Dash on that purpose. I found these two similar packages: django-dash and django-plotly-dash and I am wandering what would be the best solution. Is anyone knows the core differences between the two packages and has some experience with it? Thanks -
how to active show more button and show 3 item per page in django
i'm trying to show 3 items per page and if user press on show more button it will load more 3 items views.py : def home_page(request): pcgamesforhome = PCgames.objects.all() context = {'pcgamesforhome' : pcgamesforhome} return render(request,'html_file/enterface.html',context=context) html page : <div class="container"> <div class='row'> {% for home_page in pcgamesforhome %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href="{{ home_page.page_url }}"> <img src="{{ home_page.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href="{{ home_page.page_url }}" style="color:black">{{ home_page.name }}</a></h3> </div> {% endfor %} </div> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-secondary btn-lg loadMore" style="width:40%">Show More</a> </div> <script> $(".row").slice(0, 3).show(); //showing 3 div $(".loadMore").on("click",function(){ $(".row:hidden").slice(0, 3).show(); //showing 3 hidden div on click if($(".row:hidden").length ==0) { $(".loadMore").fadeOut(); //this will hide //button when length is 0 } }) </script> so what is the wrong in my code , ( my html page now show all items in model not 3 in once ) -
How to use the django-admin-search with search_FieldNameHere ? I am unable to use the same
The django-admin-search plugin version 0.3.5 has beem installed with django 3.0.5 on linux. How exactly to use the search_field query, I fail to understand. I am not great working with OOPS yet. What I tried: def search_mfrom(request, field_value, param_values): """ intercept query filter for description field """ query = Q() #print(request, field_value, param_values, 'llllllllllllll') query = Q(mfrom='sowmiya@abc.com') print(query, 'qqqqqqqqqqqq') return query The print(query, 'qqqqqqqqqqq') never executes. Am I passing in something wrong? The form field is mfrom. Secondly, wish to send in login specific records in queryset which this tool is overriding. How to do that? I am able to override the queryset based on login domain part of the request.user, but since this tool is also overriding the queryset object of the modeladmin, I don't know how to go about. The code snippet for the same: def get_queryset(self, request): domain_list = [] temp = [] qs = super(LogSearchFormAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: domain_list = Domain.objects.filter( customer__in=Customer.objects.filter( email=request.user.username)).values_list( 'name', flat=True) #print(list(domain_list)) dom_names = list(domain_list) #print(dom_names) qs = MailLogs.objects.none() if dom_names: for d in dom_names: qs = MailLogs.objects.filter( Q(mfrom__icontains=d)|Q(mto__icontains=d)) # qs |= MailLogs.objects.filter(mfrom__icontains=d) # qs |= MailLogs.objects.filter(mto__icontains=d) print(qs.query) #print(qs) return qs -
how can both foreign key shows the same values?
I am trying to connect two tables so i made a model with foreign key as follows- class Queryform(models.Model): querynumber=models.IntegerField(primary_key=True) name=models.ForeignKey("app.Person",on_delete=models.CASCADE,related_name="query_name",) address=models.ForeignKey("app.Person",on_delete=models.CASCADE,related_name="query_address",null=True) my Views.py def queryform(request): return render(request,'app/queryform.html',{'form':queryformform()}) But as i am using this form address is also giving name options in my form . name is correctly giving name options. how can i handle this thing ? -
Auto populating model fields in the django adminTabularinline with a foreign key relationship from another app model
Am writing a django app that can also store and manage business stock and such related stuff.Buh am a little bit stuck somewhere where i expect it to auto-populate some fields from the related stock app model into the daily sales app admin Tabularinline. I want it to autofill the rest of the fields from the related provided item name in the stock model on the fly after it has been input by the user in the daily sales. My stock model is as follows: class stock (models.Model): Item_Name = models.CharField(max_length=12) Quantity = models.PositiveIntegerField() Cost_price = models.PositiveIntegerField() Selling_price = models.PositiveIntegerField() date_added = models.DateTimeField(name='date added',auto_now_add=False) overall_price = models.PositiveIntegerField(null=True , blank=True) And then the daily sales model for tabularinline is : class product_entry (models.Model): Day = models.ForeignKey(daily_sales,on_delete=models.CASCADE) product = models.ForeignKey(stock, on_delete=models.CASCADE) Quantity = models.PositiveIntegerField() Selling_price = models.PositiveIntegerField() Total_price = models.PositiveIntegerField() For the daily sales admin : class product_entry_admin (admin.TabularInline): model = product_entry extra = 3 autocomplete_fields = ('product',) -
No matching distribution found for django==3.1.1 (from -r requirements.txt (line 23))
i am using ubuntu using terminal i am trying to install python and django i have installed python successfully but when i do pip3 install -r requirements.txt its showing this error :- WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue. To avoid this problem you can invoke Python with '-m pip' instead of running pip directly. DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality. Defaulting to user installation because normal site-packages is not writeable Ignoring python-magic-bin: markers 'sys_platform == "win32"' don't match your environment Collecting adyen==3.0.0 Using cached Adyen-3.0.0.tar.gz (13 kB) Collecting amqp==2.6.1 Using cached amqp-2.6.1-py2.py3-none-any.whl (48 kB) Collecting aniso8601==7.0.0 Using cached aniso8601-7.0.0-py2.py3-none-any.whl (42 kB) Collecting asgiref==3.2.10 Using cached asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting babel==2.8.0 Using cached Babel-2.8.0-py2.py3-none-any.whl (8.6 MB) Collecting beautifulsoup4==4.7.1 Using cached beautifulsoup4-4.7.1-py3-none-any.whl (94 kB) Collecting billiard==3.6.3.0 Using cached billiard-3.6.3.0-py3-none-any.whl (89 kB) Collecting boto3==1.14.52 Using cached boto3-1.14.52-py2.py3-none-any.whl (129 kB) Collecting botocore==1.17.52 Using cached … -
How to always let heroku run a command on deployment for a django project?
I was working on a django project. The Procfile is the place that heroku always looks on before deployment. Currently it is configured this way and it works all fine. web: python manage.py collectstatic --no-input; gunicorn project_folder.wsgi --log-file - --log-level debug This means it runs collectstatic command every time I make any changes in my project and deploy it on server. Can the same thing apply to run a background task? This background task needs to run automatically after my project is deployed. python manage.py process_tasks is what I type in my command to trigger this background_task in django on my local server. So, would something like this below be invoked the same way as python manage.py collectstatic serves(that is collecting all static files in my static folder)? web: python manage.py collectstatic --no-input; python manage.py process_tasks; gunicorn project_folder.wsgi --log-file - --log-level debug -
Redirect set of included URL patterns in django
For my Django app, I've always had my Dashboard pages prefixed with /site/dashboard/ urlpatterns = [ path('site/dashboard/', include('dashboard.urls')), ] I'd like to simplify the URLs and change it so the pages are just /dashboard/ urlpatterns = [ path('dashboard/', include('dashboard.urls')), ] I'm familiar with doing a RedirectView in URLs to redirect to a different single url/view. How would I do this with an entire set of views, so all the old /site/dashboard/ URLs in dashboard.urls were marked with a 301 redirect to the new URLs? -
How do i add in manytomany relationship in django
class Watchlist(models.Model): item = models.ManyToManyField(Product, related_name="item") watcher = models.ForeignKey(User, on_delete=models.CASCADE, related_name="watcher") def __str__(self): return f"watcher: {self.watcher}, {self.item.all()}" -
Creating rest api from Dango
I have created models to save the product, categories and ProductCategory. class Product(models.Model): ... title = models.CharField(max_length=100, default = '') ... class Category(models.Model): name = models.CharField(max_length = 20, default = '') class ProductCategory(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE) Serializer for the Model: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ProductCategorySerializer(serializers.ModelSerializer): class Meta: model = ProductCategory fields = '__all__' ViewSets class ProductViewset(viewsets.ModelViewSet): queryset = models.Product.objects.all() serializer_class = serializers.ProductSerializer class CategoryViewset(viewsets.ModelViewSet): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class ProductCategoryViewset(viewsets.ModelViewSet): queryset = models.ProductCategory.objects.all() serializer_class = serializers.ProductCategorySerializer Until now I can add data to each table and view them from Django REST framework. Json Response: Product: [ ... { "id": 1, "title": "Jacket One", } ... ] Category [ ... { "id": 1, "name": "Jacket", } ... ] Product Category [ ... { "id": 1, "product": 1, "category": 1 } ... ] The actual json I want to create is: [ "jacket":[ { "id": 1, "title": "Jacket One", } ......other jacket products...... ], ........ other categories with their products ............ ] How could I achieve such json. I tried joining the models and filtering in … -
Can't figure out primary key
Dumb question, but I can't seem to figure it out. I use Djangos User model, with a custome Profile model (OneToOne relation). Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) goal = models.FloatField(max_length=20, blank=True, null=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save(). I have this code in my view (i want to update data inside the Profile model) def home(request): profile = get_object_or_404(Profile, pk=id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save return render(request, 'Landing/index.html',{'form':form}) My question is that what is my primary key in this situation? -
Unique Id generator based on created date in django?
hello I am A new to software , i am working on id generation in the format- Q/YYYYMM0001 where 0001 is a serial number for which i wrote the following model- from sequences import get_next_value class Queryform(models.Model): querynumber=models.CharField(primary_key=True,editable=False) queryserialnumber=models.CharField(get_next_value=True,initial=0) querydatecreated=models.DateField(auto_now_add=True) def querynumber(self): return '{}/{}{}'.format(str="Q",self.querydatecreated.truncatemonth,self.serial_no.zfill(4)) def save(self, *args, **kwargs): self.generated_id = self.generate_id() super().save(*args, **kwargs) i have a few doubts - have i used get_next_value correctly ? str="Q" will give a string value? what if i delete on row from the table will the serial number vary ? example - i had Q/YYYYMM009 id saved later i deleted one , that is now i have 8 rows. The next id generated will be again Q/YYYYMM009 ? i dont want to repeat the ids to avoid clash . -
How to Get data from single django app models on multiple html page
I'm trying to display data from single django app models to multiple html page but I don't know what the correct steps are anyone can help me and i will be thankful i'm using django -
Can't store a Selenium web driver object to recover it through Django views
After days of research, I wasn't able to properly store a Selenium web driver object to recover it through different Django views. In fact, My project has only one view, and all I need is to recover the same instance of the web driver object every time that view is called. All my app does is making AJAX post requests to the view and updating the frontend and some data in the web driver window. Having initialized the driver as driver = webdriver.Chrome(executable_path=driverpath, desired_capabilities=caps) , these are all the things that I tried: 1) Storing the object in request.session array. Of course this doesn't work, a web driver object is to complex to be JSON serialized. TypeError: Object of type WebDriver is not JSON serializable 2) Pickle Serialize: Didn't work. A code like pickle.dumps(driver, open( "driver.p", "wb" )) throws this error AttributeError: Can't pickle local object '_createenviron.<locals>.encode' 3) Creating a new driver and assigning to its session_id attribute the previous web driver session_id value. Didn't work. This was the approach: request.session['driver_id'] = driver.session_id #And then on another view call: chrome_options = Options() chrome_options.add_argument("--headless") #to prevent opening a new window new_driver = webdriver.Chrome(options=chrome_options) new_driver.session_id = request.session['driver_id'] 4) Using Ctypes: This is … -
Django custom user model with BaseUserManager set is_active=True not working
I'm working on a project using Python(3.7) & Django(3) in which I have implemented a custom user model and inside the User manager, under create_user method I set user.is_active = True but it's not working on signup. Here's my implementation: class MyAccountManager(BaseUserManager): def create_user(self, email, fullname, password=None): if not email: raise ValueError('Users must provide the Email.') user = self.model( email=self.normalize_email(email), fullname=fullname, ) user.set_password(password) user.is_active = True user.save(using=self._db) return user def create_superuser(self, email, fullname, password=None): user = self.create_user( email=self.normalize_email(email), fullname=fullname, password=password ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superuser = True user.save(using=self._db) return user createsuperuser is working fine, mean it setup is_active = True but when signup as other user types it's not working. What can be wrong? -
Django ajax post 200 but no change(post) in database
I am trying to post user location to django(postgres) database. While my ajax request shows message 200 (OK) , this is not reflected on change on the database. I can't seem to figure out why. <html> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/wicket/1.3.6/wicket.min.js" integrity="sha512-7V9RlkyO655oDrkJ7kMXAa4Z+DS0+Kq/eXV0ZKWAv9RJtstw7rHJU1/KgpLovGZtL2FaJ9L24w3qa6L/qy3spg==" crossorigin="anonymous"></script> <head> {% load leaflet_tags %} {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} </head> <body> <div> <strong>Current position: </strong> {{ user_location }}<br/> </div> <label for="locations-status">Locations enabled?</label> <input type="checkbox" id="locations-status"> <script type="text/javascript">window.CSRF_TOKEN = "{{ csrf_token }}"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = Cookies.get('csrftoken'); $(document).ready(function(){ $('input[type="checkbox"]').click(function(){ if($(this).prop("checked") == true){ getLocation() } else if($(this).prop("checked") == false){ console.log("Location services are disabled"); } }); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { … -
What is the best way to make Live tracking of each user on front-end pages (date-time and other actions)?
Our project is one of the online Shopping Service , built with Django and front-end is made up with Quasar! As you guys know that users' every clicks do not request to The Back-end, but I should track every pages users visit(for analytics)! And if the Data we will be storing gets bigger than we imagine , then we will start storing the data to another Database! 2nd question is how to store data? Should we store in the default DB or a separate Big Data DB? thanks for your answers! -
Django refresh page but dont redirect
On the page /home I created a login button in my navbar and when you click on it it will open a kind of a popup with changing display to block. But my problem is that I cant find out how the user could stay on the page when logging in with wrong data. At the moment it just returns me to the /home page and if I click again on the navbar button the login window opens with the "error" message but I want it to either redirect me to the /home page but the login popup is still opened or just don't redirect me anywhere. So I think I am just looking for a way that this message updates but you stay on the login popup. Here is my part of the views.py: def post(self, request, *args, **kwargs): # form = UserCreationForm(request.POST) # print(form.errors) # <process form cleaned data> username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: print(user, "has successfully logged in") login(request, user) return HttpResponseRedirect('/recipes/all') else: messages.error(request,"Password or username is incorrect") return HttpResponseRedirect('/recipes/all') And here is the part of my HTML file: <div class="login-popup-box" id="login-popup-box"> <div class="user-card-login"> <div class="close-button-box"> … -
How to display ReadOnlyFields without label in Django Admin?
I am trying to display some data in my Django admin ReadOnlyFields, but I am unable to display, I want to display emailid and verify_emailid in the same line in the fields, I can do it using fieldset but it's displaying lable also, please let me know how I can display data without a table. Here is my admin.py file... class MyModelAdmin(ReadOnlyAdminMixin, CustomModelAdmin): fields = (('emailid','verify_emailid),'mobilenumber','type') here emailid and verify_emailid display in the same line but the issue is the verify_emailid display label, and I don't want the label of verify_emailid, please let me know how I can remove the verify_emailid label... -
How can i use django allauth token in next steps for authorization?
I used the Django-allauth login,but i can not use token for next steps for authorization,and i do not know how to change views of login and logout method that are in Django-allauth. -
which gitignore file shall i use when uploading a django project which contain a secret key?
i am new in github, i uploaded a django project without a git-ignore file & github community banned my account. That's why i need to know how to use a git-ignore file & also license.