Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting data in API with ElasticSearch
I have come across a requirement where I need to get URL link for Instructions related to a code. But the issue is the data coming from ElasticSearch in API which is already designed and working. So all the columns in the table is coming from ElasticSearch except instruction URL. I need to add a URL link for the instructions in the table column which will open in new tab once clicked. All 6 columns are there in a table in frontend which data we're getting from ElasticSearch.. So I need to map Instructions related to the code and then give the url link to the table. The problem is I cannot touch the data coming from ElasticSearch. So how do I need to proceed with? I am stuck to get For 1 column with Instruction url mapped to the code(which is already one column in table) How do I need to design API which will get the code and give the matching URL instruction link. -
Custom validation in the clean method triggers before checking the fields exist or not in Django
I have the following code in my models file in Django: class MyModel(models.Model): ... foo = models.IntegerField() bar = models.IntegerField() def validate_foo_bar(self): self._validation_errors = {} if self.foo > self.bar: self._validation_errors['foo'] = ['Must be greater than bar.'] self._validation_errors['bar'] = ['Must be less than foo.'] def clean(self): self.validate_foo_bar() if bool(self._validation_errors): raise ValidationError(self._validation_errors) super(MyModel, self).clean() Hopefully the idea is clear. I check for errors in the clean method and raise them if they occur. When I use an admin form to create an object, if I leave the foo and bar fields empty, I get the following error: if self.foo > self.bar: TypeError: '>' not supported between instances of 'NoneType' and 'NoneType' Why is this happening? Shouldn't the requirement check trigger before the method I wrote? Thanks for any help. -
Django Rest Framework JWT - expose some api with authentication
I have added JWT authentication in my django react project. what i want to achieve that i want to expose some api without authentication. its a ecommerce project and i want to expose category listing api so that anyone can access without authentication. settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':[ #'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', #'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.IsAuthenticated', #'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE':10, } views.py: @permission_classes((IsAuthenticated,)) class UserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = serializers.UserSerializer #User Registration View class CreateUserView(generics.CreateAPIView): model = get_user_model() permission_classes = [ permissions.AllowAny ] serializer_class = serializers.RegisterSerializer #Category Listing View @permission_classes((IsAuthenticated,)) class CategoryView(generics.ListCreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializers class CategoryDetailView(generics.RetrieveUpdateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializers also want to remove pagination from category listing -
Django-REST: Proper way to add API to get entity via another field?
I'm super new to Python/Django/Django-REST, but I've managed to follow the tutorial and create my own API similar to the tutorial. In my app, I have a model called Toggle, with a unique field called feature_key. Following the tutorial, the default way to get a Toggle is by using the ID, i.e. http://127.0.0.1:8000/toggles/1/ And it shows up in the browsable API page as a clickable link. My question is, how do I add another endpoint to directly get a toggle via its feature_key? Maybe something like: http://127.0.0.1:8000/toggles/key/category.key_1/ (I'm not sure if this is a "correct" way to design API) How do I make this endpoint to be visible in the browsable API so that other devs are aware that this endpoint exists? -
Django model query set to list then use that list for an exclusion query on another model
questions = Question.objects.filter(category=category) seen_questions_query = SeenQuestions.objects.filter(worker=user_id).only('question_id') seen_questions_list = list(seen_questions_query) questions_list = list(questions.exclude(id__in=seen_questions_list).values()) random_sample = random.sample(questions_list, question_count) I have this code above that does not work. I'm more curious about good Django practices than getting this to work. The goal is to take a "user_id" and query for questions they've seen in the "SeenQuestions" model then turn that into a list, which will be used to query the "Question" model for all questions that don't have a primary key on the list. Then I convert that to a list and randomly sample "question_count" amount of questions, which get turned into a JSON and returned to whomever is making the GET request. I've taken the approach above, but I don't feel like this is best Django practices, it seems like there is a better way rather than converting query sets to list then querying on that list then converting to a list again. The above does not work because it complains about converting "seen_questions_query" to list on line 3. -
Save the returned csv file in Django static folder and serve the file path to be downloadable?
So from these two functions, i want to map the output of the second function to the output of first function and then save the new mapped output to a new csv file to be saved in static Django folder and serve the file path as downloadable. How can i achieve this? For example, the response from the first function is a dataframe that contains two columns: A, B. The response from the second function is a list of numerical values (which is the routes position). I want to map the dataframe with the values from the list and save in a new csv file. def parse_csv(file_path, cols, depot): """ function to parse whole csv file for the specified cols params: nrows = no. of rows to load in dataframe file_path = file path of csv file cols = list of column index/col name to parsen returns : DataFrame """ try: df = pd.read_csv(file_path, nrows=500) except Exception: df = pd.read_csv(file_path, nrows=500, sep=';') if cols in df.columns: data = list(df[cols].values) data.insert(0, depot) else: cols = df.columns.get_values()[1] data = list(df[cols].values) data.insert(0, depot) return data def print_solution(data, manager, routing, solution): """Prints solution on console.""" max_route_distance = 0 result = list() result.clear() for vehicle_id … -
Django - Selecting multiple entries from a JSON object to be shown on next page
I am attempting to allow multiple entries to be selected from a JSON object which is represented in an HTML table. Once the user has selected their entries and submitted, they will be redirected to a new page with only their selected entries shown in the table for them to confirm their selections. One option is to create a function in my views.py that stores the selected entries in a list, the list is then called on the next page. To do this i would need my table to be a form, and on click of each row in the table that rows values get added to the list. I would also need to remove the item from the list if the user clicked that row again. another option is to create a Javascript Set, and to then store that set somehow and represent it in the next page. Does anybody have some advice on which if these would be the most practical to achieve at scale? An example of my data [ { "pk": 1, "Description": "Pizza", "Price": "100.00" }, { "pk": 2, "Description": "Cheeseburger", "Price": "80.99" }, { "pk": 4, "Description": "Coca Cola", "Price": "20.00" }, { "pk": … -
Managing hierarchies of User in Django (Peers users, sub users etc.)
I have a business requirement where I have broadly three types of users. Client Staff Admin (Super admin) A Client can be further specified as a Supplier, Buyer or some other kind of Client that we don't know in advance. A Staff can be further classified as UnderWriter or some other kind of Staff that we don't know in advance. A Client will have common Client related information and a Supplier or Buyer can have its own different data. The same goes for Staff and it's "sub" users. There will be a single login page for a Client, but it can take it to a separate dashboard view depending on the type of Client(Supplier, Buyer, etc). In short Supplier and Buyer will have their own dashboards but a single Client login. The same mechanism would be followed for the Staff members. Different dashboards depending on the type of Staff(UnderWriter, Issuer, etc) but the single login page What would be the best way to model this approach to work seamlessly with Django's builtin authentication system? Particularly I would like to know how to use model relationships or maybe Polymorphism to design this system? -
Unable to send Authorization token from iOS client to Django server
I've built an iOS app that hits my custom Django server. I am using AlamoFire to make the HTTP requests. The following is my code in Swift that I got from here (note that url is a variable I created beforehand with the correct path). let headers: HTTPHeaders = ["Authorization" : accessToken, "Content-Type" : "application/json"] AF.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: headers, interceptor: nil).validate().responseJSON { response in switch response.result { case .success: if let json = response.value as? [String : AnyObject] { completion?(json, nil) } case .failure(let error): completion?(nil, error) } } However, when I try to get my authorization token on my Django server like so (which I found from here): request.META.get("HTTP_AUTHORIZATION") I get None as the return type. I'm rather new to using Alamofire and also Django so I am unsure as to where the problem lies. I've tried looking up solutions for both the iOS and the Django side, but to no avail. As a side note, I used to work on a project using Flask and was able to get the Authorization header like so: request.headers.get('Authorization') -
Change image in ImageField programatically on existing Model (AWS S3 bucket)
I want to make a edit profile feature that after deleting existing profile image it is replaced with default one that's stored on S3 bucket also. My model: class UserProfile(models.Model): image = models.ImageField(default='default.jpg', upload_to=get_file_path) # makes unique img name After googling around I saw a solution simillar to this approach, but it gives error (listed below the code). My view: class UserProfileEditViewModal(BSModalUpdateView): model = UserProfile template_name = 'users/profile_edit_modal.html' form_class = UserProfileUpdateFormModal success_message = 'profile' def get_success_url(self): return self.request.META.get('HTTP_REFERER') def form_valid(self, form): # checks for checkbox value delete_current_image = form.cleaned_data['delete_current_image'] if delete_current_image: userprofile = self.request.user.userprofile current_image = userprofile.image if current_image.name != 'default.jpg': # delete existing one userprofile.image.delete(save=False) # read default one from storage new = storage.open('default.jpg').read() # make it django storage friendly filee = File(new) # save - ERROR here userprofile.image.save('default.jpg', filee) return super().form_valid(form) File "D:\Dev\Python\social-app\venv\lib\site-packages\django\core\files\utils.py", line 20, in <lambda> seek = property(lambda self: self.file.seek) AttributeError: 'bytes' object has no attribute 'seek' -
Apache configure multiple domains for different apps in a single django project
I using apache2 to host two apps app1 and app2 of a single django project on app1.com and app2.com respectively. For this, i have created two wsgi,settings and url files for each app. app1_wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.app1_settings') application = get_wsgi_application() app2_wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.app2_settings') application = get_wsgi_application() app1_settings.py from .settings import * ROOT_URLCONF = 'project.urls.app1_urls' app2_settings.py from .settings import * ROOT_URLCONF = 'project.urls.app2_urls' apache2.conf ################### Custom Settings ################ ## For passing authorization over https JWT Django ## WSGIPassAuthorization On ## Settings ## DocumentRoot /var/www/production/src Alias /static /var/www/production/static_cdn <Directory /var/www/production/static_cdn> Require all granted </Directory> Alias /media /var/www/production/media_cdn <Directory /var/www/production/media_cdn> Require all granted </Directory> <Directory /var/www/production/src> Require all granted </Directory> <Directory /var/www/production/src/project> <Files app1_wsgi.py> Require all granted </Files> <Files app2_wsgi.py> Require all granted </Files> </Directory> <Location "/robots.txt"> SetHandler None Require all granted </Location> Alias /robots.txt /var/www/production/src/robots.txt <Location "/sitemap.xml"> SetHandler None Require all granted </Location> Alias /sitemap.xml /var/www/production/src/sitemap.xml WSGIDaemonProcess app1 python-path=/var/www/production/src:/var/www/production/lib/python3.6/site-packages WSGIScriptAlias / /var/www/production/src/project/app1_wsgi.py <Location /> WSGIProcessGroup app1 </Location> # Security RewriteEngine on RewriteCond %{THE_REQUEST} !HTTP/1.1$ RewriteRule .* - [F] SetEnvIfNoCase User-Agent ^libwww-perl bad_bot BrowserMatchNoCase SpammerRobot bad_bot BrowserMatchNoCase SecurityHoleRobot bad_bot <Location /> Order allow,deny Allow from all Deny from env=bad_bot </Location> SSLProtocol all … -
Can Anyone tell me the way to display result of a command run in a device using restframework python django
I want the result of a command which is run in a device as like below. below i hardcoded the values. The code will be look like below from django.db import models class Device(models.Model): # device name name = models.CharField(max_length=255, null=False) # ip of device ip = models.CharField(max_length=255, null=False) # fqdn #fqdn = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.name, self.ip) I want to modify the code according to my requirement. Please some one help me in this. -
Python Django:JSONDecodeError when i try to retrieve data from the api
When I tried to return a date in my python api request, I get the error message 'Object of type date is not JSON serializable'. I converted it to JSON using this function below: def myconverter(o): if isinstance(o, datetime.datetime): return o.__str__() Now it is returning a null value and also the error message 'JSONDecodeError at /search/ Expecting value: line 1 column 1 (char 0)'.What am i doing wrongly?This is my code below: new_parameter=json.dumps(parameters, default = myconverter) print(new_parameter) urls = 'https://ije-api.tcore.xyz/v1/flight/search-flight' result = requests.post(urls,json=new_parameter,headers=headers).json() print(result.text) flight ={ "departure_date": result['body']['data']['itineraries'][0]['origin_destinations'][0]['segments'][0]['departure']['date'], "departure_time": result['body']['data']['itineraries'][0]['origin_destinations'][0]['segments'][0]['departure']['time'], } print(result) -
Django how to use distinct()
How to use distinct() in django what i tried: views.py def gradescales(request): grade = gradeScalesSetting.objects.all().values_list('Rounding','Configuration').distinct() print(grade) return render(request, 'Homepage/gradescale.html',{"gradeScalesSetting":grade}) the result i got: -
como agrupar datos repetidos?
tengo esta consulta de django: detalleventa = DetalleVenta.objects.filter(venta_id__in=idventas).values('cantidad','producto__nombreProducto') print(list(detalleventa)) el cual me imprime esto: [{'cantidad': 6, 'producto__nombreProducto': 'Jose Cuervo'}, {'cantidad': 2, 'producto__nombreProducto': 'Absolut'}, {'cantidad': 7, 'producto__nombreProducto': 'Litro Tapa Roja'}, {'cantidad': 1, 'producto__nombreProducto': 'Litro Tapa Roja'}, {'cantidad': 2, 'producto__nombreProducto': 'Ron Medellín Garrafa'}, {'cantidad': 4, 'producto__nombreProducto': 'Aguila ligth'}, {'cantidad': 1, 'producto__nombreProducto': 'Aguila ligth'}] quiero que aguila light no salgan 2 con distinta cantidad, sino algo como esto: ..... {'cantidad': 2, 'producto__nombreProducto': 'Ron Medellín Garrafa'}, {'cantidad': 5, 'producto__nombreProducto': 'Aguila ligth'}, como puedo lograrlo? -
How does Django detect locale to make translation work
I don't quite understand how Django detect the local machine's locale. I have made the translation works if I explicitly set the language code. But how does it make translation base on locale and how to test it. -
Error while passing value with url to django view
Error while passing value to view from template using url Error : Error during template rendering In template D:\TONO\DJANGO_TASK\user_auth\templates\auth_app\other-user-listing.html, error at line 114 Reverse for 'add_to_group' with arguments '(name: Administrator,)' not found. 1 pattern(s) tried: ['auth_app\\/<str:username>/'] This my urls.py url(r'^<str:username>/', views.add_to_group, name="add_to_group"), This is the call from template <a href="{% url 'add_to_group' username %}"><i class="icon-plus">Add</i> </a> -
How to post the every step data of a wizard in the database using django?
I am having the 4 html pages in templates and those html pages will be having the next and previous steps now what I am trying to do is after clicking the every next the data is to be stored and after final submit the overall data should be dumped into the database.How can we achieve this in django? please illustrate with an example if possible? Thanks in advance The steps will be as in the link given here https://www.modsy.com/project/room -
how to access request object inside Django Form
I need to access the request object inside Django Form, to name the form fields dynamically as it looks like into the code below. The request object is currently returning None. How can i have request object inside form? class PartitionAdminForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) request = kwargs.get('user', None) term_partition = core_utils.get_system_terms(request).get("partition") if self.fields.get('username'): self.fields['username'].label = _(f"{term_partition} Super Admin Username") self.fields['username'].help_text = "" -
Is there any resource for learning django?
I am new to django. I want to build an online pharmacy stock management system with e-commerce. but I'm new to django. it's getting hard for me. is there any ways to learn django. or any help. I have no idea about this guys. -
AWS Cognito Boto3 Error on Confirm Device: Invalid device key given
I have been creating a AWS Cognito flow with Python, Django and Boto3 with MFA enables. My authentication flow is the following: initiate_auth: called on an django rest endpoint response = client.initiate_auth( ClientId=settings.AWS_COGNITO_CLIENT_ID, AuthFlow='USER_PASSWORD_AUTH', AuthParameters={ 'USERNAME': email, 'SECRET_HASH': get_secret_hash(email), 'PASSWORD': password, } ) if "ChallengeName" in response: data["mfa"] = True data["session"] = response["Session"] respond_to_auth_challenge: called on a seperate django rest endpoint response = client.respond_to_auth_challenge( ClientId=settings.AWS_COGNITO_CLIENT_ID, ChallengeName='SMS_MFA', Session=session, ChallengeResponses={ 'USERNAME': email, 'SMS_MFA_CODE': code, 'SECRET_HASH': get_secret_hash(email), } ) based on this post I wanted to implement the confirm device so MFA is skipped upon next login. So after the respond to auth challenge I have this code: device_key = response['AuthenticationResult']['NewDeviceMetadata']['DeviceKey'] device_group_key = response['AuthenticationResult']['NewDeviceMetadata']['DeviceGroupKey'] device_password, device_secret_verifier_config = generate_hash_device(device_group_key, device_key) device = client.confirm_device( AccessToken=response["AuthenticationResult"]["AccessToken"], DeviceKey=device_key, DeviceSecretVerifierConfig=device_secret_verifier_config, DeviceName=email ) But I always get the Unknown error An error occurred (InvalidParameterException) when calling the ConfirmDevice operation: Invalid device key given. Can anyone help on why this happens? -
Django views function skip urls keywords
#1. path('<str:lang>/request/', views.request.get_request), #2. LangMiddleware #3. views.py ---> def get_request(request): <--- I don't want to put 'lang' param I have a lang keyword in urls, this keyword only use inside of LangMiddleware It don't need it inside of views, therefor I don't want to put keyword in every function. anyone know how to solve this? -
Advice on how to handle PostgreSQL database in Django app?
For some background, I worked on a Django app that had a SQLite3 database. I just created models in Django using the python manage.py startapp model_name, and just directly manipulated the database by creating API endpoints in python. I would then make API requests and change my database like that. But this time, I've created a Django app that has a PostgreSQL database. I managed to connect my database to Django after figuring out how to install psycopg2. Then, I created a Users table in PostgreSQL through the command line. I want to get this table to show on my Django admin site, and hopefully repeat the same method for the other app. But the Django admin site can render only Django models that have been registered to the admin. So now, I'm wondering if there is a better method for working with PostgreSQL in Django. I saw SO posts suggesting inspectdb, but this creates a large models.py file generating other classes for my app. I also couldn't successfully register the Users model to the Django admin site. I am now curious if I am working in the opposite direction. Should I be generating User models in Django and then … -
session management (Angular and Django)
I am using django rest framework and angular, practicing with this I was logging in, but I had doubts about how active sessions are handled, I have no idea how to do it but the concept, I have seen that several use a token (djangorestframework-jwt) but I do not quite understand it, what I want to do is that when you log in the records are created they carry the user's id -
what framework/language should I use to build a contact us website
a relative of mine wants me to build a contact us website for his business. I just finished systems engineering first year and have no experience with web development. I understand that this is an easy task as there is no database managment or things like that. I have played around with django and javascript but I'm not sure what kind of technologies are the best for this cases. Is django a good choice? or is the task too simple to use django? What should I use? The website should have an admin mode in which my relative can easily add and change information whenever he wants. Thanks, any suggestion as to what frameworks or languages to use for backend and frontend will be appreciatted.