Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to run Django application on xampp server (Windows 7)
I am trying to deploy my Django project on xampp server. I have followed the steps from here I am using windows 7, Python 3.6(64 bit), xampp(64 bit) I have also installed mod_wsgi using pip install mod_wsgi command And copied and the mod_wsgi.cp36-win_amd64.pyd file to the apache's modules folder as mod_wsgi.so as mentioned in the steps in the link and added the LoadModule line as well. I have added the following lines to httpd.conf file: <IfModule wsgi_module> WSGIScriptAlias / C:\xampp\htdocs\Hostel\Hostel\wsgi.py WSGIPythonPath C:\xampp\htdocs\Hostel <Directory C:\xampp\htdocs\Hostel> allow from all </Directory> Alias /static/ C:\xampp\htdocs\Hostel\live_static\static_root <Directory C:\xampp\htdocs\Hostel\live_static\static_root> Require all granted </Directory> </IfModule> The apache server is running on port 8012 but when I open localhost:8012 it is unable to load anything. This is my error log: [Wed May 06 19:51:33.663007 2020] [core:warn] [pid 2680:tid 148] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00455: Apache/2.4.43 (Win64) OpenSSL/1.1.1g mod_wsgi/4.7.1 Python/3.6 PHP/7.2.30 configured -- resuming normal operations [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00456: Apache Lounge VC15 Server built: Apr 22 2020 11:11:00 [Wed May 06 19:51:33.697009 2020] [core:notice] [pid 2680:tid 148] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Wed May … -
What SAML library is better for Django and Python?
I use python 3.6, Django 2.1.5 and SAML 2 I tried many SAML libararies so far. Most of them are either out of date or does not work at all. The last one was: python3-saml-django It produces an error: onelogin.saml2.errors.OneLogin_Saml2_Error: Invalid dict settings: sp_cert_not_found_and_required Any suggestions? -
Uncaught (in promise) TypeError: Request failed with django-pwa
I'm trying to setup django-pwa. I got like this error in console. django-pwa: ServiceWorker registration successful with scope: https://my_domain.com/ Uncaught (in promise) TypeError: Request failed. serviceworker.js:1 Application tab shows this error. No matching service worker detected. You may need to reload the page. What it did Add console.log("console.log('hello sw.js');") in serviceworker.js then console log show the comment, however I got same error at first line of the serviceworker.js I checked to access https://my_domain.com/manifest.json. It was fine. Do you have any idea to solve this problem? Please help me. -
Enable and disable dynamically a field on condition of another one in Django
I created a model TransactionModel and its related ModelForm TransactionForm. As you see below I have a field called 'Type' where I can choose between two values: 'EXPENSE' and 'INCOME'. When I choose either of them I want to be able to disable either the 'expenses' or the 'incomes' field dynamically in the form so that the user does not select both. Below is the Model class TransactionModel(models.Model): type = models.CharField(max_length=100, choices=TransactionType.choices, null=True, default=TransactionType.expense, verbose_name=_('type')) title = models.CharField(max_length=200, verbose_name=_('title')) slug = models.SlugField(max_length=200, unique_for_date='publish') amount = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('amount')) created = models.DateTimeField(auto_now_add=True, verbose_name=_('created')) publish = models.DateTimeField(default=timezone.now, verbose_name=_('publish')) updated = models.DateTimeField(auto_now=True, verbose_name=_('updated')) expenses = models.CharField(max_length=200, choices=ExpenseType.choices, blank=True, verbose_name=_('expenses')) incomes = models.CharField(max_length=200, choices=IncomeType.choices, blank=True, verbose_name=_('incomes')) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='katika_transaction') Here is the Form class TransactionForm(BSModalForm): class Meta: model = TransactionModel exclude = [ 'slug', 'user', ] def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) if self.fields['type'] == 'EXPENSE': self.fields['incomes'].disabled = True self.fields['expenses'].disabled = False else: self.fields['expenses'].disabled = True self.fields['incomes'].disabled = False As you can see I tried to put some if condition in init of the form to do it but it doesn't work at all. in the views I don't know if I have to change something but I will also share … -
Passing anonymous users from one view to another in Django 3.0.5
I'm trying to create a fully anonymous survey, where the survey participant enters a landing site (index.html), clicks a link and is directed to a survey view. On this survey (pre_test.html) page, I want to assign a new Participant object with a primary key and link that to the Survey model via a foreign key. Because this Survey isn't the main part of my study, I want to send that Participant object to a new view, where the Participant primary key is again used as a foreign key to link to another model (call it Task). What I've tried so far in the views.py is: def pre_test(request): if request.method == "POST": participant = Participants() participant.save() participant_pk = participant.pk form = PreTestQuestionnaireForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() post_primary = PreTestQuestionnaire(pk=post.pk) post_primary.Analyst_id = Participants(pk=participant_pk) post_primary.save() request.session['user'] = participant_pk return HttpResponseRedirect(reverse('main:picture_test')) else: form = PreTestQuestionnaireForm() return render(request, 'study/pre_test.html', {'form': form}) def picture_test(request): obj = Participants(Unique_ID=request.session.get('user')) # Unique_ID is the pk I've set for Participants but when calling print(obj) all I get is Participants object (None). What am I missing in using the session? Should I not be using sessions in this way at all, or should I create actual users in another … -
How to provide binary field with Django REST Framework?
Is it possible to provide a backend endpoint where the response is a json containing some field values and a data blob? I have the following model and serializer: class NiceModel(db_models.Model): index = db_models.IntegerField() binary_data = db_models.BinaryField() class NiceSerializer(serializers.ModelSerializer): class Meta: model = models.NiceModel fields = ( "index", "binary_data", ) this serializer produces a json like the following: { "index": 1, "binary_data": "veryveryveryveryveryverylongtext" } Is this very long text a string representation of the binary data handled by DRE? If so, how can I read this data with javascript? Am I doing it the wrong way? should I create an endpoint only for the blob data and forget about the json format? Thanks in advance. -
I just setup python django and Im unable to import
I just finished setup python django I did everything in the video and I wrote the most simple code from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse("<h1>Hello world!</h1>") I imported it to the url and it works as expected but the issue is I get this:It saying unable to import I dont know why it saying that bc it works well. what is wrong with the program? -
drf - How to filter on 1 item given a many to many relationship
I have 2 tables Product and Price. A product can have multiple prices. This in order to remember the old prices of the product. In my product view I have the following code: products = ProductFilter(filters, queryset=products.all()) ProductFilter is a custom filter class. The filter variable is the same as request.GET. This is what the filter looks like: class ProductFilter(django_filters.FilterSet): ... price__final_price__gte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="gte" ) price__final_price__lte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="lte" ) price__currency = django_filters.CharFilter() class Meta: model = Product fields = ["name", "external_id"] This is the problem. If product A has for example 3 prices. Product A: 1. 50$ - 2020/march 2. 20$ - 2019/dec 3. 60$ - 2019/jan When I filter, I would only like to filter on the most recent price. So if my filter had price__final_price__lte: 30 I wouldn't want this product to be selected, because the price on 2019/dec was indeed under 30, but the most current price is not. In what way do I need to change my ProductFilter class to make this possible? (Some ideas I had where to look for the closest date given the current date, but I couldn't get this to work.) Any help would be greatly appreciated. -
Clear Table data on server restart in django
I'm trying to add default data in my table in Django and then create a restful API that changes that data and when I turn the server off and restarts it again the data should be the default one. But it's not working with this code. My Migrations File(0001_initial.py) initial = True dependencies = [ ] def insertData(apps, schema_editor): Login = apps.get_model('restapi', 'Users_Details') user = Login(name="admin", email="abc@gmail.com", password="abcd123456") user.save() operations = [ migrations.CreateModel( name='Users_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100, unique=True)), ('password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ('confirm_password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ], ), migrations.RunPython(insertData) How can I reset the data to its default(initial) data every time I restart the server. -
Django rest framework csrf exempt when doing ajax post call
I'm trying to pass data via ajax POST request but getting a 403 ERROR. I've tried to use CsrfExemptMixin from braces.views but that doesn't resolve the issue. I'm new to api calls with drf so maybe my methods are incorrect. View class DialogListView(CsrfExemptMixin, viewsets.ModelViewSet): # queryset = Dialog.objects.all() serializer_class = DialogSerializer # http_method_names = ['get', 'delete'] def get_queryset(self): data = self.request.data print('helllo') print(self.request.data) # for k in data: # print(k) try: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.get(Q(owner=owner_profile, opponent=opponent_profile) | Q(owner=opponent_profile, opponent=owner_profile)) except ObjectDoesNotExist: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.create(owner=owner_profile, opponent=opponent_profile) -
Image missing in RSS/ATOM with Django
I'm trying to attach an image to my ATOM and RSS syndication feed thanks to the Django's documentation : https://docs.djangoproject.com/fr/1.11/ref/contrib/syndication/ I have to kind of feed : http://example.com/rss and http://mywebsite.com/atom rss.py class LatestEntriesFeed(Feed): title = "MyWebsite" link = "/" description = "Latest news" def items(self): return Articles.objects.filter(published=True).order_by('-date')[:5] def item_description(self, item): return '<![CDATA[ <img src="http://example.com/image.jpeg" /> ]]>' def item_title(self, item): return item.title def item_pubdate(self, item): return item.date def item_updateddate(self, item): return item.update def item_author_name(self, item): return item.author def item_author_link(self, item): item_author_link = Site_URL + reverse('team', kwargs={'username': item.author}) return item_author_link def item_author_email(self): return EMAIL_HOST_USER class LatestEntriesFeedAtom(LatestEntriesFeed): feed_type = Atom1Feed subtitle = LatestEntriesFeed.description So I think I have to use CDATA into the description html tag. However, in Django (version 1.11), item_description doesn't return <description> tag in the XML, but a <summary> tag. Is it fine or is it the source of the issue ? Otherwise, I tried to scan with W3C validator and I get 2 errors (or just warnings ?) 1) Self reference doesn't match document location 2) Invalid HTML: Expected '--' or 'DOCTYPE'. Not found. (5 occurrences) -
RelatedObjectDoesntExist error while trying to get current username through admin model
This is my model: def get_form_path(instance,filename): upload_dir=os.path.join('uploaded',instance.hostname,instance.Class) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir,filename) class Book(models.Model): Name= models.CharField(max_length=100) Class= models.CharField(max_length=100) Content =models.FileField(upload_to=get_form_path) hostname=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,on_delete=models.CASCADE) def __str__(self): return self.Name def delete(self, *args, **kwargs): self.Content.delete() super().delete(*args, **kwargs) This is form.py class BookForm(forms.ModelForm): class Meta: model=Book exclude=('hostname',) fields=('Name','Class','Content') class BookAdmin(admin.ModelAdmin): exclude=('Name','Class','Content',) form=BookForm This is my admin.py: class BookAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'hostname': kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username) return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) def get_readonly_fields(self, request, obj=None): if obj is not None: return self.readonly_fields + ('hostname',) return self.readonly_fields def add_view(self, request, form_url="", extra_context=None): data = request.GET.copy() data['hostname'] = request.user request.GET = data return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context) admin.site.register(Book, BookAdmin) Im not getting where I'm going wrong? complete error line is"upload.models.Book.hostnamee.RelatedObjectDoesnotExist:Book has no hostname please guide me through this..Thanks in advance -
How do I input the newline from textarea in HTML and put that to postgresql database through Django?
I am getting an input from the user through an HTML textarea and I need to push that to database. Ex: if user enters -- "hey how are you? \n Its great to have u here." The textarea only takes "hey how are you" and saves only this to the database but I want the whole text instead. Here is the create.html <!doctype html> {% load static%} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap-grid.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body style="background-color: lightskyblue;"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark mynavbar"> <a class="navbar-brand brand" href="index">notify</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav"> {% if user.is_authenticated %} <li class="nav-item navlinks"> <a class="nav-link" href="logout">Logout</a> </li> <li class="nav-item navlinks" style="margin-top: 9px;"> <span style="color: azure;">Hello</span><a class="nav-link" href="#" style="display: inline;">{{user.first_name}}</a><span style="color: azure;">!!</span> </li> {% else %} <li class="nav-item navlinks"> <a class="nav-link" data-toggle="modal" data-target="#exampleModalCenter2"><svg class="bi bi-person-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3zm5-6a3 … -
i'm working on the project where i need to add the operators in the data but it will gives an error to me
MY VIEWS CODE== def addoperator(request): if request.method=="POST": opera = User.objects.create_user( username=request.POST['name'], email=request.POST['email'], password=request.POST['password'] ) s=Operator() s.user=opera s.phonenumber=request.POST['number'] s.gender=request.POST['gender'] s.address=request.POST['address'] s.picture=request.FILES['userimage'] s.document=request.FILES['document'] s.save() return render(request,'Adminside/addoperators.html') else: return render(request,'Adminside/addoperators.html') MY MODELS CODE==== class Operator(models.Model): # This field is required. user = models.OneToOneField(User,on_delete=models.CASCADE,default='') # These fields are optional gender=models.CharField(max_length=200,default='') phonenumber=models.CharField(max_length=200,blank=True) address=models.CharField(max_length=200,blank=True) picture = models.ImageField(upload_to='operator/', blank=True) document = models.ImageField(upload_to='operator/', blank=True) status=models.CharField(max_length=100,default='PENDING') def isActive(self): if self.status=="ACTIVE": return True else: return False def isDisable(self): if self.status=="DISABLE": return True else: return False So, the main thing is that when i add the operator it will gives an error regarding the operator by saying that there is no user_id column in the operator model. but i only gives the user field in the operator model as you can see in the models code and i don't know how to resolve it. and i will show the error below and please help i'm stuck on this for like two to three days. and important thing for doing this i extended the auth_user tabel to enter the other fields like gender,images and phonenumber etc. MY ERROR FOR ADDING THE OPERATOR OperationalError at /admin/Adminside/operator/ no such column: Adminside_operator.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/Adminside/operator/ Django Version: 2.2.4 Exception Type: OperationalError Exception … -
how can i configure apache with django
I want to ingrate apache server with django, but i still have error, can anyone help me plz. i install apache i configure variable environnement for apache i install wsgi i modify wsgi.py because i work with windows i make this code in httpd.conf WSGIScriptAlias / "C:/users/akm/downloads/projet/testoreal/testoreal/testoreal/wsgi_windows.py" WSGIPythonPath "C:/users/akm/downloads/projet/testoreal/testoreal/site-packages"; Order deny,allow Allow from all and i steel can't open the server Thanks -
how can I connect with mongoDB container database from Host
I'm using MongoDB container. and I want to connect to MongoDB from host through django I import "djongo"(module to use django with mongoDB) at settings.py at django. I changed many time the value of host and port but I didn't worked. DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'mongoTest1', 'HOST': 'mongodb://localhost:17017', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'password', 'AUTH_SOURCE': 'password', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } container and I got this errors with python manage.py runserver enter image description here I think there are no problem with ports. Because I just simply bind 17017(host)->27017(mongo container) I only created "root" user at mongoDB and create db, collections to use. -
How do I join two models in Django by id?
I have two models as shown below with just a few fields: class Query(models.Model): query_text = models.TextField(blank=True, null=True) variable = models.CharField(max_length=250, blank=True, null=True) class Statistic(models.Model): query = models.ForeignKey(Query, models.DO_NOTHING, blank=True, null=True) processing_time = models.DateTimeField(blank=True, null=True) module = models.CharField(max_length=500, blank=True, null=True) My target is to perform a JOIN using the id of the two models. The SQL query equivalent to it would be : SELECT * FROM statistic S JOIN query Q ON S.query_id = Q.id I understand select_related or prefetch_related could do the trick? I don't know which one to use to perform the join. I'd appreciate some help on that. Thanks. :) -
Where to retrieve used API key in a HTTP request
I'm trying to develop an Endpoint for uploading files that is only accessible using an API key. I use the Django REST Framework API Key and my code in viewsets.py is as follows: class UploadFileViewset(viewsets.ModelViewSet): model = File queryset = File.objects.all() serializer_class = FileSerializer parser_classes = [MultiPartParser] # not sure whether required permission_classes = [HasAPIKey] def create(self, request): serializer = FileSerializer(data=request.data) # converts to JSON if serializer.is_valid(True): # validating the data model_instance = serializer.save() # saving the data into database I'd like to be able to pick out various attributes from request, for example, its source (in this case the API Key). When I debug I can't find the API key in the request. Is it because it's actually not present in the request, but is already "eaten up" beforehand in Django's middleware? I'm a bit confused why I can't retrieve it, and if I can actually get a source from the http request at all. -
Django filter after using select_related query
Going through a troble to filter that i used for select_related This is my model for Purchase: class Purchase(models.Model): amount = models.FloatField(default=1) entry_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='ledger_entry_by', ) is_cash = models.BooleanField(default=False) and this is my model of Consume: class Consume(models.Model): amount = models.FloatField(default=1) consumed_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='consume_entry_for', ) This is my query user_wise_cost = User.objects.annotate( difference=ExpressionWrapper( Coalesce(Sum('ledger_entry_by__amount'), Value(0)) - Coalesce(Sum('consume_entry_for__amount'), Value(0)), output_field=FloatField() ) ) The above query is working great following my requirement. I want to calculate only the amount that cash paid, i mean, if a entry is_cash=True, it will be calculated My requirement was: for example, A user Purchased 500 USD and he consumed 550 USD, that is mean, he needs to pay another 50 USD another user purchased 440 USD but he consumed 400 USD, that is mean, he will get refund 40 USD. another user example can be: a user didn't purchase anything but he consumed 300 USD, so he needs to pay 300 USD. also if a user didnt purchase anything or consumed anything, yet his data needs to show like 0. Above all the requirement was successfully achieved by that query, there is no issue at all but currently, it's calculating … -
Django Template is saying the user is not authenticated even when it says it is in the views
As the title states I have a Django template that is not authenticating. In my html I have a basic if that says: {% if request.user.is_authenticated %} But that is being evaluated to false when I login, but if I refresh the page it lets me in. Also in my part of my login views I have: if User.object.filter(username=username).exists(): user = User.objects.get(username=username) authenticate(request, username=username) print(request.user.is_authneticated) login(request, user) print(request.user.is_authenticated) return redirect(next_url) And When I check the out puts they print out as: False True Yet in the html it evaluates to False, but when I refresh the page it says it's true. (Also I know I'm authenticating with only username that's fine for the context I'm working in). Also the main issue I'm having is that it failes to login depending on the url. Ex: If I hit the website with base_url I can login as normal no problem If I hit the website with base_url/welcome I login as normal, but then I encounter the problem I described. Hopefully there is enogh info/context to give me a direction of what to do. Sorry I can't give more code -
How can I change the workflow of Django Admin
I am a beginner of Django.I want to use Django Admin to do the following things: 1-upload a excel file 2-read the header of the excel file 3-choose a part of the header to save to the database.(a list of the header with checkbox and submit button) 4-show the result to the user How can I finish the job by Django Admin?I think I should change the default workflow of the Django Admin,but how to do so? -
Django - What does objects.get return
Sorry if this seems like a really stupid question. I am building an app using Django, and at some point I am accessing the db using db.objects.get(var = val) But my question is what type object does this method return? And hw can I access the data in it? Like as a dict, list or sth else? I apologize if it is a duplicate. -
Does django cache files in MEDIA_ROOT by default?
I am using a clean install of Django 3 on a Docker container development server. I have the following settings.py: MEDIA_ROOT = '/vol/web/media/' MEDIA_URL = '/media/' And in urls.py: urlpattens = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I upload a file using models.FileField() it displays fine via 127.0.0.1:8000/media/myfile.txt. However, when I shell into the server to find it /vol/web/media is empty. I would expect the file I upload to be in this directory, per the docs, but it is not. I have confirmed the following: 127.0.0.1:8000/media/myfile.txt returns myfile.txt even when browser cache is cleared. 127.0.0.1:8000/media/notmyfile.txt returns /vol/web/media/notmyfile.txt does not exist, so the server appears to be configured correctly I have no CACHE settings set explicitly in settings.py. What could be going on here? Does Django cache MEDIA_ROOT somehow by default? -
Dynamically Change Django Form's Fields
In the django custom registration form I have ChoiceField see in the code below but what I want is to change the fields according to the ChoiceField options. for an example if the ChoiceField is selected as Student then I want to hide the "email field" or might add extra field. I know i can do this with JavaScript but i want to change from the form. class Signup_Form(UserCreationForm): def __init__(self, *args, **kwargs): super(Signup_Form, self).__init__(*args, **kwargs) # below changing on the fields of this form. self.fields['first_name'].label = "First Name" self.fields['last_name'].label = "Last Name" self.fields['email'].label = "Email" SIGNUP_USERS_TYPES = ( ('Student', 'Student',), ('Admin', 'Admin',),) user_type = forms.ChoiceField(choices = SIGNUP_USERS_TYPES, required=True, label="Sign-up as :",) class Meta: model = User fields = ['user_type', 'first_name', 'last_name','email', 'username', 'password1', 'password2' ] -
Is there a way to take JSON from swagger 2.0 in views and convert it into HTML and send it to the template in Django?
I want to use some JSON that coming from a Swagger 2.0 generated website and parse it to send it back to a template page in my Django project. I'm asking if there is a simple way to do it, like an import (I searched but without result), thanks. def swagger_documentation(request): reply = requests.get("http://example.com:5005/swagger.json") content = reply.json() <!-- Transform content into HTML here --> data = ? return render(request, 'features/documentation/doc.html', data) (doc.html) {% extends 'layout/master.html' %} {% load static %} {% block content %} I want to show it here {% endblock %}