Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use the default login view to login multiple users to different profile pages in Django?
I am using Django 3.2 and I recently learned to create custom user models with email instead of username and the default authentication views. I implemented the following form in my login.html <form action="{%url 'login'%}" class="mx-3" method="post"> {% csrf_token %} <div class="emailAddressLog"> <label data-error="wrong" data-success="right" for="modalLRInput10" class="mt-3">Email Address:</label> <div class="input-group mb-3"> <i class="bi bi-envelope-fill input-group-text"></i> <input type="text" class="form-control validate" name="username" autocapitalize="none" autocomplete="username" autofocus="" id="id_username" maxlength="60" required=""> </div> </div> <div class="passwordLog mb-4"> <label data-error="wrong" data-success="right" for="modalLRInput11">Password:</label> <div class="input-group"> <i class="bi bi-lock-fill input-group-text"></i> <input required type="password" id="id_password" class="form-control validate" contenteditable="true" autocomplete="current-password" name="password"> </div> </div> {% if form.errors %} <p class=" label label-danger" style = "color:red"> Your username and password didn't match. Please try again. </p> {% endif %} {%if next%} {%if user.is_authenticated%} <p>Your account does not have access, please login with an account that has access.</p> {%else%} <p>Please login to see this page</p> {%endif%} {%endif%} My project based urls.py has in patters path('login/', auth_views.LoginView.as_view(), name='login'), I followed the documentation and so far it seems to work as when I input an incorrect user it gives me the error message but when I input the correct user with email and password then it throws me to an error as I have not implemented … -
Getting an empty list when using filter - Django REST
I have my API in Django REST Framework: Here is my models.py: class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False) Here is my views.py: class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned) Here is my urls.py: url_patterns = [ path('users/account=<str:id>/shipments', GetItemsByEmail.as_view()), ] My Question: I am getting an empty list, getting nothing from making an API call to the above endpoint. I want to get all the items in the database associated with a particular email? -
I'd like to save all the options selected in Django
I am a student who is studying Django. I want to save all of the selected option values when I select the option. However, we are facing a problem where all of the selected option values are not saved. Of the selected option values, only the last selected option values are saved. How can I save all of the selected option values? I tried 1:1 to the experts, but it didn't work out. I don't know how to solve it, so I put up a question here. Please, I want to know how to solve it. form class ElementForm(forms.Form): value_code = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션") views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = form.cleaned_data['value_code'] element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = None element.save() html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}" enctype="multipart/form-data"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} … -
How to display richtext {{content |safe}} as in regular html to vue template
I am making this website where I am using a richtext editor for input, what I usually did before is that I include the 'safe' tag as in {{Content|safe}} in django HTML template.However, recently I want to convert it to a spa website, I am not able to render the ** |safe tags in the vue template** . How should I resolve this? -
Invoke JavaScript function when the select element is first displayed
I have the following HTML in my Django app: <select required size="1" name="relevancy" id="relevancy{{result.report_id}}" onChange="change_relevancy(this.value,{{ result.report_id }});"> <option value="" {% if result.relevance == " " %} selected {% endif %}>Select...</option> <option value="N" {% if result.relevance == "N" %} selected {% endif %}>None</option> <option value="M" {% if result.relevance == "M" %} selected {% endif %}>Moderate</option> <option value="H" {% if result.relevance == "H" %} selected {% endif %}>High</option> </select> How do I call a JavaScript function when the select is first displayed? -
Django query by filter different attributes from slug
I have a model with lots of attributes. I want to query the model by filters in attritbutes. The problems is that I have to write lots of function to query by different attributes. models.py class ETF(models.Model): ticker = models.CharField(max_length=6, blank=False, db_index=True, unique=True) full_name = models.CharField(max_length=200, blank=False) region = models.ManyToManyField(Region) sector = models.ManyToManyField(Sector) industry = models.ManyToManyField(Industry) # Even more attributes here class Theme(models.Model): name = models.CharField(max_length=50, blank=False, unique=True) slug = models.SlugField(default="", null=False) def __str__(self): return self.name I am writing a function to filter ETF by attritbutes. Here is Views.py: class Categories_selector(): def __init__(self): pass def theme(self, category_slug): return ETF.objects.filter(theme__slug=category_slug).order_by('-aum') def sector(self, category_slug): return ETF.objects.filter(sector__slug=category_slug).order_by('-aum') def region(self, category_slug): return ETF.objects.filter(region__slug=category_slug).order_by('-aum') # more function here c_object = Categories_selector() def get_etf_list(request, categories_slug, category_slug): filtered_results = getattr(c_object, categories_slug)(category_slug) return render(request, "etf/list_etf.html", { "ETFs": filtered_results }) urls.py path("<slug:categories_slug>/<slug:category_slug>/", views.get_etf_list) Is there better way to do this? I feel like this is really dumb. -
Django DRF nested relationships - how to add objects in a ManyToMany field
I am building an API with DRF. I have two models, Folder and User, connected through a ManyToMany field. models.py class Folder(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=250) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) users = models.ManyToManyField(User, related_name='folders') def __str__(self): return self.title class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email serializers.py class FolderSerializer(serializers.ModelSerializer): class Meta: model = Folder fields = ("id", "title", "description", "users", "organization") def create(self, validated_data): users = validated_data.pop('users') if 'users' in validated_data else [] folder = Folder.objects.create(**validated_data) for user in users: if user in User.objects.all(): User.objects.filter... **not sure** else User.objects.create(folder=folder, **user) return folder The part I am stuck on is the custom create method: basically, users do not get created when the folder is created, they just get added to the newly created folder, so I think that in the for loop for user in users I should check if user exists within the instances of model User and if it does, I should update its property folder. I have no idea how to do so though. Also, I am … -
In Django, optimize performance when using a foreign key's attribute in the __str__method
The implementation of DocumentDetail's str method works, but is slows everything down by running a bunch of extra queries when I try to use it views, forms, etc. Does anyone know a way around this? models.py class Document(models.Model): description = models.CharField(max_length=50) def __str__(self): return self.description class DocumentDetail(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) detail = models.CharField(max_length=50) def __str__(self): return self.document.description -
Django aggregate sum for each user
I'm creating a budget application and wanted to find the sum of each user who's signed in. Right now I'm using function-based views and I sum up the expenses with Post.objects.aggregate(sum = Sum('expense')) The issue with this is it sums up everyone in the database but I wanted it to only sum up the expenses of the user that is currently signed in. In my model, I have an author field but I'm not sure how to go about summing only for the user currently signed in. -
DRF - APIView and Serializing a model with multiple foreign Keys(User)
How to save multiple foreign keys(User) data? In my case, the client(foreign key) should be able to hire to professional(foreign key) to the User model, how is it possible? models class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) is_client = models.BooleanField(default=False) is_professional = models.BooleanField(default=False) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client') ## class Professionals(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='professional') ## class HireProfessional(models.Model): user = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE) hire = models.ForeignKey(User, on_delete=models.CASCADE, related_name="hire") hire_start_date_time = models.DateTimeField(default=timezone.now) hire_end_date_time = models.DateTimeField(default=timezone.now) serializer class UserSerializer(serializers.ModelSerializer): client = ClientSerializer() professional = ProfessionalSerializer() class Meta: model = User fields = ('email', 'username', 'is_client', 'is_professional', 'client', 'professional') class HireProfessionalSerializer(serializers.ModelSerializer): user = UserSerializer() hire = UserSerializer() class Meta: model = HireProfessional fields = ['id','user', 'hire', 'hire_start_date_time', 'hire_end_date_time'] views class HireProfessionalCreateApp(APIView): permission_classes = (IsAuthenticated, IsClientUser,) def get_user(self): user = self.request.user return user def post(self, request, pk, format=None): try: professional = User.objects.get(id=pk) data = request.data _mutable = data._mutable data._mutable = True data['user'] = self.get_user() data['hire'] = professional data._mutable = _mutable serializer = HireProfessionalSerializer(data=data) data = {} if serializer.is_valid(): hire = serializer.save() data['hire'] = hire.hire return JsonResponse ({ "message":"professional hired success.", "success" : True, "result" : data, "status" : status.HTTP_201_CREATED }) else: data = serializer.errors return Response(data) except User.DoesNotExist: return JsonResponse ({"status":status.HTTP_404_NOT_FOUND, 'message':'user … -
Django-Tinymce with Tailwind CSS
I am currently using django-tinymce4-lite for my project and everything else works as expected. But on the actual rendered HTML page where the tinymce4 formatted content is supposed to be displayed, tailwind-preflight messes up the formatting with lists and spaces. I found this solution here. It is the exact problem I am facing. The first answer doesn't work for me and I want to get that working. I am following this tutorial to use Tailwind CSS with Django. I am new to npm so I blindly followed, and everything works but when I try to implement the first answer nothing happens. Using the second answer works but then it messes up the entire front-end. -
How to get a form from django as a getlist
I am a student who is studying Janggo. I want to get all the value_code itself as a getlist, but it's not working. How can I get it on the getlist? I want to get a request.POST.getlist, but I don't know how to get it using form. How should I modify it? I would really appreciate your help. views.py if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = request.POST.getlist['value_code'] element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code = None element.save() forms.py class ElementForm(forms.Form): value_code = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션", queryset=Value.objects.all()) html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}" multiple='multiple'>{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> -
Inheritance: class method not accessible through use of Foreign Key
Inheritance: class method not accessible through use of Foreign Key Hello! Problem I have multiples classes that inherit from the same class. There are differents relationships between instances of these classes that I need stored in another class (Relationship). To be able to link these different classes together, I use the "mother" class they all inherit from as a ForeignKey. Everything works, except that I cannot access class methods from the subclasses when I access their instances through the Relationship table (Foreign Key). Is there any way I could access the class method of a subclass when using the "superclass" as a Foreign Key? Code My code is as follows: models.py class SuperClass(models.Model): random_attribute = models.CharField() class A(SuperClass): some_attribute = models.CharField() class B(SuperClass): some_other_attribute = models.CharField() def class_b_method(self): some_code = 'goes_here' return some_code class Relationship(models.Model): parent = models.ForeignKey( 'app.SuperClass', related_name='parent', on_delete=models.CASCADE ) child = models.ForeignKey( 'app.SuperClass', related_name='child', on_delete=models.CASCADE ) views.py def do_stuff(): a = A('a') b = B('b') relationship = Relationship(parent=a, child=b) relationship.child.class_b_method() This throws the following error: AttributeError at xxx 'SuperClass' object has no attribute 'class_b_method' I understand why the error is there and what it means, but I have no clue as to how to access a class … -
Websocket can only send and receive messages within the same network. (Django3 channels3 on Elasticbeanstalk(linux2) and elasticache)
I developed a web program for video call and chat using Django-channels and deployed it to AWS Elasticbeanstalk and Elasticache redis for websocket. After the deployment was completed, it worked very well when tested in the company. And even now, me and my wife are testing in the same wifi environment and it's working good. However, messages cannot send or receive between different networks. For example, the websocket connection between the person connected at work and me at home is not working well. Logs say they are connected to each other. Environment Django 3.0 channels 3 supervisor daphne AWS Elastic Beanstalk (Platform2, Linux2, nginx, gunicorn) AWS Elasticache (Redis without cluster) Javascript code let mapPeers = {}; let usernameInput = document.querySelector('#username'); let btnJoin = document.querySelector('#btn-join'); let username; let webSocket; function webSocketOnMessage(event) { let parsedData = JSON.parse(event.data); let peerUsername = parsedData['peer']; let action = parsedData['action']; if (username === peerUsername){ return; } let receiver_channel_name = parsedData['message']['receiver_channel_name']; if (action === 'new-peer'){ createOfferer(peerUsername, receiver_channel_name); return; } if (action === 'new-offer'){ let offer = parsedData['message']['sdp'] createAnswerer(offer, peerUsername, receiver_channel_name); return; } if (action === 'new-answer'){ let answer = parsedData['message']['sdp']; let peer = mapPeers[peerUsername][0]; peer.setRemoteDescription(answer); return; } // console.log('message : ', message) } btnJoin.addEventListener('click', () => { username … -
django internationalization won't populate .po files
I have a django project with two simple apps, written in English, and want to enable translation into two other languages. I have been through the full documentation and probably all related questions, but I still can't find the way to populate the .po files. # settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # added this middleware 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGES = [ ('en-us', _('English')), ('fr', _('French')), ('de', _('German')) ] LANGUAGE_CODE = 'en-us' USE_I18N = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), os.path.join(BASE_DIR, 'app1', 'locale'), os.path.join(BASE_DIR, 'app2', 'locale'), ] All template files contain the {% load i18n %} tag. I have tried all the following combinations: django-admin / python manage.py makemessages -l fr / '-l de' / -a options from the project root or from each app with or without -e option with or without creating the locale directory before running the command I have also tried to create empty .po files at the expected locations, along with multiple suggested fixes from all Stack Overflow questions I was able to find. But in the end, all I get is: processing locale <lang> in the console. No .po file is created, nor is it populated if pre-created. No error … -
Trying to merge two dictionaries tables and retrieve field into 1, but get QuerySet object has no attribute copy DJANGO
I am currently trying to query two tables with the return of a filter in django of a timestamp field and merge the two fields to return hours before and hours after. This is the endpoint I am trying to get path(r'aircrafts/arrivals/time/hours-before/<int:hours_before>/hours-after/<int:hours_after> This is what I have so far def get_hours_before_and_after(request, hours_before, hours_after, flight_kind=''): if hours_before < 0: return HttpResponse(content='Hours need to be positive, status=404) elif hours_before<20: return HttpResponse(content="No number greater than 20", status=404) elif hours_after>20: return HttpResponse(content='No number less than 20", status=404) end_time = timezone.now() + timedelta(hours=hours_after) start_time = timezone.now() - timedelta(hours=hours_before) scheduled = get_scheduled(start_time, end_time, type) actual = get_actual(start_time, end_time, type) z = merge_two_tables(scheduled, actual) z = scheduled.copy() -> here errors z.update(actual) z = OrderedDict() if request.method == 'GET: serializer(Serializer(z, many=True) return JsonResponse(serializer.data, safe=False, status=200) def merge_two_tables(scheduled, actual): z = scheduled.copy() z.update(actual) return z def get_scheduled(start_time, end_time, type): if type: return Schema.objects.filter(type=type, scheduled_time__range=(start_time, end_time)) return Schema.objects.filter(type=type, scheduled_time__range(start_time, end_time)) def get_actual(start_time, end_time, type): if type: return Schema.objects.filter(type=type, scheduled_time__range=(start_time, end_time)) return Schema.objects.filter(type=type, scheduled_time__range(start_time, end_time)) @api_view(['GET']) def get_endpoint(request, hours_before, hours_after): return get_hours_before_and_after(request, hours_before, hours_after) -> fails My approach is I am trying to convert to dictionary or set by the id then merge and OrderDict() the timestamp, but I am unsure … -
Django CK Editor not loading on web hosting server but working in localhost
Django ck-editor working in my local host but when host my website on web it's not working. Here is the console error which saying my JavaScript file not loading but I add static in head of my template but I don't add {%load static %} in my local host template and it's working. Why it's not working in shared hosting??? why file is not loading? -
Django - How to save javascript variable into Django Database via Ajax Call?
I want to save Final Score value into Database. How do I do it? index.html <input style="height: 40px; width: 120px; text-align: center; margin-left: 440px;" type="submit" class="btn btn-primary" value="Save Score" onclick="save_score()"> </div> Test.Js Final_score = 80; function save_score() { $.ajax({ url: '/save_score/', data: {'final_score': final_score}, type: 'POST' }).done(function(response){ console.log(response); }); } urls.py urlpatterns = [ url(r'^save_score/', save_score) ] views.py def save_score(request): if request.method == 'POST': player = AddScore.objects.get() player.score = request.POST['final_score'] player.save() -
I do want to create a virtual environment for Django project every time but when I do pip install Django it says requirement already satisficed
Every time am starting a Django Project with django-admin startproject projectName am getting this error PS F:\Going back to backend> django-admin startproject lecture3 django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the pelling of the name, or if a path was included, verify that the path is correct and try again. -
Django Shell Default Database
I have an app named steve_charts with a models.py containing the class Atmospheric: class Atmospheric(models.Model): time = models.DateTimeField(unique=True) temperature = models.IntegerField(blank=True, null=True) humidity = models.IntegerField(blank=True, null=True) kpa = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'atmospheric' This refers to a legacy DB I am accessing. In settings.py my postgresql DB is correctly defined: 'steveDB':{ 'ENGINE': 'django.db.backends.postgresql', 'HOST': 'localhost', 'NAME': 'sensor_data', 'USER': 'pi' }, 'default': { ## NOT EVEN USING THIS THING 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } I ran python manage.py inspectdb --database steveDB > models.py to get me a fresh new models.py no problems so far... I ran python manage.py makemigrations steve_charts (which has been added to the installed apps section) and everything went smoothly. Django accessed my DB, inspected the table, made a new models.py for me no problem. Applied migrations no problem. So now I would like to check the DB in the shell: python manage.py shell >>>from steve_charts.models import Atmospheric No problems. >>>Atmospheric.objects.all() This should dump all the rows in the table, right? Instead I get django.db.utils.OperationalError: no such table: atmospheric Full stack trace: >>> Atmospheric.objects.all() Traceback (most recent call last): File "/home/pi/steve/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pi/steve/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", … -
Where is the Root Directory of the Hosting?
I want to add a .js file for starting Ads on my website but I am having problems in finding the root directory to upload the file. -
Traceback (most recent call last): self.execute(*args, **cmd_options)
When I run the project this is the error, I am facing now: PS E:\Git Project\django-calculator\mainproject> py manage.py runserver Traceback (most recent call last): File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Git Project\django-calculator\mainproject\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_l ine utility.execute() File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 367, in run_from_argv connections.close_all() File "C:\Users\iamra\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py", line 208, in … -
Django admin - UI modification on nested models
I'm working on a project developed in Python 2.7 and Django 1.11. More in details, i'm working on an admin page with nested models. This page contains three models and the last one is itself nested. To do this, the python package django-nested-admin (v. 3.2.4) has been used. Here the involved models: class SampleModelOne(Model): # ... some fields class SampleModelTwo(Model): field_1 = models.ForeignKey(SampleModelOne, ...) # field_2, _3, _4 class SampleModelThree(Model): test_1 = models.ForeignKey(AnotherModel, ...) test_2 = models.BooleanField(default=True) Here the admin.py: import nested_admin from dynamic_raw_id.admin import DynamicRawIDMixin class SampleOneAdmin(nested_admin.NestedModelAdmin): list_display = (..., ...) list_display_links = (..., ...) ordering = (...) inlines = [SampleTwoInline, SampleThreeInline, SampleFourInline] admin_register(SampleModelOne, SampleOneAdmin) class SampleFourInline(DynamicRawIDMixin, nested_admin.NestedTabularInline): model = SampleModelTwo fields = ('field_2', 'field_3', 'field_4') dynamic_raw_id_fields = ('field_2',) inlines = [SampleFiveInline] class SampleFiveInline(nested_admin.NestedTabularInline): model = SampleModelThree form = forms.SampleFormOne The SampleFormOne is used to have a select with autocompletion on test_1 field. To a better understing, this is a picture of the result: Is it possible to move in the UI test_1 and test_2 fields near field_4 (on the right)? -
showing the error of specific field in django form
How can i check the empty field of html form in the django for example let us suppose i have two fields username and passoword <input type="text" name="username"> <input type="password" name="password'> and now i want to check them in django first way is username = request.POST['username'] password = request.POST['password'] #for checking if (username) and (password): pass else: error = 'username or password doesn't exit' but the problem is this we can't identify that which field is not present means i can't show the error like this error ='username is not present' error = 'password is not present' and the another way i found is this if email: if password: pass else: error = 'password doesn't exit' else: error = 'email is not present' but if i have more fields in the form then this is difficult so please tell me the way to show the error of specific field is possible and my another question if there is an error in the form then can show the prefilled information to the user filled in form so that user doesn't have to completely fill it again for example in this form @login_required(login_url = 'login') def create_teacher(request): user = request.user if user.rejected_once … -
how to import custom fabric folder
so i have this script, that i use to log in on many servers trouhg ssh and it was runing ok on python2 /user/local/bin/a #!/usr/bin/env python # coding: utf-8 from __future__ import print_function, unicode_literals import os import sys sys.path.append("fabric_/") import fabfile if len(sys.argv) != 2: print('Usage: a <host>') sys.exit(-1) os.system('ssh root@{}'.format(fabfile.env.roledefs[sys.argv[1]][0])) but, now with python3, when i try to run the command("a client") it gives me a error the correct fabfile that has the "env" is on my project folder ruicadete/fabric_/fabfile.py i already tried to make sys.path only with the right fabfile, it worked but the it doesn't find the modules i've imported on the fabfile. what i'm doing wrong?