Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save extra fields to django model apart from the fields which were present in django forms using the form.save method
I have a Django model with few fields, In the django forms which is created using that django models. While using the forms.save method I also want to save the extra fields which were not present in Django forms but present in django models. models.py class NewProvisionalEmployeeMail(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), (3, ("Contractor")), (4, ("Intern")) ) PAY_CHOICES = ( (1, ("Fixed")), (2, ("Performance Based")), (3, ("Not Assigned")), ) POSITION_CHOICES = () for i, name in enumerate(Position.objects.values_list('position_name')): POSITION_CHOICES += ((i, name[0]),) email = models.EmailField(max_length=70, null=False, blank=False, unique=False) token = models.TextField(blank=False, null=False) offer_sent_by = models.CharField(max_length=50) position_name = models.IntegerField(choices=POSITION_CHOICES, null=True, blank=True) accepted = models.BooleanField(default=False) name=models.CharField(max_length=30) user_name=models.CharField(max_length=30) pay = models.IntegerField(default=0) title = models.CharField(max_length=25, null=True, blank=True) pay_type = models.IntegerField(choices=PAY_CHOICES, default=3) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) def __str__(self): return str(self.offer_sent_by) +" to " + str(self.email) def clean(self): if(NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).exists()): NewProvisionalEmployeeMail.objects.filter(email=str(self.email)).delete() def save(self, **kwargs): self.clean() return super(NewProvisionalEmployeeMail, self).save(**kwargs) If you see it has following fields : email, token, offer_sent_by, position_name, accepted, name, user_name, pay, title, pay_type, emp_type. Now I only want the following fields in my forms : email, position_name, name, user_name, pay, title, pay_type, emp_type and not token and offer_sent_by whose values will be determined in my views.py using some logic. forms.py class NewProvisionalEmployeeMailForm(ModelForm): class … -
Django Rest Framework: How to include application namespace when defining HyperlinkedRelatedField
My django application has a namespace defined in the app_name variable, in urls.py. It seems like this namespace needs to be specified in the view_name argument of HyperlinkedRelatedField for HyperlinkedRelatedField to successfuly retrieve the relevant url router. To avoid repeating this namespace, I'd like to import the namespace into the serializers module. However I get an import error when doing so. extract from my app/urls.py: ... app_name = 'viewer' ... api_router = DefaultRouter() api_router.register('year', api_views.YearViewSet, 'api_year') api_router.register('month', api_views.MonthViewSet, 'api_month') ... urlpatterns = [ ... path('api/', include(api_router.urls)), ] api_views.py ... class YearViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): queryset = Year.objects.all().order_by('-date') serializer_class = YearSummarySerializer lookup_field = 'slug' def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = YearDetailSerializer(instance=instance) return Response(serializer.data) @action(detail=True) def months(self, request, *args, **kwargs): serializer = YearMonthsSerializer(instance=self.get_object(), context={'request': request}) return Response(serializer.data) ... serializers.py ... from .urls import app_name ... class YearMonthsSerializer(serializers.HyperlinkedModelSerializer): month_set = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name= app_name + ':api_month-detail', lookup_field='slug' ) class Meta: model = Year fields = ['month_set'] ... When I manually enter the app_name ('viewer') the serializer works as intended, however when I try to import app_name from .urls, python throws an ImportError ImportError: cannot import name 'app_name' from 'cbg_weather_viewer.viewer.urls' I don't understand why I get this import error as … -
How would you incorporate Java into a Python Application to make an API request?
I'm building a python web app using the Django framework, but I've hit a problem. The Amazon API I want to use uses Java and doesn't support Python. How would I do this? I'm thinking of creating and API to send JSON data from my Python app to another API written in Java to make the request from the Amazon API and then send it back like that. New to all this so I don't know if that would work? Seems logical to me? How would you go about this, at the moment I've never touched Java. -
How to set gis_enable to True
I have a geoDjango setup with postgresql/postgis and everything works fine. Now I try to install django-raster but it fails on migration. The error is Raster fields require backends with raster support. It happens because connection.features.gis_enabled is set to False in site-packages/django/contrib/gis/db/models/fields.py How to set it to True ? -
Time Spent by User on a Particular WebPage/Form - Django
I want to track the time spent by a user on a particular Django webpage and upload it to the admin. Can this be done with the Python time module? If so how can I do it? I am also open to other suggestions, but since I am a beginner I would prefer them to be simple. Thanks in advance. -
How to query complicated query with json_field
In my django app I have the following model hirarchy: Project BuildingCollection (belongs to Project) Building (belongs to BuildingCollection) SpecificValue (belongs to Building) The SpecificValue model has a JSON Field with lots of keys and values, like {1:value2, 2: value2, 3:value3.....}. The SpecificValue model also has a choice field which has 3 choices of types. I am trying to query the following through the URL which looks like so: path('blbla/<str:project>/<str:type>/<str:key>/', blbla.as_view()) In pseudocode I want to query this: Give me all buildings of the most recent BuildingCollection of the project passed in my URL. Then give me all the SpecificValues of these buildings, but only those which type was passed in the URL. And finally give me from all these SpecificValues just the values to the specified key within the JSON field. Then I want to write it into a dictionary saying: {"Building1" : valueofJSONField, "Building2" : valueofJSONField } I hope I am clear in what I am saying. I am trying this with the following (overwriting the get method of REST APIView) class MyClass(APIView): def get(self, request, **kwargs): project = kwargs.get('project') type = kwargs.get('type') key = kwargs.get('key') building_group_most_recent = BuildingCollection.objects.filter( project__project_name=project).order_by('-creation_date').first() #I get mostrecent buildings = building_collection_most_recent.buildings.all() ##all buildings … -
how to create 2 admin users in django where each user will administer only the users he creates?
I need to create more than 1 admin user who can administer roles/permissions to only the users he creates in django.This admin should be able to see only the users he creates and not the users created by another user. In short I wish to use the django as a SaaS model for my customers, where he can administer his employees/users only.Is this possible and how exactly can this be implemented? -
The current path, account/ active/muSxcXQedffNqDxt/, didn't match any of these
error picture Why it didn't match the url 7? urls.py: path('active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name='active_user'), views.py: class ActiveUserView(View): def get(self,request,active_code): users = UserProfile.objects.filter(code=active_code) if users: users.is_active = True users.save() else: users.delete() return HttpResponse('Fail!Register Again!') return HttpResponseRedirect(reverse("account:user_login")) -
How do I redirect admin login to a custom view and redirect them back to the admin dashboard after they have finished with my custom view
The custom view is going to be my own version of 2 factor authentication (I Know django-otp exists but I am doing this to challenge myself and learn). I am unaware of how to change the admin login redirection and where I should redirect using HttpResponseRedirect so that they go to the admin dashboard after they are done. As always, I am greatful for all your suggestions! Note: I am using django 2.2 with python 3.6 -
How integrate mobile app and web app for authentication?
I'm new in android and django. Now, my team is building a chat application for android while other team is developing for the web. I want to authenticate user when login to web. So, when user sign in to the web using phone number, it will show such as a pop up at the mobile app that contain of verification code. User must put the verification code to the web app so that he/she can chatting from web (like pc version). Anybody know what tool or others that can help us to integrate mobile app and web app authentication like firebase phone authentication but not through sms? Thank's before -
Django POST Method not working Onyl getting GET method even form submit as well
I am trying t o run my django form but everytimeit isgoing as GET Method even aftersubmitiing the form as well it is getting GET. I wa looking for solution long time but no luck.. here it is server log from vs code [31/Oct/2019 16:15:13] "GET /static/bootstrap.min.js.map HTTP/1.1" 404 1684 [31/Oct/2019 16:15:13] "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1687 <<<<<< THIS IS GET METHOD >>>>>>>>>>> [31/Oct/2019 16:15:14] "GET /forgotpassword/ HTTP/1.1" 200 1808 [31/Oct/2019 16:15:14] "GET /static/bootstrap.min.js.map HTTP/1.1" 404 1684 [31/Oct/2019 16:15:14] "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1687 [31/Oct/2019 16:15:17] "POST /successforgotpassword/ HTTP/1.1" 200 286 This is my models.py from django import forms class ForgotPasswordForm(forms.Form): mail = forms.EmailField(label="EMAILL - ID", label_suffix="*", max_length=50, min_length=4, widget=forms.EmailInput( attrs={"class": "form-control", "placeholder": "Enter Email Address"})) def clean_mail(self): passed_data1 = self.cleaned_data.get("mail") passed_data2 = self.cleand_data["mail"] print(passed_data1, passed_data2) req_data = "abc@gmail.com" if passed_data1 == req_data: raise forms.ValidationError("boss no gmail , why!!!") if passed_data1 == "": raise forms.ValidationError("boss no gmail , why!!!") return passed_data1 This is my forgotpassword.html <body> <div class="container" style="margin-top: 100px;"> <form action="/successforgotpassword/" method="POST" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <div class="jumbotron boxing"> <p style="text-align:center; background-color: rgb(246, 250, 8); color: rgb(250, 19, 19); font-size: 18px;"> Please provide your valid email address , We are going to send mail to mentioned email address … -
Django filter by hour of day when timezone info stored in database
With the following model structure: class Place(models.Model): ... timezone = TimeZoneField() # Defined in a package called django-timezone-utils ... class Session(models.Model): ... place = model.ForeignKey(Place, ...) created = models.DateTimeField(auto_now_add=True) # Saved in utc ... I want to get all sessions that are created inside 10th hour of day. Basic approach to this is: Session.objects.filter(created__hour=10) But with this, as expected, results are filtered by UTC time. How can I get Sessions objects that are created inside the 10th hour of day, in the timezone of the Place they are connected to? Note that there could be sessions made on different Places with different timezones, but I want to get the sessions that are created inside the 10th hour of day in their local timezones. Something like annotating each result with created time in local timezone, and then filtering on that annotated value might work, but I do not know how can I build that annotation -
SELF JOIN queryset on joined table in Django?
I want to make a self join on an joined table. I have a queryset: paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type','deal__service', 'deal__service__contractor').order_by('-id') This is a fragment from a table payment_source. Fields that contain bank_card joined with Transaction, but bank_card_details is not. They have same payer_id. It is necessary that these two lines are combined into one. How i can do this? Models.py class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) class Meta: managed = False db_table = '"processing"."transaction"' class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) # payer_id = models.BigIntegerField(blank=True, null=True) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = '"processing"."payer_payment_source"' -
How to specify the many to one models in django?
I'm trying to link two models: Department and User. They have a many-to-one relation. A department can have only admin (User) and a department can have many users. A User can only be in one department. Here is my code class Department(models.Model): admin = models.ForeignKey("applications.User", blank=True, null=True, on_delete=models.SET_NULL) class User(AbstractUser, models.Model): username = models.CharField(max_length=32, unique=True) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name="members") But I'm having this error: ERRORS: applications.Department.admin: (fields.E303) Reverse query name for 'Department.admin' clashes with field name 'User.department'. HINT: Rename field 'User.department', or add/change a related_name argument to the definition for field 'Department.admin'. I need to keep attributes naming as is. How to properly fix and model the relation between the tables? Is django assuming that Department may have many admins? -
Django multiple clients deployment solutions
I am building a Django app where there are several "user spaces" or "client domains". I was wondering how I could separate each clients from accessing other's data ? So far I have come up with several options : Distribute one project per client with their own database Keep one database and one django running (two options) a) Add some top level table with some ID to be referenced in each model. But then how do I restrict someone from impersonnating someone else's ID and access their data ? b) Build some Authorization layer on top of requests using a header or some query param to help discriminate which data the user can acces (but I don't really know how to do so) What is the state of the art in the domain of multiple clients using a same Django app ? Are my solutions appropriate and if so, how do I implement them ? I have seen few related posts / articles on internet so I'm resorting to ask here. Thanks in advance ! -
Checking if an M2M field is empty or not in Django
I have the following models: class Pizza(models.Model): toppings = models.ManyToManyField(Topping) has_toppings = models.BooleanField(default=False) def check_if_there_are_toppings(self): if len(self.toppings.all()) > 0: self.has_toppings = True @receiver(m2m_changed, sender=Pizza.toppings.through) def toppings_changed(sender, instance, **kwargs): instance.check_if_there_are_toppings() instance.save() What I want to do is update the has_toppings field whenever the toppings length is more than 0. What would be the correct way to do this? Thanks for any help. -
Python Django Forms and models
guys i have problem about django forms when post to my database here my code : forms.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') models.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') so the problem is when i deactivate "nama_depan" in forms.py its can save to models database when i activate it cant save to models database anyone know it ty ;D -
Efficient method to get all many to many objects from queryset
I have models similar to the below: class Tag(models.Model): text = models.CharField(max_length=30) class Post(models.Model): title = models.CharField(max_length=30) tags = models.ManyToManyField(Tag) A Post can have many Tags and Tags can be associated with many Posts. What I need is to get a list of all posts along with all the tags associated with each post. I then create a Pandas DataFrame from that data. Here is how I am currently doing it: qs = Post.objects.all().prefetch_related('tags') tag_df = pd.DataFrame(columns=["post_id", "tags"]) for q in qs: tag_df = tag_df.append( { "post_id": q.pk, "tags": list(q.tags.all().values_list("text", flat=True)), }, ignore_index=True, ) post_df = pd.DataFrame(qs.values("id", "title")) final_df = post_df.merge(tag_df, left_on="id", right_on="post_id") The result is correct in terms of the data I require. The problem is how incredibly inefficient it is and the number of queries that run even though I'm using prefetch_related. It appears that a query is hitting the database for each iteration of the loop. Is there a better, more efficient way to do this (possibly without loops)? All I need in the end is a dataframe that contains all the posts along with a column which has a list of the tags for each post. -
Django: DRF and surrogates
I have a weird error from production related to utf-8 and surrogate pairs. Bellow the code to reproduce the issue(for simplicity I present everything in one file and omit some unnecessary details) class User(models.Model): username = models.CharField('Username', max_length=255,) class Meta: app_label = 'users' class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['username'] class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer def test_create_user_and_set_password(django_app): response = django_app.post_json( reverse('users-list'), { 'username': '\ud83d', } ) assert response.status_code == 201 assert models.User.objects.count() == 1 as result of running the test I receive an error(the same as in production): def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 0: surrogates not allowed How should I handle such problems? My knowledge about encoding is limited but from common sense it obvious that I'm not the first one who discover such problem. -
Django:: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed
settings.py INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', ] # Auth AUTHENTICATION_BACKENDS = [ 'conf.backends.AuthBackend', ] AUTH_USER_MODEL = 'accounts.User' accounts/models.py class User(AbstractUser): class Meta: db_table = 'accounts_users' email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) provider = models.CharField(max_length=10, null=True) verified_email = models.BooleanField(default=False) group_permission_id = models.IntegerField(null=True) objects = MyUserManager() error log Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 165, in get_model return self.models[model_name.lower()] KeyError: 'user' i suddenly find this error. why get this error? full error log Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1056139d8> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 165, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 165, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 207, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 168, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File … -
How to fix 'Specifying a namespace in include() without providing an app_name '
I am facing with the problem of setting the app_name attribute in the included module. Despite the fact that I have seen similar answers on how to fix it, I had not found something that works for me. here is my urls.py from django.conf.urls import url,include from django.contrib import admin from intranet import views,forms from django.contrib.auth import views as auth_views from django.conf import settings from rest_framework import routers from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import reverse router = routers.DefaultRouter() router.register(r'pharmakeia', views.PharmakeiaViewSet,base_name='pharmakeia') router.register(r'doctors', views.DoctorsViewSet,base_name='doctors') router.register(r'new-pharmakeia', views.VriskoViewSet,base_name='new-pharmakeia') router.register(r'new-all-pharmakeia', views.VriskoAllViewSet,base_name='new-all-pharmakeia') views.json_data,base_name='test_pharmakeia') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rest/', include(router.urls, namespace='rest')), url(r'^api-auth/', include(rest_framework.urls, namespace='rest_framework')), I tried to declare an app_name variable app_name="intranet" and then fix the urls containing include function like below url(r'^rest/', include((router.urls,app_name), namespace='rest')), url(r'^api-auth/', include(('rest_framework.urls',app_name), namespace='rest_framework')), I face up a new problem "ModuleNotFoundError: No module named 'router' "despite the fact that I have already defined rooter here is my output from command line self._target(*self._args, **self._kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in … -
Heroku build React app before deploying through Django
I successfully deployed my Django project to Heroku. But I want to be able to automatically build React before deploying. The React app is served through Django, so I have the bundled files of React in my templates and static folders of the Django app. The project structure looks something like this: react/ build/ components/ App.js package.json ... django/ templates/ static/ ... Procfile requirements.txt Pipfile I have both the React and Django projects in the same repository and I want to run npm run build automatically before Django is deployed. I set up the build script to move the bundled files from React to Django. From what I've read, I need to add the NodeJS buildpack, but I don't know how to set it up to run before the Python buildpack. Basically, the NodeJS process should just build my React app and then terminate. After that, the Python process should start up and deploy the Django project. One solution to do this would be to use Docker and deploy that image to Heroku. But, is there an easier way? -
Apache kafka producer not sending messages
I am using kafka-python in a django project. Initialised the producer in settings.py file. Calling producer.send is not sending the messages. Earlier my producer was initialised in a function everytime and I was using producer.send().get(timeout=1) to send messages and it worked fine. Now I have changed the initialisation to settings file and removed .get() while calling send and it is not working. Old working code below: In module_x.py: from kafka import KafkaProducer def my_func(): KAFKA_CONNECTION = KafkaProducer(bootstrap_servers=CONFIGS.KAFKA_URL) producer = KAFKA_CONNECTION producer.send(topic, key=key, value=json.dumps(data)).get(timeout=1) Changed code below: Now changed the initialisation to settings file to avoid initialisation everytime my_func is called. In settings.py: KAFKA_CONNECTION = KafkaProducer(bootstrap_servers=CONFIGS.KAFKA_URL) In module_x.py: from django.conf import settings def my_func(): producer = settings.KAFKA_CONNECTION producer.send(topic, key=key, value=json.dumps(data)) Note that I even tried with .get(timeout=1) on send but I was getting Kafka.TiemoutError Do I have to use producer.flush() after producer.send or use linger_ms in send. ? -
Connect with a default admin user in Django 2.0
I am trying to remove the authentication page and allow the connected user to be admin by default. It may be possible to do but because I am new with Django, I cannot find a solution to it... I tried to do something like that in a file called "default_auth.py": class User: is_superuser = True is_active = True is_staff = True id = 1 pk = 1 User.has_module_perms = True User.has_perm = True class Middleware(object): def __init__(self, get_response): self.response = get_response def __call__(self, request): request.user = User() return self.response(request) Then I saw on google that I need to comment this line: 'django.contrib.auth.middleware.AuthenticationMiddleware' and replace it with: 'myProject.default_auth.Middleware' which is causing me an error when running the server. Does anyone faced the same requirements or have an idea to do it ? Thank you for your help -
Is it possible in django models to do like this ? How to make a dropdown list in django models using another fields models
Guys can you help me how to make dropdown in django models but the dropdown list is from another models's field do you have some reference/link tutorial pls comment below thanks ;D! # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return self.username class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20,blank=True) username = models.Instagram.username nama_depan = models.CharField(max_length=30,blank=True) def __str__(self): return self.username