Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.3 Inside get_absolute_url, Reverse for 'post_detail' not found
Main urls.py includes: path('', include('page.urls', namespace='page')) Page app urls.py app_name = 'page' urlpatterns = [ path('', views.home, name='home'), path('page/<slug:slug>/', views.page_detail, name='post_detail'), ] Page app models.py class Page(models.Model): . . . def __str__(self): return '{} by {} {}'.format(self.title, self.created, self.is_active) def get_absolute_url(self): return reverse("page_detail", kwargs= {"slug": self.slug }) In page app views.py: def home(request): pages = Page.objects.filter(is_active=1) context = { "pages":pages } return render(request,'page/home.html', context) def page_detail(request, slug): details = get_object_or_404(Page, slug=slug, is_active='1') return render(request,'page/details.html', {'details': details}) In the menu.html under templates/page: <nav class="collapse navbar-collapse bs-navbar-collapse navbar-right" role="navigation"> <ul class="nav navbar-nav"> {% for obj in pages %} <li><a href='{{obj.get_absolute_url}}'>{{ obj.title }}</a></li> {% endfor %} </ul> </nav> Please tell why i am getting: Reverse for 'page_detail' not found. 'page_detail' is not a valid view function or pattern name. But if I use <li><a href='/page/{{obj.slug}}'>{{ obj.title }}</a></li> in menu.html under templates/page it's working properly. The get_absolute_url is not working properly. Where I'm doing wrong. Please help me. -
Static files not serving on production with AWS, Bitnami Django Stack & Apache
I'm trying to deploy my existing Django project to an AWS Lightsail instance with Bitnami Django Stack & Apache, per Amazon's docs. (https://aws.amazon.com/getting-started/projects/deploy-python-application/?nc1=h_ls) While I was able to set up a new instance to serve my existing project, static files are not being served when the project is configured for production with DEBUG=False. I have run python3 manage.py collectstatic, verified that all my static files are collected in /opt/bitnami/apps/django/django_projects/PROJECT_NAME/static, and made sure the correct path is specified as the Alias for /static in httpd-app.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/PROJECT_NAME/PROJECT_NAME"> Options +MultiViews AllowOverride All <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} </Directory> Alias /static "/opt/bitnami/apps/django/django_projects/PROJECT_NAME/static" WSGIScriptAlias /PROJECT_NAME '/opt/bitnami/apps/django/django_projects/PROJECT_NAME/PROJECT_NAME/wsgi.py' I have specified STATIC_URL and STATIC_ROOT in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") Also, I restarted Apache for each change I have made. When running in the Django development server with DEBUG=True, static files can be accessed. However, in production with DEBUG=False the browser gives 404 when accessed via URL http://IP_ADDRESS/static/FILE_NAME. Please help. Thank you. -
DRF jwt error message type' object is not iterable and 'return [auth() for auth in self.authentication_classes]'
I'm making DRF api and i get TypeError message when I try to request. This message is preventing me from even debugging. I am looking for a way and I checked settings.REST_FRAMEWORK. This is my project code address: https://github.com/jeonyh0924/WPS_DabangAPI/tree/d13d6b440d2a5a1dfd3e17318bee14d02544f6a5 I am studying through the corresponding addres : https://medium.com/analytics-vidhya/django-rest-api-with-json-web-token-jwt-authentication-69536c01ee18 Thanks for reading. Have a nice day :) -
How to override external app template in Django?
I tried overriding a django-recaptcha template without any luck. What am I doing wrong? I am aware of Override templates of external app in Django, but it is outdated. Thanks! django-recaptcha file structure Lib/ --site-packages/ ----captcha/ ------templates/ --------captcha/ ----------includes/ ------------js_v2_checkbox.html my project file structure project/ ----templates/ --------captcha/ ------------includes/ ----------------js_v2_checkbox.html settings.py TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, ... }, ] -
how to insert foreign key data through Django Model form
How to insert foreign key data through form. Please help . what am I doing wrong So I have two models as follows : class Genre(models.Model): """Model representing a book genre.""" name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): """String for representing the Model object.""" return self.name ass UserItem(models.Model): name= models.CharField(max_length = 50, null=True) genre = models.ForeignKey(Genre, on_delete=models.SET_NULL, null=True) Forms.py : I want to create form to store Item data. Not able to reference Genre and enter value through form. class ItemForm(forms.ModelForm): name = forms.CharField() genre = forms.CharField() class Meta: model = UserItem fields = ['name', 'genre' ] Views.py def item(request): if request.method == 'POST': genre_obj = Genre.objects.get(name=request.POST.get('name')) print("Inside post") item_form = ItemForm(request.POST) if item_form.is_valid(): print("valid form") item_form_obj = ItemForm.save(commit=False) item_form_obj.genre = genre_obj item_form_obj.save() return HttpResponseRedirect(reverse('file_upload') ) else: print("invalid form") return HttpResponseRedirect(reverse('file_list') ) -
I want to use {{ }} in {% %}
```{% if request.user|has_group:"course_{{ couese.id }}" %}``` to achieve: request.user|has_group:"course_1" but doesn't meet the rules.So I want to ask for help,thanks. -
Add multiple images to a blog post using Django Ajax
I am trying to add multiple images to a post using Ajax in Django, but I cannot manage to do that with my current views as to when I upload an image I do not see it being added to the image list and my progress bar does not hide after being 100%. Currently, I have managed to create post object successfully but I do not know how to link and images to a post before the post is created, right now below are my codes: home/views.py class PostImageUpload(LoginRequiredMixin, View): def get(self, request): images = post.image_set.all() return render(self.request, 'home/posts/post_create.html', {'images':images} ) def post(self, request): data = dict() form = ImageForm(self.request.POST, self.request.FILES) if form.is_valid(): image = form.save(False) image.save() data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url} else: data['is_valid'] = False return JsonResponse(data) @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) home/models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted … -
Django_auth_ldap authentication with Microsoft AD issue
I'm unable to login to django application using AD authentication. Versions: Python 3.7 django-auth-ldap 2.1.1 python-ldap 3.2.0 OS - Windows 10 AD config -- Please see attached image... Here is my settings.py import ldap from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = 'ldap://Servername_xxx' AUTH_LDAP_ALWAYS_UPDATE_USER = False AUTH_LDAP_SEARCH_DN = "OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET" AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s") AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } from django_auth_ldap.config import ActiveDirectoryGroupType AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "DC=DEV,DC=TCORP,DC=NET", ldap.SCOPE_SUBTREE, "(objectCategory=Group)" ) AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType(name_attr="cn") AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser": "cn=django-admins,cn=users,DC=DEV,DC=TCORP,DC=NET", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 1 # 1 hour cache AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "django_auth_ldap.backend.LDAPBackend", ] # ERROR message in the console: search_s('OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET', 2, 'sAMAccountName=jsmith') raised OPERATIONS_ERROR({'desc': 'Operations error', 'info': '000004DC: LdapErr: DSID-0C090A6C, comment: In order to per form this operation a successful bind must be completed on the connection., data 0, v3839'}) search_s('OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET', 2, 'sAMAccountName=%(user)s') returned 0 objects: Authentication failed for jsmith: failed to map the username to a DN. # -
Django ORM - updating specific instance with a user-ForeignKey
I have the following model setup: class Model1(models.Model): val1_1 = models.CharField(max_length=25, blank=True) val1_2 = models.CharField(max_length=25, blank=True) user = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='model1') class Model2(models.Model): val2_1 = models.BinaryField() model1_link = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='model2') class Model3(models.Model): id = models.BigAutoField(primary_key=True) model2_link = models.ForeignKey(Model2, on_delete=models.CASCADE, related_name='model3') val3_1 = models.CharField(max_length=50) class Model4(models.Model): id = models.BigAutoField(primary_key=True) model3_link = models.ForeignKey(Model3, on_delete=models.CASCADE, related_name='model4', null=True, default=None) pred = models.CharField(max_length=50) # These fields are NOT FILLED IN during creation of an instance, and are instead updated later on with a separate query disputed_on = models.DateTimeField(blank=True, null=True) suggested_by = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='submitted_disputes', blank=True, null=True) At times, I will want to access Model4's specific instance, to actually fill in a value in fields disputed_on & suggested_by, by traversing all the way from Model1. I do that currently as such: query = Model1.objects.filter(id=some_chosen_id).get().model2.last().model3.filter(val3_1=some_chosen_value).get().model4.last() The output of that query is a single model instance, not a QuerySet. Next, I calculate new values I want to insert: dispute_date = datetime.now(tz.tzutc()) if request.user.is_authenticated: disputer = request.user else: # Assume admin (first entry) disputer = User.objects.get(pk=1) And I save new values by doing the following: query.disputed_on = dispute_date query.suggested_by = disputer query.save() Now, the strangest thing happens - my postgres DB gives me an error stating, the following: … -
Converting ndarray to Base64
A user uploads an image, if that user doesn't have another image to upload then that image is saved. We then take that image, slice it in two halves. The first half gets saved again. As for the second image, we need to convert it into a Base64 Image. However, for some reason I'm getting this error: ValueError: ndarray is not C-contiguous img = q.choice_set.all()[0].img reader = misc.imread(img) height, width, _ = reader.shape with_cutoff = width // 2 s1 = reader[:, :with_cutoff] s2 = reader[:, with_cutoff:] misc.imsave(settings.MEDIA_ROOT + "/" + img.name, s2) validated_data["choiceimage"] = base64.b64encode(s2) When I save this in the database, I get an error. What am I doing wrong? How can I decode the numpy array into base64? -
How make backend to work by java spring in python Django , Tensorflow with sql?
Create a back end, link the Java spring framework to the Python Django web project, add the Tensorflow framework, and ultimately link the sql database. عمل back end وربط اطار Java spring في مشروع الويب Python Django واضافة اطار Tensorflow وبالنهاية ربط قاعدة البيانات sql -
Ajax, not appending to table list and doesnt hide progress bar
I am trying to upload images using an Ajax request in Django with a status bar, however, after reaching 100% my status bar doesn't hide and images are not prepended tu the table. I was wondering what's the issue in my javascript code. my js code: $(document).ready(function(){ $(".js-upload-images").click(function () { $("#fileupload").click(); }); $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, start: (e) => { $("#container-progress").show(); }, stop: (e) => { $("#container-progress").hide(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); var strProgress = progress + "%"; $(".progress-bar").css({"width": strProgress}); $(".progress-bar").text(strProgress); }, done: function (e, data) { if (data.result.is_valid) { $("#image_list tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); my post_create html file: {% load crispy_forms_tags %} {% load static %} <script src="{% static 'js/image_upload.js' %}"></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ form|crispy }} </div> <div class="my-3 mx-3"> <button type="button" class="btn btn-sm mr-auto btn-primary js-upload-images"> <span><i class="fas fa-camera"></i></span> </button> <input id="fileupload" type="file" name="file" … -
Unable to render plotly graph to template in django
I am trying to plot a plotly graph to my django template but unable to do so, getting a blank template. views.py #plotly libraries used import plotly.graph_objects as go import plotly.express as px import plotly.offline as py def home(request): df=index(request) #returns a dataframe #overall cases total_df = df.groupby(['Country'])['Total Cases'].sum() total_df = total_df.reset_index() fig0 = px.scatter_geo(total_df,locations="Country", locationmode='country names', color="Total Cases", size='Total Cases',hover_name="Country", projection="orthographic",color_continuous_scale=px.colors.sequential.deep, ) fig0 = go.Figure(data=fig0) plot_div0 = py.plot(fig0, include_plotlyjs=False, output_type='div',config={'displayModeBar': False}) return render(request, 'test/welcome.html', {'plot_div0':plot_div0}) welcome.html {{ plot_div0 | safe }} -
Accessing Djnago generic DetialView directly from CreateView
I'm trying to acomplish the following functionality: the user enters required information in the form created using generic CreateView, in this case it is length and width. After the form is submitted the app performs simple calculations and returns the result along with submitted data. I tried to follow this example: [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views My models: from django.db import models class Building(models.Model): length = models.IntegerField(default=1) width = models.IntegerField(default=1) area = models.IntegerField(default=1) def __str__(self): return self.name def save(self, *args, **kwargs): self.area = self.length * self.width super().save(*args, **kwargs)re views: class BuildingDetailView(DetailView): model = Building context_object_name = 'building' class BuildingCreateView(CreateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building-detail') class BuildingListView(ListView): model = Building class BuildingUpdateView(UpdateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building_detail') urls: path('', views.indexView, name='index'), path('add_temp/', views.BuildingCreateView.as_view(), name='building_add'), path('buildings/', views.BuildingListView.as_view(), name='building_changelist'), path('building/<int:pk>/', views.BuildingDetailView.as_view(), name='building-detail'), html: {% extends 'base.html' %} {% block content %} <h1>Title: </h1> {% for object in object_list %} <p><strong>Length:</strong> {{ object.length }}</p> <p><strong>Width:</strong> {{ object.width }}</p> <p><strong>Area:</strong> {{ object.area }}</p> {% endfor %} {% endblock %} This setup is giving me the following error. I assume the problem is in my template: File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, … -
How do you use ManyToManyFields between apps without producing circular imports?
I have two apps, users and posts, with the models CustomUser and Block in users, and a model Post in posts. I'd like to created a "bookmarked" ManyToMany field for the User, so that they can bookmark any posts they want. It would look something like: class CustomUser(AbstractUser): ... neighbors = models.ManyToManyField("CustomUser", blank=True) blocks = models.ManyToManyField("Block", blank=True) bookmarked = models.ManyToManyField("Post", blank=True) ... As you can see, I have quite a few ManyToMany fields already, but they were all for models from the same app users. As for my Post class: class Post(models.Model): ... author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) block = models.ForeignKey(Block, null=True, on_delete=models.SET_NULL) ... I already imported two models from the users app, CustomUser and Block, into the posts app. I understand that by importing Post into users' models.py, it creates a circular import, at least, it gives me the following error: ImportError: cannot import name 'CustomUser' from partially initialized module 'users.models' (most likely due to a circular import) Is there a way to prevent this? I know an option is to just create the bookmarked attribute in the Post model instead of the User model, but I'm reluctant to do so simply because it's a little weird to me personally. … -
Django drop down list dependant on model?
I'm trying to make a drop down list dependent on a model. For example my app has a "store" model, when a user is created a store is set for them. Stores can have employees. When a logged in user accesses this drop down list, I want to list all the employees that are associated with the store that the user. What is the best way to do this? -
Como utilizar ManyToManyField no html para inserção de dados
forms.py from app_teste.models import Diario class FormDiario(forms.ModelForm): class Meta: model = Diario fields = '__all__' models.py from django.db import models class Diario(models.Model): nome = models.CharField('Nome', max_length=50) DiarioDescricao = models.ManyToManyField('Equipamento') class Equipamento(models.Model): descricao = models.CharField('Descrição', max_length=50) views.py from django.shortcuts import render, redirect # Create your views here. from app_teste.forms import FormDiario def index(request): if request.method == "POST": form = FormDiario(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = FormDiario() return render(request, 'index.html', locals()) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>INICIAL</title> </head> <body> <h1>Pagina Inicial</h1> <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Finalizar</button> </form> </div> </body> </html> No template index, quero inserir vários equipamentos, porem sou iniciante e não tenho ideia de como fazer isso, sem sair da pagina. Estou usando ManyToManyField pois na documentação o encontrei e pelo que entendi, da para adicionar vários objetos dentro da mesma tabela. Mas não sei como eu faria no template para poder realizar essa inserção. Me ajudem! Obs: NÃO É NENHUM ERRO, APENAS UMA DUVIDA E UM PEDIDO DE AJUDA! -
How to acces to a model related to a user in DJango
I would like to access to a model related to a user in User. I know that it's possible to get the username or the name of the user using: request.user.get_username() model.py class Profile(models.Model): profile_user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_note = models.CharField(max_length=30,...) Is there any method to take the related model field without a query? Example: request.user.profile.profile_note -
Dynamic rows with jinja template
Project Hi, I'm building a django webapp but i'm having some problems with jinja. I want to create a page were a list of entries can be displayed so something like Django def page(request): entries = Entries.objects.all() context = { 'entries' : entries } return render(request, 'page.html', context) HTML {% for e in entries %} <div class="row"> <div class="title"></div> {% for i in e.list %} <div class="card">i.title</div> {% endfor %} </div> {% endfor %} Problem For each entries i want to display its related list of objects in a row. Problem is that if i have for example 10 elements i'd like to create multiple rows that automatically adapt when user resize the window Is that possible? -
Django add a product to the user automatically
I want to add a product to the user profile, but I can only do it by using a form, and on the template choosing the user from a dropdown menu. What I want to do, is, go to add product ('Añadir vehiculo' in this case), and select the features of said product on the fields, and then I want that product to be automatically added to my profile. As you can see in this image, where it says "Propietario" it's the user(client). https://imgur.com/hWZntVQ And I want to make this: https://imgur.com/VGWUYiv Select every single field but not the "Propietario"(client) one, so It's automatically added to the user who is adding it. But I get these two errors when I change a couple of things, and I can't think of a way to make this work. Errors: "IntegrityError at /perfil-vehiculo-alta NOT NULL constraint failed: webapp_vehiculo.duenio_id" "TypeError at /perfil-vehiculo-alta cannot unpack non-iterable builtin_function_or_method object" and These are the two models that matter: class Usuario(AbstractBaseUser, PermissionsMixin): Departamentos = models.TextChoices('Departamentos', 'Artigas Canelones Cerro_Largo Colonia Durazno Flores Florida Lavalleja Maldonado Montevideo Paysandú Río_Negro Rivera Rocha Salto San_José Soriano Tacuarembó Treinta_y_Tres') nombre = models.CharField(max_length=20, default="") apellido = models.CharField(max_length=20, default="") documento = models.CharField(unique=True, max_length=8, default="") email = … -
How do I adjust my Apache Docker config to only route some URLs to my Docker django instance?
I have Apache, Django, and MySql images set up in my Docker container. Below is my docker-compose.yml file ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3306" volumes: - my-db:/var/lib/mysql command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" #volumes: # - web-static:/www/static links: - web:web volumes: my-db: Within my Apache configuration, I have set up this virtual host to route traffic to my Django instance ... <VirtualHost *:80> ServerName maps.example.com ProxyPreserveHost On ProxyPass / http://web:8000/ ProxyPassReverse / http://web:8000/ Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" </VirtualHost> My question is, how do I alter the above configuration to only send traffic to my Django instance in which the URL begins with the words "data" or "coops"? -
"email": [ "Enter a valid email address."] Django is saying email is not an email
problem: I am trying to serialize an email field using Django Rest Framework, however the server is saying not accepting any email. All emails are greeted with error "Enter a valid email address". Below are my configurations. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password') models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, verbose_name='email address') first_name = models.CharField(max_length=256, verbose_name="First Name", blank=True) last_name = models.CharField(max_length=256, verbose_name="Last Name", blank=True) id = models.UUIDField(primary_key=True, unique=True) data = JSONField(default=default_data, name="device_data") is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] django.core.validators.py @deconstructible class EmailValidator: message = _('Enter a valid email address. Not valid') code = 'invalid' ... domain_whitelist = ['localhost', 'gmail', 'gmail.com', '@gmail.com'] httpie to server http -f POST http://127.0.0.1:8000/reg email="l55@gmail.com", password='pw' response HTTP/1.1 400 Bad Request Allow: POST, OPTIONS Content-Length: 42 Content-Type: application/json Date: Mon, 30 Mar 2020 00:11:14 GMT Server: WSGIServer/0.2 CPython/3.7.3 Vary: Accept, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY { "email": [ "Enter a valid email address." ] } Previous effort: I was told to add domains to the domain_whitlist property (which i've done) I have also tried using Django's default user class, but I encountered the same error. Can you help … -
Add a product to the user automatically on django
I want to add a product to the user profile, but I can only do it by using a form, and on the template choosing the user from a dropdown menu. What I want to do, is, go to add product ('Añadir vehiculo' in this case), and select the features of said product on the fields, and then I want that product to be automatically added to my profile. As you can see in this image, where it says "Propietario" it's the user(client). https://imgur.com/hWZntVQ And I want to make this: https://imgur.com/VGWUYiv Select every single field but not the "Propietario"(client) one, so It's automatically added to the user who is adding it. But I get these two errors when I change a couple of things, and I can't think of a way to make this work. Errors: "IntegrityError at /perfil-vehiculo-alta NOT NULL constraint failed: webapp_vehiculo.duenio_id" "TypeError at /perfil-vehiculo-alta cannot unpack non-iterable builtin_function_or_method object" and These are the two models that matter: class Usuario(AbstractBaseUser, PermissionsMixin): Departamentos = models.TextChoices('Departamentos', 'Artigas Canelones Cerro_Largo Colonia Durazno Flores Florida Lavalleja Maldonado Montevideo Paysandú Río_Negro Rivera Rocha Salto San_José Soriano Tacuarembó Treinta_y_Tres') nombre = models.CharField(max_length=20, default="") apellido = models.CharField(max_length=20, default="") documento = models.CharField(unique=True, max_length=8, default="") email = … -
How can I show a dropdown in my form with the title of the objects in the table? Django ModelForm
Hi I've been trying to create a simple app for workflows or binary protocols (yes or no instructions, very helpful sometimes) I have created a simple form with ModelForm: class BlocForm(forms.ModelForm): class Meta: model = Bloc fields = [ 'description', 'loop_child' ] and my model looks like this: class Loopeable(models.Model): protocol = models.ForeignKey(Protocol, on_delete=models.CASCADE, null=True) description = models.TextField() pointing_at = models.IntegerField() class Bloc(models.Model): description = models.TextField() protocol = models.ForeignKey(Protocol, on_delete=models.CASCADE) parent = models.ForeignKey('self',on_delete=models.CASCADE, null=True, blank=True) loop_child = models.ForeignKey(Loopeable, on_delete=models.CASCADE, null=True, blank=True) question = models.BooleanField(default=False) end_bloc = models.BooleanField(default=False) And my problem is that instead of having this loop_chile dropdown list of ugly objects I would like to get the description in the Loopeable Model, is there a way to get some data that is not just "Loopeable Object (id_number)". I didn't add my views.py in order to keep the post short, but I implemented the for by simply doing something like: form = BlocForm(request.POST or None) if form.is_valid(): ...rest of the code If anyone has some ideas I will be grateful!! Thanks... -
Creating dropdown like Django Admin
I hope you're all fine. Thats my first ask here. I am trying to build a dropdown like this: admin button Participant is a model, so it haves some fields like name and institution. How can i add a button like this to my django app? (I don't want to do this on Admin, but in the app)