Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', ] -
This code is returning the error 'local variable 'name' referenced before assignment'.I am trying to keep a form and formset together
I am trying to make a form and formset work together which are not related to each other.Any suggestions if there are easy solutions to this? def resume(request): form=ResumeForm(request.POST) ExperienceFormSet=formset_factory(Experience) formset=ExperienceFormSet(request.POST,request.FILES) print(form.is_valid) if request.method=='POST': if form.is_valid() and formset.is_valid(): name=request.POST.get('name') email=request.POST.get('email') phone=form.cleaned_data['phone'] objective=request.POST.get('objective') branch=request.POST.get('branch') course=request.POST.get('course') course_total=course+' in '+branch department=request.POST.get('department') other_link=request.POST.get('other_link') for f in formset: cd=f.cleaned_data companyName=cd.get('companyName') print(companyName) else: form=ResumeForm() ExperienceFormSet=formset_factory(Experience) formset=ExperienceFormSet() return render(request,'resume.html',{'name':name,'email':email,'phone':phone,'objective':objective,'course_total':course_total,'department':department,'other_link':other_link}) -
How to add custom css to Bootstrap/Django files
I am trying to add a custom css snippet into my code for my homepage(index.html)but am new to bootstrap/css and not sure which file to add the code to. So far, I've tried adding the snippet to a custom.css file within the same directory as my html files but nothing is changing. Would I instead add this to index.html file? Can you even add css to an html file? Example of code snippet im trying to add: body { background: url('https://source.unsplash.com/twukN12EN7c/1920x1080') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } -
Django: how to specify `include_blank=False` in `modelform_factory` using `formfield_callback`?
I am using the django.forms.modelform_factory() function. Some of the database fields are IntegerFields with choices, so Django defaults to using a django.forms.TypedChoiceField that has a blank choice ("--------------"). I'm using the RadioSelect widget, so it's redundant to have a blank choice. How do I get rid of the blank choice? (I'm answering my own question, but of course if you have a better answer, feel free to share!) -
Unable to add two foreign keys to the user model in django
I have a user model which I have extended to store extra information. Now I have a department table which has two keys(foreign) which will be related to the columns in the user table. But I am getting an error. This is what I have tried models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. 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, related_name='usernames', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Department(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, unique=True) manager = models.ForeignKey(User, blank=True, null=True, related_name='manager_usernames', on_delete=models.DO_NOTHING) tech_lead = models.ForeignKey(User, blank=True, null=True, related_name='usernames', on_delete=models.DO_NOTHING) Error message ERRORS: users.Department.tech_lead: (fields.E304) Reverse accessor for 'Department.tech_lead' clashes with reverse accessor for 'Profile.manager_username'. HINT: Add or change a related_name argument to the definition for 'Department.tech_lead' or 'Profile.manager_username'. users.Department.tech_lead: (fields.E305) Reverse query name for 'Department.tech_lead' … -
Android device can not connect Django websocket
I built an app with a chat function using Django channels, everything works fine, I can connect to it from iOS simulator, iOs Device, even with an Android simulator, but when I launch it on an actual android device (Huawei Pro) It seems it does not want to connect. What can cause an issue like this? Should I implement something in my Android code or is it a specific problem with Huawei? I use JavaScript's WebSocket to connect to it.