Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
added form data is not related ManytoOne relationship in database
[models.py]forms.py 2I added foreign key for many to one relationship .when i open my database i had all added data that was not connected with each other. i need to connect every data , means user must be added to person , person is to be added to questions, then only foreign key relationship worked . my problem is why the form data automatically linked by user to person, person to question.views.py -
ERROR: Could not find a version that satisfies the requirement pkg-resources - Heroku not deploying Django App
I am trying to deploy a Django Application on Heroku through Github but I keep getting the error below: Below is the requirements.txt file I don't understand where the pkg-resources is coming from. Also, Heroku is ignoring the runtime.txt which specifies the Python Version is 3.7.9 -
How can I identify the firstname and lastname even if I don't pass them in order in python? [closed]
I am developing an algorithm which can take PAN number and Bank account name, when I pass this two parameters to my function , It should return true if the both name has identically same meaning. Like: "Bhavik Darji" and "Darji Bhavik" are identically same That we human can understand , Another Scenario be "Bhavik Darji" and "Bhavik A. Darji" are same so my function should return True. Any help or suggestions would be highly appreciated. Thanks in advnace. -
How to only show specific values in Form with ModelChoiceField based on group/permissions?
This is what my UserCreateFrom looks like: class UserCreateForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) driver_number = forms.CharField(max_length=30, required=False) group = forms.ModelChoiceField(queryset=Group.objects.all, required=True) In my auth_group table I added a field for a role number. Like admin=1, editor = 2... If a user now accesses a site to create a user, I want him only to be able to choose a group for that new user, that has a higher value than his own group. So the admin can create everything, but the editor cant create an admin and so on. Is there a way to pass a value to the UserCreateForm which I then can use in the definition of the form field? Smth like this: group = forms.ModelChoiceField(queryset=Group.objects.filter(role>requesting_user_role), required=True) My other idea would be to work with custom permissions, but I still would need to pass the user somehow when creating the form. -
How to deactivate and activate users from SQLlite when they input wrong password three time in python Django?
The question is if user puts 3 times wrong password then he deactivate from database for 5 mins and after 5 mins program can allow to login the same user please provide a good program on Django/Python enter image description here -
Django put data from external api to Database
iam working on a django-project. And my goal is to receive data from the docker deamon and pass the information to a simple integrated Django-Database like sqlite3. I made it already to put the information output to the template. But how i can pass the data to this database. I tried it for month and i didnt get it.i hope some of you can help me. Some Code: docker_api.py where the information comes in: from json.decoder import JSONDecodeError from requests_unixsocket import Session from requests import RequestException from config.settings import DOCKER_API def docker_requester(func): def wrapper(*args, **kwargs): method, endpoint, data = func(*args, **kwargs) session = Session() call = getattr(session, method) resp = call(DOCKER_API + endpoint, json=data, timeout=30) if resp.status_code == 204: return True if resp.status_code == 201 or resp.status_code == 200: try: return resp.json() except JSONDecodeError: return True return False return wrapper @docker_requester def list_image(): return "get", "images/json", None This already works images.py(acting like a view): from dockerInspector.forms import ImageForm from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from dockerInspector.docker_api import list_image, pull_image, delete_image def list_images_view(request): resp = list_image() images = [] for res in resp: try: img_id = res["Id"].split(":") repo_tags = ( res["RepoTags"] … -
Can´t crate test database django
I´m trying to test a django application, but when I run python manager.py test I got this error django.db.utils.ProgrammingError: column deals_dealproposal.billing_branch_launcher_id does not exist it´s occurs in File "/migrations/0008_dynamicpackingtype.py", line 18, in run for proposal in bulk_proposals: In this point, billing_branch_launcher doesn't really exist, it´s create in migration 27 migrations.AddField( model_name='dealproposal', name='billing_branch_launcher', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='billing_branch_launcher', to='clients.CoffeeCompany'), ), The migration 8 looks like this class Migration(migrations.Migration): dependencies = [ ('coffeedeals', '0007_auto_20190315_1642'), ('schemas', '0003_dynamicpackingtype') ] def run(app, schema_editor): bulk_proposals = md.DealProposal.active.filter( data__negotiation__packing='bulk', data__negotiation__packing_type__isnull=False) for proposal in bulk_proposals: del proposal.data['negotiation']['packing_type'] proposal.save() operations = [migrations.RunPython(run, atomic=True)] How can I fix it? -
I am getting this error when im trying to deploy my google cloud app. I have included the .gcloudignore file, however i still get this issue
ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: This deployment has too many files. New versions are limited to 10000 files for this app. '@type': type.googleapis.com/google.rpc.BadRequest fieldViolations: description: This deployment has too many files. New versions are limited to 10000 files for this app. field: version.deployment.files[...] -
cannot serve static files using caddy + django + gunicorn
I'm working on a project that's using caddy as a web server and proxy, django as the backend, and gunicorn as the wsgi. But everything all works well except I can't serve the static files. This is my Caddyfile. mydomain.com { root * /path/to/staticfile/ file_server encode zstd gzip @notstatic { not path /path/to/staticfile/* } reverse_proxy @notstatic app:8000 } Is there anything wrong that I have used? -
Websocket Not running using DJango Channels - 200 Response Code
Websockets is not able to establish a connection. The server config is as below. Daphne server runs fine and normal web views work fine too. failed: Error during WebSocket handshake: Unexpected response code: 200 The App is run as below using daphne and gunicorn. Tried to run just using runserver on 8100 too but same issue. daphne -b 0.0.0.0 -p 8100 --proxy-headers eCommerce.asgi:application type: development 2021-03-04 09:42:08,913 INFO Starting server at tcp:port=8100:interface=0.0.0.0 2021-03-04 09:42:08,914 INFO HTTP/2 support enabled 2021-03-04 09:42:08,915 INFO Configuring endpoint tcp:port=8100:interface=0.0.0.0 2021-03-04 09:42:08,916 INFO Listening on TCP address 0.0.0.0:8100 gunicorn --access-logfile - --workers 4 --bind unix:/srv/expo/eCommerce_copy/run.sock eCommerce.wsgi:application [2021-03-04 09:41:58 +0000] [26534] [INFO] Starting gunicorn 20.0.4 [2021-03-04 09:41:58 +0000] [26534] [INFO] Listening at: unix:/srv/expo/eCommerce_copy/run.sock (26534) [2021-03-04 09:41:58 +0000] [26534] [INFO] Using worker: sync [2021-03-04 09:41:58 +0000] [26537] [INFO] Booting worker with pid: 26537 [2021-03-04 09:41:58 +0000] [26538] [INFO] Booting worker with pid: 26538 [2021-03-04 09:41:58 +0000] [26540] [INFO] Booting worker with pid: 26540 [2021-03-04 09:41:58 +0000] [26543] [INFO] Booting worker with pid: 26543 type: development type: development type: development type: development routing.py from django.urls import path from .chat_consumer import ChatConsumer websocket_urlpatterns = [ path('messaging/<str:other_username>/', ChatConsumer), ] nginx configuration file map $http_upgrade $connection_upgrade { default upgrade; '' close; } … -
How to restrict a user from accessing the home page when the user is logged out? also defined the login decorator but not working? any idea about this
@login_required(login_url='/accounts/login/') def dashboard(request): if request.method == 'POST': c_form = MyUploadForm(request.POST, request.FILES) if c_form.is_valid(): file_name = c_form.cleaned_data['title'] the_file = c_form.cleaned_data['file'] FileUploads(name=file_name, my_file=the_file).save() messages.success(request, 'File uploaded successfully.') return render(request, 'account/dashboard.html') else: return HttpResponse('error.') else: context = { 'form': MyUploadForm() } return render(request, 'account/dashboard.html', context) -
Django inspectdb ORA-00942: table or view does not exist
Im trying to import existing oracle tables in django. Installed cx_oracle and i did all the steps for django to communicate with my oracle db. import cx_Oracle con = cx_Oracle.connect("PYTHON","PYTHON", "METDBR") cur = con.cursor() cur.execute("select * from ICUSTOMER") res = cur.fetchall() for row in res: print(row) works fine.... when im trying to inspect the table with the command python manage.py inspectdb icustomer i get Unable to inspect table 'icustomer' The error was: ORA-00942: table or view does not exist -
> Process 'command 'C:/openlogic-openjdk-11.0.8+10-win-x64/bin/java.exe'' finished with non-zero exit value 1
I have cloned a Kotlin reposity from my friend.If i try to run it in the IntelliJ IDEA Community Edition 2020.3.2 I get this error : Process 'command 'C:/openlogic-openjdk-11.0.8+10-win-x64/bin/java.exe'' finished with non-zero exit value 1. I am using Windows 10. Why? Thanks -
Django implement search filter with MySql Db
I want to search from keywords field in database that match whole word not character in that like: When my search term = "service" Then i get the result = ["Car service", "cab service"] And when my search term = "vice" Then also my result = ["Car service", "cab service"], but it should = [] Here is my code: def search_service_view(request): query_string = request.data['query'].split(' ') category = ServiceCategory.objects.filter( reduce(operator.or_, (Q(keywords__icontains=query) for query in query_string))) serializer = ServiceCategorySerializer(category, many=True, read_only=True) return Response(serializer.data) -
Reading string from excel using xlrd but it is returning an integer value
I have a field in excel which is displayed as '#NAME?' but its actual value is a string that is '=+cmSgER4Q10xcjhgkfygvBl1UUNil+a2aEJ1'. when I am trying to read this field using xlrd it is returning an integer value instead of the actual string. please help me out. import xlrd import boto3 import pprint loc = ("C:/cloud/crm.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) ID = (input("Please enter the Customer ID: ")) for j in range(sheet.ncols): if(sheet.cell_value(0,j).strip().casefold() == "AWS Account ID".strip().casefold()): for i in range(sheet.nrows): if(str(sheet.cell_value(i,j)).strip().lstrip("*").split('.')[0] == ID.strip()): username_row_index = i break elif sheet.cell_value(0, j).strip().casefold() == "Access Keys".strip().casefold(): Key_column_index = j Key = sheet.cell_value(username_row_index,Key_column_index) print(Key) -
Connect Django .html from urls.py
I would like to be able to click in a tab and directly access to a specific view template. I tried using TemplateView as suggested here: Django urls straight to html template But is not working for me. Here is my urls.py from django.urls import path from django.urls import re_path from django.conf.urls import url from . import views from django.contrib import admin from polls.views import * from django.views.generic.base import TemplateView urlpatterns = [ path('', views.index, name='index'), url(r'^$', TemplateView.as_view(template_name = 'culturesView.html'), name = 'culturesView'), path('<str:sample_id>/culturesView/', views.culturesView, name='culturesView'), path('addSample/', views.addSample, name='addSample'), ] The idea is to be able to connect directly to /main/culturesView.html It worked when I added this in my urls.py: path('/main/culturesView.html', views.culturesView, name='culturesView') However, If I want to access to this template again from already /main/culturesView.html It will try to access to /main/main/culturesView.html And it will keep adding the (main) in the path... thanks in advance for your help! -
Can I apply Django 2.X version to the latest version?
Currently, the latest version of Django is 3.1. I'm not familiar with Django, so I looked for Django lectures, and there were many Django 2.X versions of lectures. Can I apply Django 2.X version lecture to the latest version of Django (3.1 version)? -
Internationalization using babel not working on django project
So i am working on this project which has the following code for internationalization in it's settings.py file: ..... from babel import Locale LANGUAGE_CODE = "en" mi = Locale.parse("mi") LANG_INFO["mi"] = { #language details } ..... I am only sharing this piece of code as this is the only part that i wrote, which compiler specifies has an error. The end line of the error message is: raise UnknownLocaleError(input_id) babel.core.UnknownLocaleError: unknown locale 'mi' Here's the complete error message in case needed for reference: https://pastebin.com/YicNzEKS The command from where i get this error is python manage.py makemigrations I am not much familiar with internationalization. Can someone please help me with this... thank you -
"NoReverseMatch at" when a new model instance is created using CreateView
I am trying to create new model instances using the built-in CreateView and it it successful as I can see the new instance after submitting the CreateView form. However it fails to redirect to the DetailView of the new model instance returning NoReverseMatch at detailview/id. I have configured the model to redirect to the newly created instance but I think for some strange reason it is not working. Here are the model, views, templates, and the url patterns: the urls: from .views import (Courses, CourseDetail, NewCourse) path('courses/', Courses.as_view(), name="course"), path('course/<int:pk>/', CourseDetail.as_view(), name="course_detail"), path('course/new/', NewCourse.as_view(), name="new_course"), the views: class Courses(ListView): template_name = 'courses.html' model = EnglishClasses context_object_name = "classes" class CourseDetail(DetailView): template_name = 'courses.html' model = EnglishClasses context_object_name = "classdetail" class NewCourse(LoginRequiredMixin, CreateView): model = EnglishClasses fields = ['name', 'level', 'subject', 'instructor', 'price'] model: class EnglishClasses(models.Model): name = models.CharField(max_length=40, null=True) level = models.CharField(max_length=50, null=True, blank=True, choices=Levels,) subject = models.CharField(max_length=50, null=True, blank=True, choices=Subjects) instructor = models.ForeignKey(Teachers, null=True, blank=True, on_delete= models.SET_NULL) price = models.DecimalField(max_digits=15, decimal_places=2, max_length=30, null=True, blank=True) def __str__(self): return self.name + " " + str(self.subject) class Meta: verbose_name_plural = "English Classes" def get_absolute_url(self): return reverse('course_detail', kwargs={'pk': self.pk}) template: <a class="button..." href="{% url 'new_course' %}">Add New Class!</a> Again I can see the … -
pymongo addToSet with array of objects
I want to update array of objects only if object is not present in array. also I want to return document. I am using pymongo find_one_and_update and "$addToSet" but my function returning None. AttributeList is array of objects like "AttributeList" : [ {"attrId": "clr123", "attrName": "Color"}} object i want to add is like, {"attrId": "clr456", "attrName": "Style"} I want to add objects to this above array only if its not present. my approach to this is, def update_attribute_grp_data(self, grp_name, new_values, tag_name): query = {"attributeGroupName.en": grp_name, "status": 1, "attributeGroupTagName": tag_name} print(query) result = db2.productAttributes.find_one_and_update(query, {"$addToSet": {"AttributeList": new_values}}, return_document=ReturnDocument.AFTER) return result Problem here is, query finds document in mongoshell but this functions returns None in my python code. I am trying the object which is not in array. So it should return me document after updating. using pymongo==3.11.2 -
Get Paypal transaction ID to post to form from OnApprove
I have a paypal transaction set up with a smart button and I would like on approval following a redirect for the payment ID to be posted into my registration form. I can get it to redirect after the payment successfully but I cannot seem to get it to post the ID into the 'invoice' field. Here is my working so far - <script> function initPayPalButton() { paypal.Buttons({ style: { shape: 'rect', color: 'black', layout: 'vertical', label: 'buynow', }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{"amount":{"currency_code":"USD","value":1}}] }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { window.location.replace("https://www.mywebsite.com/register"); document.getElementById("invoice").value=details.id; }); }, onError: function(err) { console.log(err); } }).render('#paypal-button-container'); } initPayPalButton(); </script> And then my forms.py is set up as follows - class UserRegisterForm(UserCreationForm): email = forms.EmailField() invoice = forms.CharField(max_length=50, widget= forms.TextInput(attrs={'id':'invoice'})) class Meta: model = User fields = ['email', 'invoice', 'password1', 'password2'] -
It is possible to do a single complex query on these models rather than doing multiple queries?
With these models: class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile") bio = models.CharField(max_length=250) img = models.ImageField(upload_to='img_profiles/') class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post") text = models.CharField(max_length=260) data = models.DateTimeField(auto_now_add=True) class Following(models.Model): follow = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follow") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_that_like") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_like") I would need to take data from Post, User and Profile for each Post that has Post.user=Following.follow where Following.follower=request.user.id. Added to that I nedd a Sum of Like.post for each Post catched. The first part is ok with : qs=Following.objects.values('follow__post__id','follow__post__text', 'follow__post__data','follow__username','follow__first_name','follow__last_name', 'follow__profile__img').filter(follower_id=request.user.id).order_by('-follow__post__data') I would like to understand if it is possible to obtain the second part with the same query or if I need a second query / subquery -
How to assign a customer to a user in Django?
I created a system and in this system, there are several users and customers. What I want to create an assign function. A customer should assign to a user. For example, I have a customer list. When the user clicks a button, the user will see a list that other users and select one of them. After that, the customer's name will be listed in the different assigned customers list of the selected user. I wrote a code and this is working, but I cannot reach user from customer list. What I mean is when I click assign button it create a new customer. How can I reach user id or username? views.py def customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) # Assign form = AssignForm(request.POST or None) if form.is_valid(): form.save() return redirect('user:customer_list') myFilter = TableFilter(request.GET, queryset=customer_list.all()) context = { 'customer_list': customer_list, 'myFilter': myFilter, 'form': form } return render(request, 'customer_list.html', context) models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.CharField(max_length=20) address = models.CharField(max_length=100) VATnumber = models.CharField(max_length=10) telephone = models.CharField(max_length=10) email = models.CharField(max_length=30) contact_person = models.CharField(max_length=30) company = models.CharField(max_length=20) id = models.AutoField(primary_key=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True) class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) user_id … -
Django, get objects by multiple values
There is a model class Fabric(models.Model): vendor_code = models.CharField(max_length=50) color = models.CharField(max_length=50) lot = models.CharField(max_length=50) I've a list of objects values = [ {'vendor_code': '123', 'color': 'aodfe', 'lot': 'some lot 1'}, {'vendor_code': '456', 'color': 'adfae', 'lot': 'some lot 2'}, {'vendor_code': '789', 'color': 'dvade', 'lot': 'some lot 3'}, ] There are no ids in dict objects. How can get objects checking for list of field values? I know that I can query one by one in loop as: for item in values: fabric = Fabric.objects.filter(vendor_code=item['vendor_code'], etc.) but amount of objects in list can be large. Is there any proper way to get objects at once, if they exists? Or at least to get them with min amount of db hit. Thanks in advance! -
How can I check which Django middleware is synchronous or asynchronous?
I am using Django 3.1. I would like to see if I can use async to handle my webhook so as to give a faster response. From Async View, it states that: Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”. My question is how to turn on my logger to check it? I tried to add logger config to my settings.py. After that, I call logger.debug('in index') in a test function but nothing is shown. I cannot find the log messages “Synchronous middleware … adapted”. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'WARNING', }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': False, }, }, }