Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-tables2 URL Link from multiple foreign key not working
I'm working on a site using Django and need help with data flow and accessing the foreign key data. models.py class Boards(models.Model): board_no = models.CharField('Board No', max_length=10, unique=True) board_name = models.CharField('Board Name', max_length=100) class BoardLocations(models.Model): board = models.ForeignKey(Boards, on_delete=models.CASCADE, related_name='board') location_code = models.CharField('Location Code', max_length=10, null=True) class BoardContacts(models.Model): board_location = models.ForeignKey(BoardLocations, on_delete=models.CASCADE) contact_first_name = models.CharField('Contact First Name', max_length=100, null=True) contact_last_name = models.CharField('Contact Last Name', max_length=100, null=True) The BoardContacts are tied to a BoardLocation which all come from a Board. I'm displaying the list of BoardContacts properly through a django-tables2 as follows: List of Contacts The URL shows: http://127.0.0.1:8000/adm/boards/view_data_contact_list/6/ where 6 is Board.id. All fine. The Contact First Name link is defined as: tables.py class BoardContactsTableView(tables.Table): selection = tables.CheckBoxColumn(accessor='id') contact_first_name = tables.LinkColumn('view_board_contact', args=[A('id')], attrs=TABLE_VIEW_ATTRS) contact_last_name = tables.LinkColumn('view_board_contact', args=[A('id')], attrs=TABLE_VIEW_ATTRS) class Meta: model = BoardContacts template_name = TABLE_TEMPLATE_NAME attrs = TABLE_ATTRIBUTES ordering = ['contact_last_name'] fields = ('selection', 'contact_first_name', 'contact_last_name', 'contact_type', 'access_type', 'last_login', 'create_date') When I select Contact First Name or Last Name, the URL changes to: http://127.0.0.1:8000/adm/boards/view_data_contact/29/ because source indicates: <td ><a class="text-decoration-none fw-bold" style="color:gray" href="/adm/boards/view_data_contact/29/">Robert</a></td> But 29 is the BoardContacts.id. I need to maintain the Board.id of 6 within the URL so I can go back to the list of contacts … -
Which Framework django or react.js? [closed]
I am developing a web app (for admin & restaurants ) regarding food delivery (cloud kitchen) and an online grocery store. which framework should I use am confused, I have 2 options django and react.js .. can anyone guide me which is better and reliable.... thanks -
Django Concatenate charfields and parse it as Datetime
how are you? I have a model that has two fields named start_time and end_time, both are CharField, and this model has a relation to another model that has a field named date it is a DateField. It looks like this class A(models.Model): date = models.DateField() class B(models.Model): relation = models.ForeignKey(A) start_time = models.CharField() end_time = models.CharField() I need to query model B, using datetime values for example: B.models.filter(reconstructed_datetime="2021-04-19 15:02:00") where reconstructed_datetime is date (from model A) concatenated with start_time or end_time (from model B) I tryed something like this: B.objects.annotate( reconstructed_start=Concat( F('relation__date'), Value(' '), F('start_date'), output_field=CharField() ) ).annotate( reconstructed_start_datetime=Cast("reconstructed_start", DateTimeField()), ) But then I tried to filter .filter(reconstructed_start_datetime="2021-04-19 15:02:00") and it does not return my database record here "hora_inicio" is start_time. I suppose that use Cast does not work So, do you know a way to concatenate those model values and then make a query as datetime field? -
Django API sudden degrade in performance
I am working on a project where all REST API are implemented in django and UI is taken care by Vue.js. Since last week our dev and qa environments are facing long TTFB response time even for simple select queries to Postgres Database. To investigate this I added some logs to see how much time it takes to execute the query. Here is the code below import datetime from django.core.signals import request_started, request_finished from django.conf import settings class TenantListViewSet(APIView): """ API endpoint that returns all tenants present in member_master table in panto schema. """ @ldap_login_required @method_decorator(login_required) def get(self, request): settings.get_start_time = datetime.datetime.now() print(f'Total time from started to get begin {settings.get_start_time-settings.request_start_time}') errors = list() messages = list() try: settings.db_query_start_time = datetime.datetime.now() tenant_list_objects = list(MemberMaster.objects.all()) print(MemberMaster.objects.all().explain(verbose=True, analyze=True)) settings.db_query_end_time = datetime.datetime.now() print(f'Total time taken to execute DB query {settings.db_query_end_time-settings.db_query_start_time}') db_start = datetime.datetime.now() serializer = MemberMasterSerializer(tenant_list_objects, many=True) db_end = datetime.datetime.now() print(f'Total time taken to serialize data {db_end-db_start}') tenant_list = serializer.data response = result_service("tenant_list", tenant_list, errors, messages) settings.get_end_time = datetime.datetime.now() print(f'Total time taken to finish get call {settings.get_end_time-settings.get_start_time}') return JsonResponse(response.result["result_data"], status=response.result["status_code"]) except Exception as e: if isinstance(e, dict) and 'messages' in e: errors.extend(e.messages) else: errors.extend(e.args) response = result_service("tenant_list", [], errors, messages) return JsonResponse(response.result['result_data'], status=400) def … -
Add a random avatar to new user in Django UserCreationForm
I am trying to choose a random avatar from the database and add it to a user's account when they click on the 'Sign up' button on the registration page. I tried implementing this in my view but I keep getting the following error. > if file and not file._committed: AttributeError: 'UserAvatar' object > has no attribute '_committed' views.py def signup(request): ... user = form.save(commit=False) ... # query the avatars in the database and choose a random one for user avatar = UserAvatar.objects.all() random_avatar = random.choice(avatar) user.avatar = random_avatar ... user.save() ... form = CustomUserCreationForm() return render(request, 'signup.html', { "title": _('Sign up'), 'form': form, }) -
When running migrations on a new MSSQL server, I get the following error
Applying account.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ __init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ __init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 398, in execute output = self.handle(*args, **options) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/cagenix/.local/lib/python3.8/site-packages/django/core/management/ commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_i nitial=fake_initial) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_ initial) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/migrations/ex ecutor.py", line 230, in apply_migration migration_recorded = True File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/backends/base /schema.py", line 118, in __exit__ self.execute(sql) File "/usr/local/lib/python3.8/dist-packages/sql_server/pyodbc/schema.py", lin e 871, in execute sql = str(sql) File "/home/cagenix/.local/lib/python3.8/site-packages/django/db/backends/ddl_ references.py", line 201, in __str__ return self.template % self.parts KeyError: 'include' This code has a problem with the part of my website that handles Online Users, I don't know exactly what is causing the problem, but if I try to run migrations a second time it says that a db named account_users already exists. If you need any other info please ask. -
Django - 403 Forbidden on media files
When using apache2 and django, I am unable to access media files, as I am getting 403 forbidden when trying to load them. I am fairly certain I have set up my config correctly (see below) but im not totally sure. Static files are loading totally fine. I have looked at the other similar posts on stack overflow, which showed to include the following: <Directory /var/www/website/media/> Order deny,allow Allow from all </Directory> The entire contents of my config is below. <VirtualHost *:443> ServerName www.websiteurl.uk ServerAlias www.websiteurl.uk SSLEngine on SSLCertificateFile /etc/ssl/crt/websiteurl.uk_ssl_certificate.cer SSLCertificateKeyFile /etc/ssl/crt/_.websiteurl.uk_private_key.key SSLCertificateChainFile /etc/ssl/crt/_.websiteurl.uk_ssl_certificate_INTERMEDIATE.cer DocumentRoot /var/www/ WSGIScriptAlias / /var/www/website/wsgi.py <Directory /var/www/website/> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media /var/wwww/website/media/ Alias /static /var/www/website/static/ <Directory /var/www/website/static> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /var/www/website/media/> Order deny,allow Allow from all </Directory> <Location /server-status> Require ip 84.167.178.229 SetHandler server-status </Location> </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet <VirtualHost *:80> ServerName www.websiteurl.uk ServerAlias www.websiteurl.uk Redirect permanent / https://websiteurl.uk/ </VirtualHost> -
Is there methods of having inline form and related form in the same update page
The case is, there is a company and its employees. On the company page, I should be able to add employees to the company. Additionally be able to update company models.py class Company(models.Model): name = models.CharField(max_length=100, null=True, blank=True) link = models.URLField(null=True, blank=True) description = models.TextField(null=True, blank=True) class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) address = models.TextField() company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.first_name forms.py class CompanyForm(forms.ModelForm): class Meta: model = Company fields = '__all__' EmployeeFormSet = inlineformset_factory(Company, Employee, fields=('first_name', 'last_name',), extra=1) views.py def inlineformset_view(request, company_id): try: company = Company.objects.get(pk=company_id) except Company.DoesNotExist: return render(request, 'formset_view.html', {}) context = { 'company': company } if request.method == 'POST': formset = EmployeeFormSet(request.POST, request.FILES, instance=company) company_form = CompanyForm(request.POST, request.FILES) if formset.is_valid() or company.is_valid(): cd = formset.cleaned_data print(cd) company.save() formset.save() company = Company.objects.get(pk=company_id) context = { 'company': company, 'formset': formset, 'company_form': company_form } else: formset = EmployeeFormSet(instance=company) company_form = CompanyForm(instance=company) context = { 'formset': formset, 'company_form': company_form } return render(request, 'inlineformset_view.html', context) The problem I am having I am not able to post the data for the employee inline form and company form. I am having the same empty models when the forms is posted. -
Video and audio calling app using Python webrtc
I am doing an internship where they have asked me to build a video and audio calling feature for their chatting app using python. Can anyone guide me how can I build this feature using python ? -
Add a message on all views in Django
I'd like to use the Django messages functionality to show a message to users visiting our website. The idea is to show it on the first page they view and then not show it again for the rest of the user session. I'm thinking it will work a bit like this: if request.session.get('show_welcome_message', True): messages.info(request, 'Welcome to our site!') request.session['show_welcome_message'] = False My question is, where's the best place to add this to have it show on all website pages? And, is there a better way to do something like this that makes use of Django's native messaging to display a message to users that they don't see again on the same session if they close the message? -
How to change graph in django template on form submit
I have a django template as follows <div class="container"> <section class="main"> <h1>Check the chart below</h1> <form> {% csrf_token %} <div class="switch"> <input id="chk" type="checkbox" class="switch-input" /> <label for="chk" class="switch-label">Switch</label> </div> </form> <div class="main_graph"> {% if main_graph %} {{ main_graph.0|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> </section> </div> <script type="text/javascript"> $(document).on('click', '#chk', function (e) { $.ajax({ type: 'POST', url: '/home', data: { chk: $('#chk').prop('checked'), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { if (data.success == true) { // if true (1) location.reload(true); } } }); }) </script> This is my views def home(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() all_list = pd.read_csv('./all_list.csv').All.unique() chked=request.POST.get('chk', '') if chked == 'true': print(chked) my_graph = main_graph(all_list, len(const_list)) else: print('this is a test') my_graph = main_graph(part_list, len(const_list)) context={'main_graph':my_graph, 'const': const_list} return render(request, 'home.html', context) The main_graph function takes a list and an int value as parameters for creating a bar graph with plotly. The list will be for populating the y-axis and the int value is a range for the x-axis. The graph is created properly. Now I want to change the graph on the click of a button. For this purpose, I created a toggle switch which when clicked will … -
Is Django a good choice for web-dashboard that works with data from IoT devices and sensor devices?
I am a business owner and I would like to develop a web based service that uses the data from a number of sensors and IoT devices and analyze the data with scientific and mathematical methods. These data and their interpretations would be then be represented as reports, analytical summaries etc. My clients can login to the web dashboard and can see the reports and analytics. I would like to use to the flexibility and power of Python for data analytics, machine learning etc. My choice is Django for this purpose. I would like to know if I am making the right choice based on the following outcomes I need to serve more than 10k customers on a monthly basis I may have to scale up the resources and programming scopes significantly gradually I may have to opt for SPA(single page applications), rest APIs for additional functionalities and performance I may have to control the IoT devices according through the website Looking forward for your valuable insights Regards -
template inheritance not working i.e extends in django html template is not working
I am new to django web development and learning how to inherit one HTML template to another within templates folder I have tut.html(base) and card.html(child) card.html {% extends "templates/tut.html" %} {% block content %} <div class="container px-4 py-4"> <div class="row gx-5"> {%for tut in Tutorial %} <div class="card col-lg-5" style="background-color: rgb(115, 128, 128)"> <div class="card-body"> <h4 class="card-title">{{tut.name}}</h4> <p class="card-text">{{tut.content|safe}}</p> <p>{{tut.date}}</p> </div> </div> <div class="col-lg-1"></div> <br /><br /> {% endfor %} </div> </div> {% endblock %} this is child HTML template that I intend to use in parent HTML tut.html {% load static %} <html> <head> <link href={%static "tinymce/css/prism.css" %} rel="stylesheet" /> <!-- CSS only --> <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' integrity='sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk' crossorigin='anonymous'> <!-- JS, Popper.js, and jQuery --> <script src='https://code.jquery.com/jquery-3.5.1.slim.min.js' integrity='sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj' crossorigin='anonymous'></script> <script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js' integrity='sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo' crossorigin='anonymous'></script> <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' integrity='sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI' crossorigin='anonymous'></script> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <a class="navbar-brand" href="#">Tutorial</a> <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdownId"> <a class="dropdown-item" href="#">Action 1</a> <a class="dropdown-item" href="#">Action 2</a> </div>enter code here … -
Update models using signals
There are two models and I want to know how the profile bio can be updated using signals when the website model is modified (I need profile bio updated) Models.py from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) Signals.py from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: # ! HOW TO IMPLEMENT THESE TWO LINES # ** Add website to user - instance: user else: # ! HOW TO IMPLEMENT THESE TWO LINES My problem is with the AutoUpdateBio part Any help is highly appreciated -
Importing a django model to a python file
Project structure enter image description here import os import sys import django project_path = os.path.dirname(os.path.abspath('/mnt/c/WEB/codepython/PaymentForParking/index/telegram')) sys.path.append(project_path) os.environ["DJANGO_SETTINGS_MODULE"] = "PaymentForParking.settings" django.setup() And I get the error ModuleNotFoundError: No module named 'PaymentForParking' -
Url to the product after payment for subscription with Stripe in Django app
I've build Django app with authentication (Login/Sing up function). Then I created with Striple functionality to pay subscription for the product. In what way I can redirect user to the url with the product after payment? Does it require any special url/mechanism to activate the url after payment? I haven't yet created webhooks, is the mechanism of redirection to product url anyway related to webhooks implementation? -
ModuleNotFoundError: No module named 'my_app.urls' in django
after deploying site on heroku ,it's showing Internal server error. for debug I made "debug=true" and I found this error : "ModuleNotFoundError: No module named 'my_app.urls' " I've added my app in installed app list INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app', ] my_project urls : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('my_app.urls')) ] my app(my_app) urls: from django.urls import path,include from . import views urlpatterns = [ path('',views.home ), ] views.py: from django.shortcuts import render def home(request): return render(request,'index.html') site running on local server while debug = true but not running while debug=false(showing server error ) how to fix this "ModuleNotFoundError: No module named 'my_app.urls' " What did I miss. Any help/suggestion will be highly appreciated. Thanks -
Error inserting data into two joined serializers
I am making an application in Django Rest Framework which the user can register multiple tasks in a project, but I am running into a problem and it is that when I want to record the data it generates an error where it says that task_id cannot be null: This my serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'title', 'description' ) class ProjectSerializer(serializers.ModelSerializer): start_project = serializers.DateField(input_formats=['%Y-%m-%d']) end_project = serializers.DateField(input_formats=['%Y-%m-%d']) task = TaskSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'developer', 'title', 'description', 'start_project', 'end_project', 'task', 'project_state' ) This is the json that I send: { "developer": [ 1 ], "title": "Inicio", "description": "Iniciar", "start_project": "1999-02-02", "end_project": "1999-02-02", "task": [ { "title": "Titulo", "description": "empezar" } ], "project_state": 1 } When I show the response by console it returns the complete data: data={'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'task': [{'title': 'Titulo', 'description': 'empezar'}], 'project_state': 1} But when I want to get the data from the serializer it doesn't show me the tasks: {'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'project_state': 1} -
How to remove empty label from choices in django filters while using foreignkey
enter image description here This is the image.How to remove these (---------) lines from these choices.I am using django-filters. class NotesFilter(django_filters.FilterSet): subjects = CharFilter(field_name='subjects', lookup_expr="icontains", label='Subject', widget=TextInput(attrs={'placeholder':'Enter Subject'})) term = django_filters.ChoiceFilter(choices=SEMESTER_CHOICES, required=False, label='Semester', empty_label=None,widget=Select(attrs={'placeholder':'Enter Subject'})) class Meta: model = Notes fields = ['subjects', 'faculty', 'program','term'] -
How to open a DAL ( Django Autocomplete Light ) Select2 programmatically
I'm using DAL to render an autocomplete from a form field like this: search = forms.ChoiceField( widget=autocomplete.Select2( url='/search/my_search/', attrs={ 'data-placeholder': 'Select an option', 'data-minimum-input-length': 1, 'data-theme': 'bootstrap4', }) ) It gets rendered with this class: "select2-hidden-accessible" and gets this attr "data-autocomplete-light-function="select2". It doesn't get the "select2" class, that is given to one of its spans. Everything works well, except that I can't open the select2 programmatically. I tried: $('#id_search').select2('open') But it gives the error: "The select2('open') method was called on an element that is not using Select2.", because DAL doesn't pass the class "select2" to the rendered form field "id_search". Due to some peculiarities, I can't pass the class manually to the component. If I click on the field, it opens and works normally. I need some help in opening the select2 on page load. -
not able to access related model data using foreign key in Django
models.py class products(models.Model): name = models.CharField(max_length=100) sku = models.CharField(max_length=50) vendor = models.CharField(max_length=50) brand = models.CharField(max_length=50) price = models.FloatField() product_status = models.BooleanField() quantity = models.IntegerField() def __str__(self): return self.name # categories class categories(models.Model): category_name = models.CharField(max_length=50) parent_id = models.IntegerField() # product categories class product_categories(models.Model): product = models.ForeignKey(products, on_delete=models.CASCADE) category = models.ForeignKey(categories, on_delete=models.CASCADE) def __str__(self): return self.category I can access 'category' table data using data = products.objects.all() data.values('product_categories__category__category_name') output: <QuerySet [{'product_categories__category__category_name': 'xxxx'}}]> If I put this data.product_categories.category output: 'QuerySet' object has no attribute 'product_categories' how do I get a qureyset(can be passed to html) which includes data from "categories" table along with the data of "products" table -
How can i assign task to an employee?
I am developing a HR Task management system where employee can assign a task to another emloyee. what I am able to do is create two fields in the form. One field is named ASSIGNED TO and the other is name ASSIGNED BY. WHAT I WANT If I am assigning a Task to another employee, the employee should be able to know who assigned the task to him without me indicating or using the field called ASSIGNED TO in the form. WHAT I HAVE DONE SO FAR class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) # avatar = models.ImageField(upload_to='Avatars', null=True, blank=True) # user_type = models.CharField(max_length=10, choices=user_type, default='manager', null=True, blank=True) avatar = models.ImageField(upload_to="avatars", null=True, blank=True, default='default.jpg') # organisation = models.ForeignKey('Organisation', on_delete=models.RESTRICT, null=True, blank=True) # department = models.ForeignKey('Department', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) street_address = models.TextField(max_length=200, null=True, blank=True) appartment_unit = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) zip_code = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=40, null=True, blank=True) #state_of_birth = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.CharField(max_length=100, null=True, blank=True) marital_status = models.CharField(max_length=100, null=True, blank=True) # spouses_name = models.CharField(max_length=100, null=True, blank=True) # spouses_employer = models.CharField(max_length=100, null=True, blank=True) # spouses_work_phone = models.CharField(max_length=100, null=True, blank=True) … -
Assigning issue, unable to give or take roles in user admin , django
so basically what is happening is that i am trying to stop a user from acessing specific views, for example: admin and so on, unfortunately for some weird reason every time i create a user it receives every group role i created, even tho i didnt even write the code for it. I also cant take out a user from a group or put him in one, when i go inside a user infos. it is worth noting i am using, an abstract user model which may be the cause. This is how my user admin currently is, this is a new user by the way And this is how i think it should look like -
How to create separate form widgets for ModelMultipleChoiceField in Django
I have a ManyToMany relationship between two Django Models: Team and Member. A single Member can be part of multiple teams. I am able to successfully bind a Form class to a CreateView, and, using the standard ModelMultipleChoiceField,can successfully save the Form using the save_m2m method. However, the default widget for the field is not suitable for my user experience. Instead of using a picklist, I would like to create a separate select box for each number of selectable Members per team. For example, if the Team can have 7 Members, I would like to show 7 select boxes, rather than one pick list that a user selects 7 different objects from. I understand I may not get a complete answer, but would appreciate any pointers on if I should be looking into overriding the Field with a custom MultiWidget, or if using an inline formset might be a more appropriate route. Or, something else... -
Existing Django site implementation of wagtail. How to get RichTextField to show in admin?
I have added wagtail to an existing Django site. I wish to change the content part of the model to a RealTextField. What I had and what I have altered is shown below: class Post(models.Model): content = models.TextField() class Meta: ordering = ['-date_added'] def __str__(self): return self.title Post(models.Model): content = RichTextField() class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title