Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Posting form data in Angular 4 is received in Django as bytes
I am trying to build a full stack web app using Angular 4 on the front end and Django on the backend. I created a reactive form in Angular, which I submit to a backend API that is linked in Django urls.py. The full code is on my GitHub repo: https://github.com/shivkiyer/django-angular The Angular component code has: newCompanyForm: FormGroup = new FormGroup({ 'name': this.name, 'headquarters': this.headquarters, 'address': this.address, 'company_website': this.company_website, 'established_year': this.established_year }); addCompany() { console.log(this.newCompanyForm.value); this.http.post(this.apiBaseURL + 'new-company', JSON.stringify(this.newCompanyForm.value)).subscribe( response => { console.log(response); }, errors => { console.log(errors); } ); } Where addCompany() is called with the ngSubmit of the form. The Angular form is a mirror image of the Django model which is: class Company(models.Model): name = models.CharField(default='Google', max_length=200) headquarters = models.CharField(default='San Jose, California', max_length=200) address = models.CharField(default='123 River Drive, San Jose, California', \ max_length=500, blank=True, null=True) company_website = models.URLField(default='http://www.google.com', \ blank=True, null=True) established_year = models.IntegerField(default=2000, blank=True, null=True) def __str__(self): return str(self.name) + " in " + str(self.headquarters) def __unicode__(self): return str(self.name) + " in " + str(self.headquarters) I have created a simple class based view to receive the form data: @method_decorator(csrf_exempt, name='dispatch') class NewCompany(View): def get(self, request): return JsonResponse({"message": "Hello world"}) def post(self, request): new_company_data = json.loads(request.body.decode('utf-8')) new_company β¦ -
'module' object is not iterable when running django website to the server
i wanted to run my django website to their server so i open cmd and go to manage.py directory : C:\Users\computer house>cd desktop/newproject then i type this code : python manage.py runserver but i got this error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03BE5A08> Traceback (most recent call last): File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 542, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\computer house\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 549, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'videos.urls' from 'C:\\Users\\computer house\\Desktop\\newproject\\videos\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns β¦ -
multivaluedictkeyerror after uploading file
Error when trying to upload file There are my files below to see and error message after files sdfsfsdfsfd sf sdf sdf s df sdf sd fs dfsdfsdfsdf sdf sd fs dfsd f sf sf sd f sf sf Model.py import uuid from django.conf import settings from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from bootcamp.notifications.models import Notification, notification_handler class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) class News(models.Model): """News model to contain small information snippets in the same manner as Twitter does.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="publisher", on_delete=models.SET_NULL) parent = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE, related_name="thread") #myfile = models.FileField(null = True,blank=True) timestamp = models.DateTimeField(auto_now_add=True) uuid_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) content = models.TextField(max_length=280) liked = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="liked_news") reply = models.BooleanField(verbose_name=_("Is a reply?"), default=False) class Meta: verbose_name = _("News") verbose_name_plural = _("News") ordering = ("-timestamp",) def __str__(self): return str(self.content) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.reply: channel_layer = get_channel_layer() payload = { "type": "receive", "key": "additional_news", "actor_name": self.user.username } async_to_sync(channel_layer.group_send)('notifications', payload) def get_absolute_url(self): return reverse("news:detail", kwargs={"uuid_id": self.uuid}) def switch_like(self, user): if user in self.liked.all(): self.liked.remove(user) else: self.liked.add(user) notification_handler(user, self.user, β¦ -
Python django Surf on phone
I can not surf the internet made by django on phone browser,but I can surf by pc .i am using pc ip as link with http starting.how can I do ?thank you -
Adding error_css_class to SignupForm
I am using the Django Allauth SignupForm. It's working properly, but when I add error_css_class='error' to it, it's not adding class='error' when the field is invalid. How do I make it so that it adds the class name when there's an error just like how it is in forms.Forms? class RegisterForm(SignupForm): field_order = ['username', 'email', 'password'] error_css_class = 'error' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].label = "Email" self.fields['username'].widget = forms.TextInput(attrs={"placeholder": ""}) self.fields['email'].widget = forms.EmailInput(attrs={"placeholder": ""}) self.fields['password1'].widget = forms.PasswordInput(attrs={"placeholder": ""}) -
Use Google API with a token [Django & AllAuth]
I am using AllAuth on my Django app to manage user authentication. With that my users can connect their Google accounts and i get a google API token (with appropriate scopes). I would like to use that token to access google APIs (Calendar v3 in my case) with that token, as my user already used OAuth2 to sign-in on my website, and gave me access to the calendar API. Google only gives the full process on their website (from auth to api), is there a way to build my idea, or is it simply impossible? i have tries drive = build('calendar', 'v3', credentials=credentials) as said here but "credentials" needs to be part of an oauth2client and not just a simple string token. Thank you for your precious time. Simon -
rest_framework_mongoengine yields the "Invalid data. Expected a dictionary, but got str." exception
I've been playing around with the mongoengine framework and came across the above mentioned exception. Seems like I'm missing something and that's what I would like to clarify, hopefully with your help. Here is my MSV: models.py import mongoengine class PersonAddressModel(mongoengine.DynamicEmbeddedDocument): country = mongoengine.fields.StringField() town = mongoengine.fields.StringField() class PersonInfoModel(mongoengine.DynamicDocument): name = mongoengine.fields.StringField() age = mongoengine.fields.IntField() is_married = mongoengine.fields.BooleanField() address = mongoengine.fields.MapField( mongoengine.fields.EmbeddedDocumentField( PersonAddressModel ) ) serializers.py from rest_framework_mongoengine import serializers from .models import PersonInfoModel, PersonAddressModel class PersonAddressSerializer(serializers.EmbeddedDocumentSerializer): class Meta: model = PersonAddressModel fields = '__all__' class PersonInfoSerializer(serializers.DocumentSerializer): def create(self, validated_data): return PersonInfoModel.objects.create(**validated_data) class Meta: model = PersonInfoModel fields = '__all__' views.py from rest_framework_mongoengine import viewsets from .serializers import PersonInfoSerializer from rest_framework.response import Response from rest_framework import status import djongo class PersonInfoView(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = PersonInfoSerializer def create(self, request): serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except djongo.sql2mongo.SQLDecodeError: return Response( status=status.HTTP_503_SERVICE_UNAVAILABLE ) return Response( status=status.HTTP_201_CREATED ) Here is the json file I'm trying to post: { "name": "John", "age": 20, "is_married": false, "address": { "country": "Canada", "town": "Toronto" } } But it doesn't work, what am I failing to understand about all this? -
Django Rest Framework - Send multipart/form-data with file and other data to API
I'm trying to create some automated tests for my web-app which uses Django and DRF as a back-end to hand requests from the front-end. I'm having trouble finding a way to use the client to send some form-data to the API, I'm getting an error that no fields were posted. Here is my attempt using the APITestCase class: from django.test import TestCase, TransactionTestCase from django.core.exceptions import ObjectDoesNotExist from django.urls import reverse from rest_framework.test import APIRequestFactory, APITestCase, APIClient, RequestsClient, APITransactionTestCase import json, os, re import requests as python_requests from requests_toolbelt.multipart.encoder import MultipartEncoder .... .... def testInvoiceUploadAndRead(self): #test non-logged in user response=self.client.get(reverse("invoiceupload")) self.assertEqual(response.status_code, 403) user=Account.objects.get(username="test_user") self.client.login(username=user.username, password="rebar123") response=self.client.get(reverse("invoiceupload")) self.assertEqual(response.status_code, 405) #create the invoice full_filename=os.path.join("media", "testfiles", "sample_file.png") invoice = MultipartEncoder( fields={ "invoicefile":("test_file.png", open(full_filename, "rb")), "debtor":"5560360793", "amount":"55000", "serial":"1234567890", "dateout":"20180728", "expiration":"20180808", } ) response=self.client.post(reverse("invoiceupload"), invoice, content_type="multipart/form-data") print(response.data["message"]) self.assertEqual(response.status_code, 201) I'm getting the error: {'debtor': [ErrorDetail(string='This field is required.', code='required')], 'invoicefile': [ErrorDetail(string='No file was submitted.', code='required')], 'expiration': [ErrorDetail(string='This field is required.', code='required')], 'dateout': [ErrorDetail(string='This field is required.', code='required')], 'amount': [ErrorDetail(string='This field is required.', code='required')], 'serial': [ErrorDetail(string='This field is required.', code='required')]} No detected content sent, any ideas on how I can fix it, or better ways to accomplish the same thing? -
Django static files in production not loaded
I have a problem with static files in my Django application. I create a simple blog app with Django REST Framework and Angular 6. It's working fine in my local development environment, but I have a problem with deploying it to production. The thing is, the app is loading (I know that because the root route is a redirection to /app and I am being redirected correctly) but there are no static files loaded. Here is part of my configuration related to the static files: STATIC_URL = '/static/' BASE_DIR = os.path.join( os.path.dirname(os.path.dirname(__file__)), '..', '..', '..' ) STATIC_ROOT = os.path.join(BASE_DIR, 'app', 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend'), ] INSTALLED_APPS = [ ... 'django.contrib.staticfiles' ... ] The paths are correct, I triple-checked them to be sure. And here are routes configured in Django application: urlpatterns = [ url('^api/', include(api_patterns)), url('^admin/', admin.site.urls), url('^app/', serve, kwargs={'path': 'index.html'}), url('^$', HomepageView.as_view(), name='homepage-redirection'), ] I am able to run manage.py collectstatic without any errors and all static files are correctly copied to the static directory. Static files for admin application are not loaded correctly as well. Here is a rough structure of directories in my project: βββ app β βββ (python code here) βββ frontend β βββ β¦ -
How to get some fields in Inner Join from django?
i am trying get some fields from my database in django My model class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): product_Description = models.CharField(max_length=255) product_Comments = models.CharField(max_length=255) size = models.CharField(max_length=10, null=True) product_Status = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) date_Created = models.DateTimeField(default=datetime.now, blank=True) date_Modified = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.product_Description my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'product_Description', 'product_Comments', 'product_Status', 'category', 'date_Created', 'date_Modified') class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class InventorySerializers(serializers.ModelSerializer): model_b = CategorySerializer(source="category") class Meta: model = Product fields = ('id', 'product_Description', 'product_Comments', 'product_Status', 'category', 'date_Created', 'date_Modified', 'model_b') and my view.py class inventoryList(generics.ListCreateAPIView): queryset = Product.objects.select_related('category') print(str(queryset.query)) serializer_class = InventorySerializers def get_object(self): queryset = self.queryset() obj = get_object_or_404(queryset) return obj and it is json result [ { "id": 9, "product_Description": "Corbata roja gruesa", "product_Comments": "Corbate para ocasiones especiales", "product_Status": true, "category": 1, "date_Created": "2018-07-24T19:53:13Z", "date_Modified": "2018-07-24T19:53:13Z", "model_b": { "id": 1, "name": "Corbata" } } ] but i need it : [ { "id": 1, "name": "Corbata", "items": { "id": 9, "product_Description": "Corbata roja gruesa", "product_Comments": "Corbate para ocasiones especiales", "product_Status": true, "category": 1, "date_Created": "2018-07-24T19:53:13Z", "date_Modified": "2018-07-24T19:53:13Z" } } ] i was trying in change β¦ -
Ghost NoReverseMatch Error for Django app in Parallels VM
I have an odd behavior that I can't seem to track down a cause for. I am using the Parallels Desktop Lite app running on High Sierra to create a new MacOS VM that is also running High Sierra for development. I have successfully built a Postgres / Gunicorn / Nginx / Supervisor / Django stack. I am using Django==1.9.2 for legacy reasons. I imported my legacy django website code and it runs fine. Now I start taking snapshots of the VM as I remove unneeded components from the Django site. So say I have 10 apps in INSTALLED_APPS. I have successfully commented out / removed all of the code for 5 of them. I test the system, everything that is left runs fine. Then I take a snapshot of the VM and shut down for the day. The next day, I fire up the VM at the last snapshot to continue the process. However, now when I pull up the django website, I get a NoReverseMatch error for a namespace of an app that I had previously removed. And it is at line 0 of the base_template no less (which doesn't have a line 0). If I search through β¦ -
Hiding django json api data from public viewing
I am working on a Django project that is using vue as a front end framework. To allow vue to interact with the Django models I have set up a JSON restful api. By this I mean I have a view that pulls the necessary data from the database (using Django models), converts to JSON and publishes to a url as JSON formatted text. The vue app then looks at this url for all its data. The problem that I have is that people have access to the JSON url and can see all the data. Can I prevent this page from being viewed by visitors to the site? -
Upload image - Django rest framework
I have 2 User and EcoUser models with relation of 1 to 1 (I have reduced the fields of the tables for this example): class User(AbstractUser): picture_url = models.ImageField(upload_to='logos/', blank=True) class EcoUser(models.Model): user = models.OneToOneField(User, related_name='eco_user') document = models.CharField(max_length=45, blank=True) def __str__(self): return str(self.user) In which I use a NestedSerializer to be able to create and update the data of the two tables in a single post or put in this way I did the update since in the register I do not keep images and I have no problem with it: This is the serializer: class EcoUserSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = EcoUser fields = '__all__' def update(self, instance, validated_data): instance.document = validated_data.get('document', instance.document) instance.save() user_data = validated_data.pop('user') user = instance.user user.picture_url = user_data.get('picture_url', user.picture_url) user.save() return instance and in my viewset: class EcoUserViewSet(viewsets.ModelViewSet): serializer_class = EcoUserSerializer queryset = EcoUser.objects.all() pagination_class = None parser_classes = (MultiPartParser,) @transaction.atomic def update(self, request, *args, **kwargs): with transaction.atomic(): try: instance = self.get_object() instance.id = kwargs.get('pk') serializer = EcoUserSerializer(instance=instance, data=request.data) print(serializer) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response({"status": True, "results": "Datos actualizados correctamente"}, status=status.HTTP_201_CREATED) except ValidationError as err: return Response({"status": False, "error_description": err.detail}, status=status.HTTP_400_BAD_REQUEST) This worked correctly until I added the ImageField field and β¦ -
get person id through authenticated user id
I try to get person id of my Person model, connected with User model from django.db import models from django.contrib.auth.models import User class Person(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) middle_name = models.CharField(max_length=30) def __str__(self): return '%s %s %s' % (self.user.last_name, self.user.first_name, self.middle_name) from template-generated page, but I only can get user id who authenticated right now {{ user.id }} but not Person id. How can I get Person id through user id on the page? -
Django: display items from context dictionary in parralel in the HTML template
I am passing the below dictionary from view to Django template: activities = {'names':names, 'dates':dates} names and dates are lists. I want to display this data via template like this: Activity1, 1st January 2018 Activity1, 3rd January 2018 etc. So I need a loop to display the data from both lists one by one next to each other. So far I got this: <p>{% for name in names %} <p>{{name}}</p> {% endfor %}</p> But I don't know how to iterate dates in parallel to names. -
'class' object has no attribute 'object'
What am i doing wrong here. I have been trying to figure this out for hours. I think i am having issues with Django get_context_data function. Error is 'PatientBedAllotmentList' object has no attribute 'object' views.py @method_decorator(login_required, name='dispatch') class PatientBedAllotmentList(ListView): model = BedAllotment template_name = 'room/bed_allotment_list.html' def get_context_data(self, **kwargs): context = super(PatientBedAllotmentList, self).get_context_data(**kwargs) start = BedAllotment.objects.get(id=self.object.id).allotment_date end = BedAllotment.objects.get(id=self.object.id).departure_date amount = BedCreate.objects.get(id=self.object.id).cost days_number = abs((end - start).days) days_number = int(days_number) amount_due = amount * days_number context['account_type'] = AccountUser.objects.get(user_id=self.request.user.id) hospital_id = AccountUser.objects.get(user_id=self.request.user.id).hospital_id allotment_details = BedAllotment.objects.filter(hospital_id=hospital_id) context['allotment'] = allotment_details context['amount'] = amount_due return context -
Filtering a Queryset in django with a field such that only 1 object in that field shows
Intro: I have a model called event which has a ForeignKey post. The way it works is: Example A user creates a Post called "Solar Eclipse". Any number of users can create a event based on that post. So if someone goes on that post detail page. It has a button called and clicks on a button See all Events They can see all people who are hosting Solar Eclipse Event. Say there are 3 posts each has 10 events. On my Homepage I have a section that says Events. In the events section of homepage I want to show 3 posts not 30 events How Do I do that. Currently I know my queryset is Event.objects.all() is not correct. How do I filter this to show not only 1 post per event. Such that I don't hit the DataBase too many times my event models.py are class Event(models.Model): user = models.ForeignKey(User, related_name='host') post = models.ForeignKey(Post, related_name='event_post') price = models.DecimalField(max_digits=5, decimal_places=2) stock = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(15)]) initial_stock = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(15)], default=1) date = models.DateField() time_from = models.TimeField() time_to = models.TimeField() available = models.BooleanField(default=True) note = models.CharField(max_length=350, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Below are the views.py class EventView(ListView): model β¦ -
Views and http methods in Django rest framework
I'm starting with Django and Django Rest framework and coming from MVC world (groovy/grails, elixir/phoenix), I'm a bit confused with some things. I think Views work like Controllers right? But I'm used to define routes pointing to a specific action in the controller (it could be a get or post), but in django seems that a View is a less flexible Controller. I don't want to use all the shortcuts like generic views or something like that, I just want to define a View class, and define different methods specifying the HTTP method they'll serve, is that possible? Most of the documentation online is oriented to CRUD applications, but I want something more than that, and with less abstractions. Also, it seems that all the views are located in views.py, what happens if I'm working in a big project? that file is gonna be huge and difficult to maintain, is it a good practice to split that views.py in different files? thanks -
Django background task for data collection
I am writing a Django app which collects data after every interval from various 3rd party APIs and stores it in the database. This database is then used to create graphs and other analysis pieces of stuff. I am running background periodic tasks with the help of celery delay(). The question, how do I invoke the background process, as it should be only invoked once and run forever. I am looking for a way where the task would start automatically without manually executing any command. -
Django model many to many relationship
I Had a hard time in designing model for this requirement. 1) there are two models. a) student b) course 2) every student must opt a course in a priority list example course_opt1, course_opt2, course_op3 3) Depending on the selection of this options, a student will be assigned to a course. class Course(models.Model): course_name = models.CharField(max_length=200) course_code = models.CharField(max_length=200) def __str__(self): return self.course_name class Student(models.Model): student_name=models.CharField(max_length=200) rollno = models.CharField(max_length=200) course1 = models.ForeignKey(Course,on_delete=models.CASCADE) course2 = models.ForeignKey(Course,on_delete=models.CASCADE) course3 = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.student_name -
Django not serving media files when DEBUG is turned to False
Django is not serving my media files when DEBUG = False. Here is my code: DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') I've tried several things but none have worked. Please help me if you know the answer to my problem! -
Django not importing CSS
I cannot get the CSS to appear when I refresh the page nor when I turn the server off and then restart it. {% load staticfiles %} <!DOCTYPE html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name='viewpoint' content='width-device-width, initial-scale-1.0'> <meta http-equix='X-UA-Compatible' content='ie-edge'> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css"/> <link ref="stylesheet" type='text/css' href="{% static 'css/styles.css' %}" /> My settings.py file has STATIC_URL = '/static/' I'm not sure what else it could be. I've attempted several other stackoverflow questions but I'm out of ideas. Any help is appreciated. -
app.User has not been installed - forms.py error
I'm getting the error AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.User' that has not been installed forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.conf import settings class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254) class Meta: model = get_user_model() fields = ('username', 'password1', 'password2', 'email') models.py from django.db import models from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.conf import settings class UserManager(BaseUserManager): def create_user(self, email, username, password, first_name, last_name): if not email: raise ValueError("enter an email") if not username: raise ValueError("enter a username") if not password: raise ValueError("enter a password") user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name) if user.occupation == "admin": user.is_staff = True user.set_password(password) user.save() return user def create_superuser(self, email, username, password, first_name, last_name): user = self.create_user(email, username, password, first_name, last_name) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=False) username = models.CharField(max_length=25, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = UserManager() USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def β¦ -
How to use same bootstrap modal for 2 different submit buttons in django?
I have 2 buttons that basically submits form but I first need to confirm from user and used a modal for that <form action="{% url 'reset_pl' %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-primary btn-xs"> <span class="glyphicon glyphicon-remove"></span>Clear Players </button> </form> <form action="{% url 'reset_all' %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-primary btn-xs"> <span class="glyphicon glyphicon-remove"></span>Clear Teams </button> </form> and a modal for it that I need to use with both of them but don't want to repeat code <div class="modal fade" id="clear" tabindex="-1" role="dialog" aria-labelledby="Clear" aria-hidden="true"> <div class="modal-dialog modal-sm modal-notify modal-danger modal-dialog-centered" role="document"> <!--Content--> <div class="modal-content text-center"> <!--Header--> <div class="modal-header"> <p class="heading lead">Are you sure?</p> </div> <!--Footer--> <div class="modal-footer justify-content-center"> <button class="btn btn-primary btn-xs" data-dismiss="modal">Yes</button> <button class="btn btn-primary btn-xs" data-dismiss="modal">No</button> </div> </div> <!--/.Content--> </div> I am not sure how to dynamically change action of forms or let modal know where to actually submit form when a button is clicked. -
django render drops context value
Good morning Django community: I am having an odd context problem. I use a function to return a dictionary that I load into the context argument in render. I am adding values to my context dictionary in my view that are not quite accessible once rendered in my template. view.py class ModelInstanceView(LoginRequiredMixin, DetailView): """ This view shows all information specific to one instance of a model. Needs extra functionality for tutors whose info is much more complicated """ def get_model_instance_dict(self, pk, model): fields = [] self.model = model for field in list(self.model._meta.get_fields()): if hasattr(field, 'verbose_name'): fields.append(field.verbose_name) elif isinstance(field, ManyToOneRel): pass else: fields.append(str(field).split(':')[-1].split('.')[-1]) # try: values = list(self.model.objects.values_list().filter(pk=pk)[0]) print values if hasattr(self.model, 'related_set'): # ? fields.append('Tutors at this Site') related_values = self.model.objects.get(gg=pk).related_set.all() tutors_at_site = '' for x in range(len(related_values)): tutors_at_site += str(related_values[x].first_name + ' ' + related_values[x].last_name + ', ') values.append(tutors_at_site[:-2]) model_instance_dict = OrderedDict(zip(fields, values)) # except IndexError: # no record for the pk # model_instance_dict = None return model_instance_dict def get_context_data(self, pk, **kwargs): model = self.kwargs['model'] print 'THE MODEL 0', model, type(model) context = { "model_name": str(model.__name__), "model_select": model.objects.get(pk=pk), "model": self.get_model_instance_dict(pk, model), "id": pk, } if model.__name__ == 'Tutor': events = self.kwargs['model_two'] context["edit_model_url"] = 'edit_' + str(model.__name__).lower(), context["events_name"] = str(events.__name__), β¦