Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password reset email not sending with the addition of a custom template
Trying to get my custom template to display with my password reset email, but it's not working. The email sends, but the custom email template does not render. path('accounts/password-reset/', auth_views.PasswordResetView.as_view( template_name='password_reset.html', html_email_template_name='password_reset_email_template.html', subject_template_name='password_reset_subject.txt' ), name='password_reset'), password_reset_email_template.html: <html> <tr> <td style="color:#333333; font-family: Helvetica, sans-serif;text-align:left; font-size:14px; line-height:20px; padding-bottom:18px;text-align:left;"> {% load i18n %} {% autoescape off %} You're receiving this e-mail because you requested a password reset for account. {% endautoescape %} <p>Follow the link below to reset:</p> <a href="https://domain{% url 'password_reset_confirm' uidb64=uid token=token %}"> Reset Password </a> </td> </html> -
set() argument after * must be an iterable, not NoneType in Django
I have recently implemented a system where users can only submit 3 tags on their posts, and it will tell them that they can't if they try to upload more than 3. (Thanks for helping me do this @minglyu). Whilst this does work, I get this error after trying to resubmit the form with the right amount of tags set() argument after * must be an iterable, not NoneType I am using django-taggit at the moment for tags by the way Here is my forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','group','image','file','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def clean_tags(self): tn = self.cleaned_data.get('tags', []) if len(tn) > 3: raise ValidationError('Invalid number of tags') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['file'].required = False The issue is coming from the clean_tags method. Here is the views.py class PostListView(SelectRelatedMixin,TagMixin,ListView): model = Post hit_count = True template_name = 'mainapp/post_list.html' selected_related = ("user","group") paginate_by = 10 context_object_name = 'posts' queryset = models.Post.objects.all() def get(self,request,): posts = Post.objects.all().order_by('-published_date') users = User.objects.exclude(id=request.user.id) count= User.objects.all().count() friend, created = Friend.objects.get_or_create(current_user=request.user) friends = friend.users.all() group = Group.objects.all() args = { 'users':users, 'friends':friends, 'posts':posts, 'group':group,'count':count } return render(request, self.template_name, args) def get_queryset(self): return … -
Microsoft login page and Django
enter image description here I want to bring the Microsoft login page like the above picture on my Django project. can anybody help me here how to do it? -
two forloop that generates every item using one table row
I have two loops from my python which generates every item with their respective. \html <table> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} </table> \views def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) teachers = SubjectSectionTeacher.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')) roomsched = SubjectRoomSchedule.objects.filter(Subject_Section_Teacher__in=teachers) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType,"teachers":teachers,"roomsched":roomsched}) else: . . . return render(whatever I want) \models class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='grade', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) def __str__(self): suser = '{0.Education_Levels} {0.Courses}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', … -
How do I create a separate model for relating primary keys of two models in a single table?
I have a User model and a Position Model, Where Position and User model both has username and position name as unique key. I want to create a separate table(which will be a relation table) where I can associate each user to their position. This is what I have tried : class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username class Position: name = models.CharField(max_length=20, unique=True) class Emp_position: emp_uname = models.ForeignKey(User, related_name='emp_name', to_field='username', on_delete=models.CASCADE) position_name = models.ForeignKey(Position, related_name='position', to_field='name', on_delete=models.CASCADE) It was working fine until I migrated Position table but when I am adding the relation table i.e Emp_position, I am getting an error : Traceback (most recent call last): File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Position' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Himanshu Poddar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 381, in … -
URL with question mark slug calling incorrect Django view
I have a Django 2.2 project (using the rest framework) where I need to call a view function with a url of the following format: /class/students?date=07092019 and I've set up the following url route to handle this url:path('class/students?date=<str:date>/',StudentsInClassView.as_view() ,name='student'). The corresponding view function has the following definition: class StudentsInClassView(APIView): def get(self, request, date,format=None): For some reason, whenever I go to url, it gets converted to /class/students/?date=07092019 and a different view, with the url path('nba/students/',StudentsView.as_view() ,name='students'), gets called instead. If I remove the "?date=" from the url and just include the actual date, the StudentsInClassView is called as expected. How can I get the "?date=" slug to remain in the url as it is used to call the StudentsInClassView? -
Django Rest Framework endpoint to fetch data from an api and store in postgresql database
I am trying to build an API endpoint to fetch data from https://randomuser.me/api/ fake JSON API. I know Django rest framework very well but not getting how to build api endpoint to fetch data from another api endpoint. Can anyone give me a guideline how to build endpoint to fetch api from another api. I am new in web development THanks and regards -
Django file upload: redirect views keep returning errors
I have been working on this music site in Django, basically just trying to get the upload view to work. When you upload a music file, I want it to redirect to the results page. I have been having real trouble with trying to get the redirect to work and it should be very simple but just has not been working. Any help would be greatly appreciated!! My error: ValueError at /uploads/home/ The view uploads.views.upload didn't return an HttpResponse object. It returned None instead. uploads/views.py (relevant buggy code): def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('uploads:results') else: form = UploadFileForm() return render(request, 'uploads/upload.html', {'form': form}) uploads/urls.py from django.urls import path from . import views app_name = 'uploads' urlpatterns = [ path('home/', views.upload, name='index'), path('<int:audiofile_id>/results/', views.ResultsView.as_view(), name='results'), ] upload.html (the upload template) {% extends 'uploads/base.html' %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-12 col-md-8"> {% for audiofile in audiofiles %} <h1>{{ audiofile.title }}</h1> </div> </div> <div class="row"> <div class="col-lg-12 col-md-8"> <form action="{% url 'uploads:results' audiofile_id %}" method="post" name = "form" enctype = "multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> … -
How to POST image to django rest API
I am not too practiced in handling image files, and I am very confused about posting and handling an image using my django REST API. I am using a python script as client just for testing (will be ios app eventually). Anyone who can help me receive an image file, and save it locally on the server would be greatly appreciated. Client: i = Image.open('image.jpeg') upload = { 'id': 3, 'picture': i } r = requests.post(ip, data=upload, stream=True) print(r.text) Server: class Picture_Upload(APIView): def post(self, request): f = request.data['picture'] return Response(f.content) -
TemplateDoesNotExist only happen on prod ec2 but Templates works on local
I have running on my windows pc a django app with following structure this app also runs locally and works with this settings 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mysql', 'users', 'posts', 'comments', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'chango2.middelware.ProfileCompletionMiddelware', ] libraries: { 'tags': 'tags', } ROOT_URLCONF = 'chango2.urls' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] this app work as expected when its runned locally with python manage.py runserver now i trying to deploy this app on a ec2 , i have configurated the security gropus to allow port 80 **and **8000 for inbound and outbound on ec2 i run with (env) ubuntu@ip-172-31-3-242:~$ gunicorn --bind 0.0.0.0:8000 chango2.wsgi:application app starts listening on port 8000 got the first page but for other link then i recive the the only thing changed between prod and local was ALLOWED_HOSTS = [my ec2 dns] and DATABASES (but that its working) -
Django Model Field - is there anyway to define a field that stores an object
I'm trying to add Django to my react project. Currently, I'm stuck on defining correlating model fields in Django to what I had in React state. This is what my old state looks like (when I stored all the info directly in the state) This is what my new state looks like (when I fetched the data from api and stored it into the state) The reason I want to have "teamBackground", "textColor", "votedUpColor", "votedDownColor" properties is that I want to be able to style each team. I tried defining these properties as CharField and JSONField, but they don't seem to be working. Is there anyway to solve this problem? -
NOT NULL constraint failed: snippets_choice.post_id
am trying to use the POST method here but it is throwing me an error. this is Models.py: from django.db import models class Post(models.Model): post_text=models.CharField(max_length=200) def __str__(self): return self.post_text class Choice(models.Model): post=models.ForeignKey(Post, on_delete=models.CASCADE) choice_text=models.CharField(max_length=200) likes=models.IntegerField(default=0) def __str__(self): return self.choice_text this is serializes.py: from rest_framework import serializers from snippets.models import Post, Choice class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Post fields=['id','post_text'] class ChoiceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Choice fields=['id','choice_text','likes'] this is views.py: from django.shortcuts import render from rest_framework import generics from rest_framework.reverse import reverse from .models import Choice, Post from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from snippets.serializers import ChoiceSerializer, PostSerializer class PostList(generics.ListCreateAPIView): queryset=Post.objects.all() serializer_class=PostSerializer name='post-list' class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset=Post.objects.all() serializer_class=PostSerializer name='post-detail' class ChoiceList(generics.ListCreateAPIView): queryset=Choice.objects.all() serializer_class=ChoiceSerializer name='choice-list' class ChoiceDetail(generics.RetrieveUpdateDestroyAPIView): queryset=Choice.objects.all() serializer_class=ChoiceSerializer name='choice-detail' class ApiRoot(generics.GenericAPIView): name='api-root' def get(self, request, *args, **kwargs): return Response({ 'posts': reverse(PostList.name, request=request), 'choices': reverse(ChoiceList.name, request=request), }) urls.py: urlpatterns=[ path('post-list/', views.PostList.as_view(), name='post-list'), path('post-list/<int:pk>/', views.PostDetail.as_view()), path('choice-list/', views.ChoiceList.as_view(), name='choice-list'), path('choice-list/<int:pk>/', views.ChoiceDetail.as_view()), path('',views.ApiRoot.as_view(),name=views.ApiRoot.name), ] when I try to post: { "id":3 "choice_text": "random text", "likes": 0 } I got this error: IntegrityError at /choice-list/ NOT NULL constraint failed: snippets_choice.post_id if am providing the id, why it is throwing an error? even in Postman, it's asking me to put 'choice_text', … -
How to render db data from consumer into template using django channels
I'm in the process of upgrading my application to be able to update my site in real time using Django Channels. I have a dashboard that would render the DB values from my view into the template tags i've added on my template. Now I want to do this but using Django Channels instead. So i've created a consumer, but i'm not sure how to receive the data inside my template. Previously I would just call {% for a in taskposted %} {{ a.TaskType }} {% endfor %} inside my template, but how do I access this using channels? consumer.py import asyncio import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from dashboard.models import Usertasks class DashboardConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept", }) user = self.scope['user'] tasks = await self.getTasks(user) print(tasks) async def websocket_receive(self, event): await self.send({ "type": "websocket.send", "text": event["text"], }) async def websocket_disconnect(self, event): print("Disconnected", event) @database_sync_to_async def getTasks(self, user): return Usertasks.objects.all().filter(user=user).filter(TaskStatus__in=["Computing", "Failed", "Waiting", "Finished",]) dashboard.html <script> var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log("message", e) console.log(e.data) } socket.onopen … -
Reset Site name in cookiecutter
How can I change my site.name after i've been working in my project for a while? I've looked under django.contrib.sites but didn't find anything except for a migration that has set the name. -
Invalid credentials on Django social auth
I am using Django social_django and rest_framework_social_oauth2 for authentication in my app. I have successfully integrated Facebook. However I am facing a challenge integrating GoogleOAuth2. For starters I have these in my django settings INSTALLED_APPS = [ ...... 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ..... ] AUTHENTICATION_BACKENDS = ( # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Google SSO 'social_core.backends.google.GoogleOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) # Google Config SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] My view basically does serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) if isinstance(backend, BaseOAuth2): access_token = serializer.data.get('access_token') user = backend.do_auth(access_token) and the serialiser is class SocialSerializer(serializers.Serializer): """ Serializer which accepts an OAuth2 access token and provider. """ provider = serializers.CharField(max_length=255, required=True) access_token = serializers.CharField(max_length=4096, required=True, trim_whitespace=True) The way I retrieve the token is via android as below gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(Scope(Scopes.PROFILE)) .requestServerAuthCode(serverClientId) .requestEmail() .build() mGoogleSignInClient = GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso!!) .build() val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleSignInClient) startActivityForResult(signInIntent, RC_SIGN_IN) /// Then at the callback point val account : GoogleSignInAccount? = completedTask.getResult(ApiException::class.java) val authCode = account?.serverAuthCode val call = apiService!!.socialLogin(SocialAuthLoginDto(provider = "google-oauth2", access_token = authCode)) processSignInCall(call) The client can successfully retrieve and post the token … -
Specify model names in select_for_update instead of relations
I would like to specify the table/model names instead of the relations in the QuerySet's model. Reason being the relation I'm linking to is a multi-table inheritance model. When I use select_for_update and provide relations using the of parameter, only the parent tables are "selected for update". Consider the piece of code: order = Order.objects.filter(uuid=order_uuid).prefetch_related( Prefetch( lookup='items', queryset=items ) ).select_related('outlet').select_related('user').select_related('outlet__group') \ .select_for_update(of=('self', 'outlet')) Here, outlet is a relation defined by outlet = models.ForeignKey(Outlet, on_delete=models.PROTECT, related_name="orders") Both the Order as well as Outlet models are sub-models to Transaction and Cashless models (which are situated in another Django app) By logging PSQL, this is the query that is being executed: SELECT "payment_gateway_transaction"."uuid", "payment_gateway_transaction"."ref_number", "payment_gateway_transaction"."shop_id", "payment_gateway_transaction"."user_id", "payment_gateway_transaction"."timestamp", "payment_gateway_transaction"."amount", "payment_gateway_transaction"."payment_method", "payment_gateway_transaction"."transaction_status", "payment_gateway_transaction"."service", "cashless_order"."transaction_ptr_id", "cashless_order"."token", "cashless_order"."outlet_id", "cashless_order"."order_status", "cashless_order"."order_start_time", "cashless_order"."order_end_time", "cashless_order"."order_collect_time", "cashless_order"."order_review", "cashless_order"."order_ratings", "authentication_user"."id", "authentication_user"."password", "authentication_user"."last_login", "authentication_user"."is_superuser", "authentication_user"."email", "authentication_user"."student_id", "authentication_user"."first_name", "authentication_user"."last_name", "authentication_user"."date_joined", "authentication_user"."ip_address", "authentication_user"."mac_address", "authentication_user"."location", "authentication_user"."phone_number", "authentication_user"."total_spent", "authentication_user"."is_banned", "authentication_user"."needs_student_id", "authentication_user"."generated_at", "authentication_user"."verify_token", "authentication_user"."is_active", "payment_gateway_shop"."uuid", "payment_gateway_shop"."name", "payment_gateway_shop"."location_id", "payment_gateway_shop"."location_coords", "payment_gateway_shop"."tax_applicable", "payment_gateway_shop"."percentage_tax", "payment_gateway_shop"."gst_number", "payment_gateway_shop"."open", "payment_gateway_shop"."active", "payment_gateway_shop"."group_id", "cashless_outlet"."shop_ptr_id", "cashless_outlet"."start_time", "cashless_outlet"."end_time", "cashless_outlet"."break_start_time", "cashless_outlet"."break_end_time", "cashless_outlet"."items_limit", "cashless_outlet"."image", "cashless_outlet"."description", "cashless_outlet"."on_cashless", "cashless_outlet"."ratings", "cashless_outlet"."latest_token", "auth_group"."id", "auth_group"."name" FROM "cashless_order" INNER JOIN "payment_gateway_transaction" ON ("cashless_order"."transaction_ptr_id" = "payment_gateway_transaction"."uuid") INNER JOIN "authentication_user" ON ("payment_gateway_transaction"."user_id" = "authentication_user"."id") INNER JOIN "cashless_outlet" ON ("cashless_order"."outlet_id" = "cashless_outlet"."shop_ptr_id") INNER JOIN "payment_gateway_shop" ON ("cashless_outlet"."shop_ptr_id" = "payment_gateway_shop"."uuid") INNER … -
Add values to context for render in Django
I have the following code inside a view: return render( request, 'home/index.html', { 'mobile':False, 'title':'Home', #'year': datetime.now().year, } ) So I used to always calculate the year in every view. I had to since it was needed in my layout.html Because of that I thought it would be a good idea to extract this calculation so I don't have to write it in each view specifically. I tried this using the following middleware: from datetime import datetime from django.utils.translation import gettext as _ def get_vars(get_response): def middleware(request): request.year = datetime.now().year return get_response(request) return middleware But it seems that the year variable is not added the same way it would be in the view. So my question is: How can I implement this functionality?` If not with a middleware how can I otherwise do it? -
drf-yasg provides wrong paths to URIs
I need to display multiple Swagger pages with grouped endpoints. One of my paths supplies mobile app, another supplies web client. URL patterns are kept in 2 different urls.py accordingly. To generate swagger specification for those I'm initializing 2 separate schema_views for each urls.py file like this: from api_mobile.urls import urlpatterns as mobile_patterns from api_web.urls import urlpatterns as web_patterns mobile_schema_view = get_schema_view( openapi.Info( title="Mobile API", default_version='v3', ), public=True, permission_classes=(permissions.AllowAny,), patterns=mobile_patterns, ) web_schema_view = get_schema_view( openapi.Info( title="Web API", default_version='v1', ), public=True, permission_classes=(permissions.AllowAny,), patterns=web_patterns, ) urlpatterns = [ path( 'api/mobile/docs', mobile_schema_view.with_ui('swagger', cache_timeout=0), name='mobile-schema-ui' ), path( 'api/web/docs', web_schema_view.with_ui('swagger', cache_timeout=0), name='web-schema-ui' ), path('api/mobile/v3/', include('api_mobile.urls'), name='mobile_urls'), path('api/web/v1/', include('api_web.urls'), name='web_urls'), ... ] Where mobile_patterns and web_patterns are just a list of url patterns. If I open http://localhost:8000/api/mobile/docs or http://localhost:8000/api/web/docs I do see correctly generated schema for both lists of patterns, yet if I try to do a request directly from swagger specification page all endpoints return 404 error – they all try to do a request without providing full path to endpoint. So if I do a request to any view from mobile endpoints swagger tries to do a request at http://localhost:8000/some_mobile_url/ instead of http://localhost:8000/api/mobile/v3/some_mobile_url/ And situation is the same for another schema: Swagger wrongly requests … -
Filter and get VS Q()
Is there any performance differences between using: Transaction.objects.filter(profile=request.user).get(id=transaction_id) VS Transaction.objects.filter(Q(profile=request.user) & Q(id=transaction_id)).first() And which one should be used over the other? -
OperationalError at /admin/login/ no such table: django_site
When I try go to the admin/login I get error. OperationalError at /admin/login/ no such table: django_site settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ] SITE_ID = 1 migrations account [X] 0001_initial ... admin [X] 0001_initial ... auth [X] 0001_initial ... contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique console ./manage.py makemigrations No changes detected Traceback How to fix it? Thanks. -
How can I convert a dataframe to csv and save it to return it?
I'm reading a .xlsx file and converting it to .csv but I need to return it as a .csv on a because I don't have access to the path where it should be storage. I'm only have been able to return it as a data frame. Any help will be really appreciated. Thanks. import pandas as pd def excel_to_csv(myfile): print(myfile) data_xls = pd.read_excel(myfile, index_col=None) data_xls.to_csv(encoding='utf-8', index=False) return(myfile) -
Character encoding issue when using Python3/mysqlclient to retreive data encoded in latin1
I'm running into a character encoding issue when retrieving data from an older database that is using latin1 encoding. The problem is occurring when I try to retrieve characters from the database that fall in the \x80 to \x9f range, which is the range that is different between MySQL's latin1 (aka windows-1252 in Python) and the official latin1 (ISO-8859-1). This is the stack that I'm using: MySQL database server version 5.1 with latin1 encoding at the column level and latin1-swedish-ci collation at the table level. Django version 2.2 using Python3 and mysqlclient version 1.4.4. As an example, I'm trying to retrieve the word "Isn't" from the database where the apostrophe is encoded as \x92. If I don't pass a charset to the mysqlclient connection through Django settings, I get the error "'utf-8' codec can't decode byte 0x92 in position 5: invalid start byte". If I pass latin1 as the codec to the connection, there is no error but the word renders to the page as "Isn t", with blank space where the apostrophe should be. When I open up a separate python shell session and try the connection from the python command line, the result is "Isn\x92t". >>> import MySQLdb … -
Trouble extracting multiple HTML DOM elements for AJAX with Django
I'm trying to implement a feature on a web app where I have a menu of pizzas, and the price listed on each card (feature taken from Bootstrap) dynamically updates depending on the style (regular/sicilian), size (small/large) and name (cheese/special) of pizza selected. I'm using a loop to create all the cards by querying the database using ORM in the backend, which takes all existing pizzas the restaurant owner adds, and makes a menu item for each one. Then, I'm aiming to extract the name, style, and size selections for each, and give a dynamic render of the price of that specific type of pizza in the price area of the card, using AJAX, before implementing the checkout functionality whereby a user buys that pizza. The problem is mainly that I'm unsure how to extract the name, style, and size selections given that the cards are implemented using a templating loop, and also I think there are a few small errors littered through my AJAX/backend. But I suspect the solution would be something to do with Javascript's ForEach() after I extract an array of the styles from the cards? I really don't know how I'd go about proceeding. My code … -
Avoid nested objects when using nested serializers
I have two models, one contains the other in a foreignKey relationship, I wanted to make an API that would return the combine of these two models, so I attempted to use nested Serializers to add the related model as well, but the data are not all on the same level, the related models is a object inside the first. Here are the Models class ModelOne(models.Model): last_counter = models.IntegerField() class ModelTwo(models.Model): model_one = models.ForeignKey(ModelOne, on_delete=models.CASCADE) category = models.CharField(max_length=64) counter_type = models.CharField(max_length=32) Here are the serializers class ModelOneSerializer(serializers.ModelSerializer): class Meta: model = ModelOne fields = "__all__" class ModelTwoSerializer(serializers.ModelSerializer): model_one= ModelOneSerializer(read_only=True) class Meta: model = ModelTwo fields = "__all__" This would return from the API in the form of { "category" : ..., "counter_type" : ..., "model_one" : { "last_counter" : ... } } But I don't want the response to be like that, I want it more like this { "category" : ..., "counter_type" : ..., "last_counter" : ..., } Is there a way to achieve this through serializers? -
Nested serializers: Could not resolve URL for hyperlinked relationship using view name
I've looked up this error but the answers posted earlier aren't working for me. I'm trying to set up nested serializers/views with HyperLinkedIdentityFields in Django Rest Framework but I'm getting the following error: Could not resolve URL for hyperlinked relationship using view name "customers-report-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I have the following setup: urls.py urlpatterns = [ path('<pk>/reports/<report_nr>/', ReportApiDetail.as_view(), name='customers-report-detail'), path('<pk>/reports/', ReportApiList.as_view(), name='customers-report-list'), path('<pk>/', CustomerApiDetail.as_view(), name='customer-detail'), path('', CustomerApiList.as_view(), name='customer-list'), ] views.py class CustomerApiList(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerListSerializer class CustomerApiDetail(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerDetailSerializer class ReportApiList(generics.ListAPIView): serializer_class = ReportListSerializer queryset = Report.objects.all() def get_queryset(self, *args, **kwargs): pk = self.kwargs['pk'] report_nr = self.kwargs['report_nr'] return self.queryset.filter(customer_id=pk, report_nr=report_nr) serializers.py class ReportDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ['id', 'customer_id', 'report_nr', 'title', 'date_created', ] class ReportListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ['url',] class CustomerDetailSerializer(serializers.ModelSerializer): reports = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='customers_report_detail' ) class Meta: model = Customer fields = ['pk', 'name', 'reports',] class CustomerListSerializer(serializers.HyperlinkedModelSerializer): # reports = serializers.SerializerMethodField('get_customer_orders') class Meta: model = Customer fields = ['url', 'pk', 'name', ]