Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I post data with json nested and image file use APIRequestFactory in Django
I have problem when post data json with image file using APIRequestFactory. This is my demo code: post_data = { 'token': token, 'account': 'account', 'avatar': image_file, 'user': { 'email': 'user email', 'account': 'user_account', } } request = self.factory.post('/account/create', post_data, 'multipart') And this is error I got: AssertionError: Test data contained a dictionary value for key 'user', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. Please help me resolve this problem. Thank you. -
How to build json dynamically in python using tuple
I want to build json in following format { "codeTableData": [ { "codeValue": "11", "codeDisplayName": "AAAAAA" }, { "codeValue": "22", "codeDisplayName": "BBBBBB" } ] } from tuple which is result = [('11', 'AAAAAA'), ('22', 'BBBBBB'), ('33', 'CCCCCCCC')] I have tried creating dictionary and then adding tuple data inside that dictionary but still no luck jsonResult = {"codeTableData: " [ { tmp1:tmp2 }, ]} json_data = json.dumps(jsonResult) for above code program execution comes out of function with no error shown -
All the tabs in the chrome are loading same django page simultaneously
I'm developing a django application. In chrome when i test the app it works fine but if i work with multiple pages of same django application all the pages load at the same time. i.e, If I open admin page in one tab all the tabs that are running django application loads admin page simultaneously. This happens even while using different users and tabs at the same time. When i tried the same in Edge browser it was fine. I was able to load two different pages at the same time but not in chrome. I don't know what is happening here. Please help me to understand this problem, whether this is due to some bugs in my chrome or django application. -
Django - How can I distinguish what item I want to get deleted?
So I have several items (notes as I call them) saved in a database and displayed in a page like this: https://imgur.com/a/O90Qqsb I wanna be able to edit and delete a specific note but I'm having difficulties to know how can I tell my view which one I want to delete/edit I had to do similar things before but before I always was able to change my url so I would just pass the id through there, so now that I stay in the same page I really don't know what to do views.py if request.method == 'GET': form = AddNote() note = Notes.objects.all() args = {'form': form, 'note': note} return render(request, "notes.html", args) if request.method == 'POST': # Adds router to the database form = AddNote(request.POST, request.FILES) if form.is_valid(): print(form) print("Working!!!") # get info from form username = request.POST.get('username', '') print(username) date = request.POST.get('date', '') text = request.POST.get('text', '') notes_obj = Notes.objects.create(username=username, date=date, text=text) print(notes_obj) return redirect("notes") else: form = AddNote() if request.POST.get('delete'): return return render(request, "notes.html", {'form': form}) -
Unexpected Keyword argument in django model from json data
In my django project I have a model class having some fields. I have an API endpoint from which I get a JSON response. I parsed the json using requests library and tried to make a model instance. Unfortunately I could not do so. The following is the stack trace Internal Server Error: /app/ Traceback (most recent call last): File "C:\Users\REVE\PycharmProjects\FantasyFootballAnalytics\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\REVE\PycharmProjects\FantasyFootballAnalytics\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\REVE\PycharmProjects\FantasyFootballAnalytics\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\REVE\PycharmProjects\FantasyFootballAnalytics\app\views.py", line 38, in index strength_defence_away=team['strength_defence_away'] File "C:\Users\REVE\PycharmProjects\FantasyFootballAnalytics\venv\lib\site-packages\django\db\models\base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Team() got an unexpected keyword argument 'team_code' Here is my model class: class Team(models.Model): team_code = models.IntegerField draw = models.IntegerField # form = models.FloatField(null=True) team_id = models.IntegerField loss = models.IntegerField name = models.CharField(max_length=20) played = models.IntegerField points = models.IntegerField position = models.IntegerField short_name = models.CharField(max_length=3) strength = models.IntegerField # team_division = models.IntegerField(null=True) unavailable = models.BooleanField win = models.IntegerField strength_overall_home = models.IntegerField strength_overall_away = models.IntegerField strength_attack_home = models.IntegerField strength_attack_away = models.IntegerField strength_defence_home = models.IntegerField strength_defence_away = models.IntegerField def __str__(self): return self.name Here is my view function: def … -
Trying To get the message from sql management server to print it in my code using django
When I run a query using the cursor a message appears in the SQL Management serever and I want this message to get this message and print it in my code from django.db import connections def step1ATMexuSim(request): empty=Rfde2003Syd0827.objects.using('DataAdmin').all() sourcePE = request.GET.get('sourcePE') targetPE =request.GET.get('targetPE') sourceInterFace =request.GET.get('sourceInterFace') targetInterFace =request.GET.get('targetInterFace') with connections['DataAdmin'].cursor() as cursor: cursor.execute("DTA.mig_sop_virtual_interface_0814 1, %s ",[sourcePE,]) #I want to get the message that will appear after runing this query return render(request,'posts/mainPage.html') This is the message that I want to print -
'Collection' object is not callable when using djongo to change database to MongoDB?
I have a django project with settings set to psql database with lots of tables and data in each of them. Everything works fine in this project. But I am trying to switch from psql to MongoDB. Through a search in internet I found out that the djongo package can help me on this. I changed the settings.py related part to the following: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'myFreshMongo', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 27017, } } and after that, migrate works perfectly in creating a new database in the named databse in MongoDB with all my project's tables (models). However clearly they are empty and the data is not migrated psql since I have not done anything on that matter yet. Before migrating data, I try to run python manage.py runserver, and I bump into the following error right after the command windows shows System check identified no issues (0 silenced): File "...\MyVirtEnv\lib\site-packages\django\db\backends\base\in trospection.py", line 51, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "...\MyVirtEnv\lib\site-packages\djongo\introspection.py", line 46, in get_table_list for c in cursor.db_conn.list_collection_names() File "...\MyVirtEnv\lib\site-packages\pymongo\collection.py", li ne 2652, in __call__ self.__name) TypeError: 'Collection' object is not callable. If you meant to call the … -
How to inherit from one class in Models.py into another class and turn it into a dropdown in Django
I have different classes in models.py that define an item's details. I need to make a new class that uses details listed in the existing classes and turn that into drop down menu (choices). How would I inherit from those other classes and turn it into a drop down? I am fairly new to python and django, I was thrown into the deep end and I'm trying to figure things out as I go, I'm not even sure where to start with this issue. Here is one of the classes: class StockItem(models.Model): item_id = models.AutoField(primary_key=True) stock_code = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self) return self.description Here is the class that needs to inherit from the above class: class StockInventory(models.Model): serial_number = models.CharField(max_length=255) stock_item = # needs to get the description from StockItem class above # and have its contents as a drop down stock_item in StockInventory needs to get what the user typed into description under StockItem and have it shown as a drop down with all descriptions previously entered. As I said, I am fairly new to this (been doing it for a month with no prior coding experience), so I apologize if I am asking something very stupid. -
Django Cookie-Cutter with Docker "python: can't open file 'manage.py': [Errno 2] No such file or directory" Error Macbook
I am trying to setup Django Project using Cookie-cutter with Docker using this tutorial: https://realpython.com/development-and-deployment-of-cookiecutter-django-via-docker/. I followed the instructions step by step, and I was able to successfully run all commands until the step when I need to run: docker-compose -f local.yml run django python manage.py makemigrations. This command gives me an error: python: can't open file 'manage.py': [Errno 2] No such file or directory . I've searched around online for the problem, the problem seems to be that the source files of the Django project is not copied inside the app directory of the docker. I tried running these commands to check if the files were there: docker-compose -f local.yml run django sh ls -la And indeed, the files weren't there, specially manage.py. Why is that so? Here's a screenshot: -
Django get all rows of models identified by foreign key
The European privacy policy requires to give information which data a website has about a user. With Django 1.11. I can get all relations to a specific user by ._meta.get_fields. Is there a nice way to iterate over the relations and get the actual data as rows? This is what my relations look like: In [1]: from test_project.people.models import Profile ...: user = Profile.objects.get(id=1000) ...: user._meta.get_fields(include_hidden=True) ...: Out[1]: (<ManyToOneRel: admin.logentry>, <ManyToOneRel: avatar.avatar>, <ManyToOneRel: dialogos.comment>, <ManyToOneRel: agon_ratings.rating>, <ManyToOneRel: announcements.announcement>, <ManyToOneRel: announcements.dismissal>, <ManyToOneRel: actstream.follow>, <ManyToManyRel: user_messages.thread>, <ManyToManyRel: user_messages.thread>, <ManyToOneRel: user_messages.groupmemberthread>, <ManyToOneRel: user_messages.userthread>, <ManyToOneRel: user_messages.message>, <OneToOneRel: tastypie.apikey>, <ManyToOneRel: guardian.userobjectpermission>, <ManyToOneRel: oauth2_provider.application>, <ManyToOneRel: oauth2_provider.grant>, <ManyToOneRel: oauth2_provider.accesstoken>, <ManyToOneRel: oauth2_provider.refreshtoken>, <ManyToOneRel: oauth2_provider.idtoken>, <ManyToOneRel: invitations.invitation>, <ManyToOneRel: account.emailaddress>, <ManyToOneRel: socialaccount.socialaccount>, <ManyToOneRel: base.contactrole>, <ManyToOneRel: base.resourcebase>, <ManyToManyRel: base.resourcebase>, <ManyToOneRel: layers.uploadsession>, <ManyToOneRel: maps.mapsnapshot>, <ManyToOneRel: people.profile_groups>, <ManyToOneRel: people.profile_user_permissions>, <ManyToOneRel: groups.groupmember>, <ManyToManyRel: services.service>, <ManyToOneRel: services.serviceprofilerole>, <ManyToOneRel: upload.upload>, <ManyToOneRel: favorite.favorite>, <ManyToOneRel: monitoring.notificationreceiver>, <ManyToOneRel: mapster_adapter.mapstoreresource>, <ManyToOneRel: pinax_notifications.noticesetting>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: password>, <django.db.models.fields.DateTimeField: last_login>, <django.db.models.fields.BooleanField: is_superuser>, <django.db.models.fields.CharField: username>, <django.db.models.fields.CharField: first_name>, <django.db.models.fields.CharField: last_name>, <django.db.models.fields.EmailField: email>, <django.db.models.fields.BooleanField: is_staff>, <django.db.models.fields.BooleanField: is_active>, <django.db.models.fields.DateTimeField: date_joined>, <django.db.models.fields.CharField: organization>, <django.db.models.fields.TextField: profile>, <django.db.models.fields.CharField: position>, <django.db.models.fields.CharField: voice>, <django.db.models.fields.CharField: fax>, <django.db.models.fields.CharField: delivery>, <django.db.models.fields.CharField: city>, <django.db.models.fields.CharField: area>, <django.db.models.fields.CharField: zipcode>, <django.db.models.fields.CharField: country>, <django.db.models.fields.CharField: language>, <django.db.models.fields.CharField: timezone>, <django.db.models.fields.related.ManyToManyField: groups>, <django.db.models.fields.related.ManyToManyField: user_permissions>, <taggit.managers.TaggableManager: keywords>, <django.contrib.contenttypes.fields.GenericRelation: tagged_items>, <django.contrib.contenttypes.fields.GenericRelation: actor_actions>, <django.contrib.contenttypes.fields.GenericRelation: target_actions>, … -
Can I include complete Python scripts from GitHub to a Django application?
I have a question before I get started in a whole project... I'm in a team of 6 people, and I'm the only one using Python. I only use scripts already written, I just put in the arguments and that's it (scripts like Sherlock : https://github.com/sherlock-project/sherlock or Twint : https://github.com/twintproject/twint By the time, I learned a bit about coding in Python but really, it remains basic stuff. Now, my colleagues would like to use these applications too, and I thought about using Django, set up a web server, importing those scripts in the server, and giving the possibility to my colleagues to enter the args in a user-friendly way (some really don't know a thing about programmation) Is that possible with Django? If yes, will it be complicated? (I never used Django before and will follow courses, don't have a deadline) If no, do you guys know of any alternatives that I could use? Thanks for your answers! -
How to make a view that records the data from a ModelMultipleChoiceField form in database with django?
I use a ModelMultipleChoiceField form in my website, because it helps me check the presence of users (employees) at work or not. But I don't understand how can I recover the data from my form to write them in my model (database). form.py : class HoursDeclarationForm(forms.Form): number_of_hours = forms.FloatField(required=True) presense = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple ) views.py : from django.contrib.auth.models import User from registration.models import UserExtention def hours_declaration (request): form = HoursDeclarationForm(request.POST or None) if form.is_valid(): number_of_hours = form.cleaned_data['number_of_hours'] presence = form.cleaned_data['presence'] for user in presence : #this is the part I can not achieve return render ( request, 'HoursDeclaration/hours_declaration.html' , locals() ) models.py : class UserExtention (models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, verbose_name='utilisateur') town = models.CharField (max_length=50, null=True, blank=True, verbose_name='ville') address = models.CharField (max_length=500, null=True, blank=True, verbose_name='adresse') hours_number = models.IntegerField (null=True, blank=True, verbose_name="nombre d'heure effectuée par le salarié") Thank you for your answer ! -
How to transfer a file to the converter function
I am looking for a way to transfer a file to a function that converts different formats to pdf. The transfer takes place at the moment of saving the source file to AWS S3 inside the perform_create() function. When I pass a file stored on the local machine to the function manually everything works. class DocumentsListView(AwsUrlMixin, viewsets.ViewSetMixin, generics.ListCreateAPIView): ..... ..... def perform_create(self, serializer): file = serializer.validated_data['filedata'] name, ext = os.path.splitext(file.name) random_name = uuid.uuid4().hex file.name = f'{random_name}{ext}' url = self._get_aws_url(file)#get the link to private S3 directory for file download or view if ext != 'pdf': directory = os.path.abspath(os.path.dirname(__file__)) convert_to_pdf(file, directory) serializer.save(author=self.request.user, url_link=url) models.py class Documents(models.Model): .... filedata = models.FileField(storage=PrivateMediaStorage()) url_link = models.URLField(default=None, blank=True, null=True) convert_function.py from subprocess import Popen LIBRE_OFFICE = '/usr/lib/libreoffice/program/soffice' def convert_to_pdf(input_docx, out_folder): p = Popen([LIBRE_OFFICE, '--headless', '--convert-to', 'pdf', '--outdir', out_folder, input_docx]) print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx]) p.communicate() I got an error File "/home/y700/anaconda3/lib/python3.7/subprocess.py", line 1447, in _execute_child restore_signals, start_new_session, preexec_fn) TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile I've also tried this way (using url instead of file instances as an argument for the function convert_to_pdf) def perform_create(self, serializer): file = serializer.validated_data['filedata'] name, ext = os.path.splitext(file.name) random_name = uuid.uuid4().hex file.name = f'{random_name}{ext}' url = self._get_aws_url(file) if ext != … -
I am trying to print the message that appears in the sql server management in a text area in my html in django
I am trying to print the message that appears in the sql server management in a text area in my html in django This is the message that I want it to be in my Html This is the Text Area that I the message will be -
How add values to child form by parent ID?
This is my model class User(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Phone(models.Model): user = models.ForeignKey(Osoba, editable=False, related_name='phone', on_delete=models.CASCADE) phone = models.CharField(max_length=50) and i want to add phone to current User selected by ID and display it on site i have tried that def create_phone(request, id): user = User.objects.get(id=id) form = PhoneForm(request.POST or None, instance=user) if form.is_valid(): form.save() return redirect('list_users') return render(request, 'index-phone.html', {'form': form}) But it doesnt work, when i click button, its not creating new Phone My urls urlpatterns = [ path('', list_users, name='list_users'), path('new', create_user, name='create_user'), path('/<int:id>/update', update_user, name='update_user'), path('/<int:id>/delete', delete_user, name='delete_user'), path('/<int:id>/', create_phone, name='create_phone') ] -
Django: Move calculations query set, away from Python code
In the following code snippet, my goal is to get outstanding_event_total_gross. To get that I first lookup for each ticket that belongs to the event the amount of sold_tickets. Out of that, I can calculate tickets_left. For each ticket I then calculate the outstanding_ticket_total_gross which I add up to outstanding_event_total_gross. A lot of the business logic happens in Python, but I wonder now if there is a more efficient query set to achieve what I am doing while calling the data from the database? tickets = Ticket.objects.filter(event=3) outstanding_event_total_gross = 0 for ticket in tickets: sold_tickets = ticket.attendees.filter( canceled=False, order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE, ), ).count() tickets_left = ticket.quantity - sold_tickets outstanding_ticket_total_gross = tickets_left * ticket.price_gross outstanding_event_total_gross += outstanding_ticket_total_gross print(outstanding_event_total_gross) -
Django Channels equivalent to reverse()
In regular Django, I know I can use reverse to reverse a url. Is there equivalent functionality in django-channels for reversing a websocket url. If I have the following routing application = ProtocolTypeRouter({ "websocket": URLRouter([ url(r"^foo-websocket/$", FooConsumer, name="foo-example") ]), }) Is there something I can call like >>> reverse("foo-example") "/foo-websocket/" Or is this not possible in django-channels? -
How to properly unit test a Django middleware
I have to write unit tests for several Django Middlewares (Django > 1.10 styled middlewares). Project is an API, done with Django==2.2.3 and djangorestframework==3.9.4, I'm using standard Django unit testing module, and APIRequestFactory() and APIClient() test functions from Django REST framework to create mock requests for my tests. Here is an example of one middleware I want to test: from . import models class BrowserId(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if hasattr(request, 'COOKIES') and 'mydomain.bid' in request.COOKIES: bid = request.COOKIES.get('mydomain.bid', None) else: bid = None request.bid = models.BrowserId(bid) if bid else models.BrowserId.random() response = self.get_response(request) response.set_cookie( conf.BID_COOKIE_KEY, value=request.bid, max_age=conf.COOKIE_MAX_AGE, domain=conf.BID_COOKIE_DOMAIN ) return response I want to test: * That browser ID has successfully been added to the request * That cookie has successfully been set on the response ...independently of others middlewares. So, to be more precise, part of the tests would vaguely have to look like this: from rest_framework.test import APIRequestFactory, APIClient, APITestCase from my_api.auth import middlewares, models class MiddlewaresTestCase(APITestCase): def test_fresh_browser_id_request(self): ??? SOME CODE TO PROCESS THE REQUEST BY THE MIDDLEWARE assert hasattr(request, 'bid') assert len(request.bid) == 30 def test_existing_browser_id_request(self): req = APIRequestFactory().get('/') mock_bid: str = 'abcd1234' req.COOKIES = {cookie_key: mock_bid} ??? SOME CODE … -
How to operate a model in django without not define?
There are two projects, the A project defines each model, and the B project queries and modifies the model of the A project. How to do it? A project: class Case(models.Model): is_active = models.BooleanField(default=False) B project: I thought like this, but I don't know how to continue: class Base(models.Model): pass def save(self, force_insert=False, force_update=False, using=None, update_fields=None): pass -
How to avoid populating previous field value when click add another in formset
I have used formset to add some contents to model. When i click edit, i can use add another or delete link to add or delete content. But when i click add another its populating with previous data. How to avoid that data? I tried using initial but its shows error. ChoiceFormset1 = inlineformset_factory( Course, Materials_pdf, form=Materials_pdfForm, extra=0, intial =[{'chapter':'test'},{'pdf':'test'}, {'course_type':'test'}] can_delete=True, fields=('chapter','pdf','course_type') ) what i wanted is new fields which is not populated with previous data, when i click add another. Please help me to find a solution. -
How do I code in HTML get an image from a media server running on the same host as apache server
I'm running a UI to control some sensors using a Django Web app on apache2 on port 80 of a raspberry pi. I need to integrate streaming video into the app. I'm using MJPG-streamer as my streaming video server on port 8080 of the same machine. On the streaming video server site the html to get the image is: . Is there a way to code a reference to this in my DJango UI on the apache server? -
Use the "Add More" functionality to a page(template) without submitting the existing form (and values) and submitting in the end
I have a ModelForm which asks for his dreams from the users. But I want users to provide with the "Add More" button so that they can submit the form (form fields) all at once without being the headache of reloading the page everytime the user presses ADD More For example, If a user is done with telling its one wish, he/she can n number of more wishes and once he/she presses Submit , the form should then submit the answer to the DB. How can I make a model for this? Will a single class Wish(model.Model): user=models.Foreignkey(User, on_delete=models.CASCADE) wishes= models.Charfield(max_length=1024) and a form from this model to render the form???? A user can have any number of wishes available in the DB so that he/she can delete at any point of time by checking/unchecking. -
when i run python manage.py migrate getting ValueError: String input unrecognized as WKT EWKT, and HEXEWKB please do
when i made manage.py migrations i went sucessfully but when i run manage.py migrate i am new to geodjango pls help me Settings.py import os if os.name=='nt': import platform OSGEO4W=r"C:\OSGeo4w" if '64' in platform.architecture()[0]: OSGEO4W+="64" assert os.path.isdir(OSGEO4W), "Directory does not exist:"+OSGEO4W os.environ['OSGEO4W_ROOT']=OSGEO4W os.environ['GDAL_DATA']=OSGEO4W+r"\share\gdal" os.environ['PROJ_LIB']=OSGEO4W+r"\share\proj" os.environ['PATH']=OSGEO4W+r"\bin;"+os.environ['PATH'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '+2r35-w0_kqcr4ygbt474-!xx9q9izus$-+)g)%(-+=8d*^1pt' DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'repoter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'agricon.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'agricon.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'postgis_25_sample', 'USER': 'postgres', 'PASSWORD': 'Shanmukhavarma99@', 'HOST': 'localhost', 'PORT': '5432', } } GEOS_LIBRARY_PATH = r'C:\\OSGeo4W\\bin\\geos_c.dll' GDAL_LIBRARY_PATH = r'C:\OSGeo4W\\bin\\gdal204.dll' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation. UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' LEAFLET_CONFIG={ 'DEFAULT_ZOOM':1, 'MAX_ZOOM':30, 'MIN_ZOOM':10, 'SCALE':'both', } in models.py applied this to get welcome table python manage.py ogrinspect #repoter/data/TM_WORLD_BORDERS-0.3.shp welcome --srid=4326 --multi --mapping from django.db import models from … -
the content of Django form is not showing
I am little new to programming and I am trying to make the home page and login page in the same page the email and the password field are not showing index.html <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt=""> </div> <div class="col-md-4"> <form method="POST"> {% csrf_token %} {{ form }} <div class="form-check"> <span class="fpswd">Forgot <a href="#">password?</a></span> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> app/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from homePage.forms import SignInForm # Create your views here. def homePage(request): if request.method == 'POST': sign_in_detail = SignInForm(request.POST) if sign_in_detail.is_valid(): return render(request, "index2.html",{}) else: sign_in_detail = SignInForm() return render(request, "index.html",{"form":'sign_in_detail'}) app/forms.py from django import forms from django.core import validators class SignInForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput( attrs={ "class": 'form-control', "placeholder":'Enter E-mail', "id": 'exampleInputEmail1' }) ) password = forms.PasswordInput( attrs={ "class":'form-control', "placeholder":'Enter Password', "id":'exampleInputPassword1' }) the output is just a string "sign_in_detail" -
create method is raising key error in serializer
I am creating an API for signup. Serializers.py class UserSignupSerializer(serializers.Serializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'role'] extra_kwargs = {'password': {'write_only': True}} def create(self, validate_data): user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username']) user.set_password(validate_data['password']) user.save() return user Views.py class UserSignupView(APIView): def post(self, request): serializer = UserSignupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_204_NO_CONTENT) But this is giving key error 'email' or anything I put first in this line: user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])