Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render list of lists elements in django html
I have list of lists like this in django view: res = [['Adam','334','Ford'],['Steve','130','Porsche'],['Dave','510','Ford']] I want to display for example Adam, 334, Ford in table cells {% for n in data %} {% for k in n %} <table style="border:1px solid black;margin-top:15px;width:100%"> <tr> <td style="width:33%;border:1px solid black;"> {{ k.0 }} </td> <td style="width:33%;border:1px solid black"> {{ k.1 }} </td> <td style="width:33%;border:1px solid black"> {{ k.2 }} </td> </tr> </table> {% endfor %} {% endfor %} Type of res is list and printing res[0][2] - gives Ford, but in table I get - k.0 = A k.1 = d k.2 = a With one for loop I get triple printing of res[0] in k.0/1/2 -
AttributeError: module 'django.contrib.auth' has no attribute 'models'. what am I missing?
when I run the migration in django the terminal says AttributeError: module 'django.contrib.auth' has no attribute 'models'.I'm following lectures in django 1.1 where Im actually using django 2.2. views.py def calicutpara(request): return render(request, 'calicutpara.html') class signup(CreateView): form_class = forms.userCreateForm success_url = reverse_lazy('login') template_name = 'signup.html' app urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'login' urlpatterns = [ path('ktupage/', views.ktupage, name='ktupage'), path('mgcourses/', views.mgcourses, name='mgcourses'), path('calicutcourses/', views.calicutcourses, name='calicutcourses'), path('mgcourses/mgaas/', views.mgaas, name='mgaas'), path('mgcourses/mgpara/', views.mgpara, name='mgpara'), path('calicutcourses/calicutaas/', views.calicutaas, name='calicutaas'), path('calicutcourses/calicutpara/', views.calicutpara, name='calicutpara'), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(),name='logout'), path('signup/', views.signup.as_view(),name='signup'), ] models.py from django.db import models from django.contrib import auth class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class userCreateForm(UserCreationForm): class Meta: fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'E-mail Address' -
Prevent collectstatic from trying to access a database
I have a Dockerfile with a multi-stage build in which I'm trying to run collectstatic to get all the static files and copy them into the final docker image. At this moment I don't have a database to access, but as collectstatic is trying to access one with dummy values, I get an error. In my opinion there should be no need for collectstatic to access a database. I have read through some Issues concerning this and I think that the maintainers of django are not planning on changing this. That's why I need to know if there is any way to prevent this access to a database. Here's what I have: ARG baseImage FROM ${baseImage} AS base USER root ENV DB_HOST="example" \ DB_NAME="example" \ DB_USER="example" \ DB_PASSWORD="example" RUN python app/manage.py collectstatic --skip-checks --noinput --clear \ && node_modules/.bin/gulp compile --destination "/tmp/staticcmp" FROM nginx:1.11 AS cdn COPY docker/cdn/etc/cdn-nginx.conf /etc/nginx/conf.d/default.template COPY docker/cdn/robots.txt /usr/share/nginx/html/robots.txt COPY docker/cdn/bin/ /usr/local/bin/ COPY --from=base /tmp/staticcmp/ /usr/share/nginx/html/static ENV NGINX_ERROR_LOG="/dev/stdout" \ NGINX_ACCESS_LOG="/dev/stdout" EXPOSE 8000 ENTRYPOINT ["docker-cdn-entrypoint"] -
Filter Django ResourceRelatedField's queryset
In our project we are using ResourceRelatedField for a foreign key field in one of our serializers to comply with JSON:API format. This is how it looks: types = ResourceRelatedField( queryset=Type.objects, many=True ) The problem that I have is that I want to exclude some of the items from the queryset of this field so that I don't get all the items from the Type model, but a subset. If I write something like this it doesn't work: types = ResourceRelatedField( queryset=Type.objects.exclude(id=13), many=True ) Didn't find anything related in the documentation. -
trying to change a .mov file to .mp4 when uploading it - python/django
first time asking a question here... so, I have a django web app where people can upload video files. The video file upload just fine and when they are .mp4 files, they can click on them and immediately play them in the chrome browser. However, if the video file is .mov, it forces the user to download the file to their computer before viewing it. I have tried to capture the file before is saves and change the filename from .mov to .mp4 but its not working. form = AddAttachmentForm(request.POST, request.FILES) if form.is_valid(): attachment = form.save(commit=False) attachment.user = student attachment.attacher = self.request.user attachment.date_attached = timezone.now() attachment.competency = competency attachment.filename = request.FILES['attachment'].name if attachment.filename.endswith('.mov'): attachment.filename.replace('.mov','.mp4') attachment.save() -
A field with precision 10, scale 2 must round to an absolute value less than 10^8
I have a django-field total_price in postgres database with version 9.3.11. Here is the current code for it. total_value = models.DecimalField(decimal_places=100, default=0, max_digits=300) I want to convert it to proper 2 decimal place. So I wrote this code total_value = models.DecimalField(decimal_places=2, default=0, max_digits=10) My migration file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('my_table', '0040_my_table_skipped'), ] operations = [ migrations.AlterField( model_name='my_table', name='total_value', field=models.DecimalField(default=0, max_digits=10, decimal_places=2), ), ] When I run command python manage.py migrate It shows me this error A field with precision 10, scale 2 must round to an absolute value less than 10^8. Any idea what is this about ? -
Django app giving error after deployed on Heroku
I have deployed the Django app on heroku and giving the error: OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I have in setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'LP7Website', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432' } } App link is: https://lp7.herokuapp.com/ How to solve..? -
Django search_field
How to solve this error? cause whenever I search the student user I received an error, error admin.py @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') search_fields = ('Student_Users',) def lrn(self, obj): return obj.Student_Users.lrn my models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) -
How to run django project in Aws ec2 ubuntu
I have created a django application and uploaded in to Ec2. I can access the site using public IP only when I run the python manage.py in aws command line. If I close the putty window I am not able to access the site. How can I make sure that the site is available always even if i close the command line / putty. I tried WSGI option but its not working at all. Appreciate your help to give us a solution to run the python applicaiton in AWS -
Are celery tasks and queues interrupted when elastic beanstalk EC2 instances are removed?
I have a Django app running on Elastic Beanstalk in a Multicontainer Docker platform. So each EC2 instance has Docker containers for Django, Celery, RabbitMQ and Nginx. I have concerns regarding celery tasks when an EC2 instance is removed due to an auto-scale event or an immutable deployment. Will current tasks in the celery queue be lost when an instance is removed? Can a running celery task be interrupted on an instance removal? Celery beat schedule (cron) would be called from every new instance launched, causing duplicated calls. I'm curious if anyone else has experience solving the above? Here's a list of some of the solutions I'm thinking about: Change the celery broker to a remote ElastiCache Redis instance. Not sure that would work tho. Use another library to replace Celery which can store the tasks in the DB (e.g. huey or apscheduler). Migrate from celery to AWS SQS + Elastic Beanstalk Worker. That would mean duplicating the same codebase to be deployed to both the current web as well as a worker Elastic Beanstalk. Any other ideas or concerns? -
How to assign query result value by column in django
The output of mysql query in django is shown below. -- views.py -- def result(): cursor = connection.cursor() try: cursor.execute( "select b.date, a.value from t1 a join t2 b on a.id = b.id" result = cursor.fetchall() finally: cursor.close() return result -- result -- ((datetime.date(2019, 4, 25), '8192'), (datetime.date(2019, 5, 25), '8192'), (datetime.date(2019, 6, 25), '8192'), (datetime.date(2019, 11, 25), '8192')) I want to assign a value to a variable like this x = data y = value What should I do? Please let me know. -
pull data from two tables with one query
I want to pull data from two tables with one query. I try with the following code but it doesn't fetch the data from the first table. How do I fix this? ` class DebtFinancialReceivedAmountListAPIView(ListAPIView): permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] def get(self, request): spen = Spending.objects.filter( createdDate__gt=(self.request.query_params.get('startingDate')), createdDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate( spendingAmount=Sum('spendingAmount'), spendingKdv=Sum('spendingKdv'), spendingTotal=Sum('spendingTotal')) result = Debt.objects.filter( paymentDate__gt=(self.request.query_params.get('startingDate')), paymentDate__lt=(self.request.query_params.get('endDate')))\ .aggregate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) return Response(spen, result) ` -
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)