Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want that when I select grade year the specific subject for that grade year will appear
I want that when I select grade year the specific subject for that grade year will appear I want that when I select grade year the specific subject for that grade year will appear //test.html //here is my code in html <select id="id_of_select" name="subject"> <option>--</option>**strong text** {% for ylvl in edulevel %} <option value="{% for sub in subj %} {{sub.Description}}<br> {% endfor %}">{{ylvl.Description}} </option> {% endfor %} </select> <button id="btn">Show selected</button> <div id="display"> </div> <script> function show_selected() { var selector = document.getElementById('id_of_select'); var value = selector[selector.selectedIndex].value; document.getElementById('display').innerHTML = value; } document.getElementById('btn').addEventListener('click',show_selected);; </script> //views.py def test(request): edulevel = EducationLevel.objects.all() id=request.GET.get('id_of_select') print(id) subj = Subject.objects.all() context = { 'edulevel':edulevel, 'subj':subj } return render(request, 'accounts/test.html',context) I want that when I select grade year the specific subject for that grade year will appear -
can't access to django web site with nginx on specific port, connection timed out
I try, in vain, to set up a demonstration website running under django. On azure we have 2 virtual machines accessible from a public address. The website must be launched on a azure virtual machine. Both virtual machines deploy a nginx server, but when I launch a nginx server on the 2nd virtual machine on another port, it's time out. It seems to me that this is a configuration problem. The configuration I use is based on nginx, gunicorn , supervisor , django. This is the django /site_show/miss_site/miss_site/setting.py file : '''python ALLOWED_HOSTS = ['168.63.54.50', "*"] STATIC_ROOT = '/site_show/miss_site/static/' MEDIA_ROOT= os.path.join(BASE_DIR, 'media/') MEDIA_URL= "/site_show/miss_site/media/" TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',) SITE_ID = 1 ''' some django file : /site_show/miss_site/manage.py /site_show/miss_site/media and /site_show/miss_site/static/ also /site_show/miss_site/templates/ where the index.html is config file for nginx ''' upstream sample_project_server { server unix:/site_show/miss_site/gunicorn.sock fail_timeout=0; } server { listen 8008; server_name 168.63.54.50; client_max_body_size 4G; access_log /site_show/miss_site/logs/nginx-access.log; error_log /site_show/miss_site/logs/nginx-error.log warn; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect http; if (!-f $request_filename) { proxy_pass http://sample_project_server; break; } } location /static/ { autoindex on; alias /site_show/miss_site/static/; } location /media/ { autoindex on; alias /site_show/miss_site/media/; } ''' launch script : ''' NAME="showcase" DJANGODIR=/site_show/miss_site SOCKFILE=/site_show/miss_site/gunicorn.sock USER=www-data … -
How to pass params dynamicaly from template to ListView in Django?
I want to pass params dynamically to ListView via URL: views.py: from django.shortcuts import render from django.views import generic from objects.models import Object class UserObjectsView(generic.ListView): template_name = 'user_objects.html' def get_queryset(self): return Object.objects.all() urls.py: from django.urls import path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects') ] template where I call this url: <h3><a href="{% url 'user-objects' %}{{ user.id }}">Objects</a></h3> I want to pass this user.id dynamically, but right now it appers error: Reverse for 'user-objects' with no arguments not found. 1 pattern(s) tried: ['objects/user/(?P[0-9]+)/$'] -
User Profile picture not displaying on the template but saved to media File
devs...mayday mayday... I want the user profile picture to be displayed on the user dashboard after login, the image saves into the media file, i can display every other details pertaining to the user, but the image is not displaying, the picture is been uploaded when the user wants to update profile details, and not at the point of signup, please any help is appreciated ..Thanks a lot . template <img class="profile-user-img img-responsive img-circle" src="{{ request.user.get_profile.picture.url }}" alt="User profile picture"> <h3 class="profile-username text-center">{{ user.full_name }} {% if user.is_verified %}<i class="fa fa-check btn-primary img-circle"></i>{% endif %} </h3> views.py def image_update(request): if request.method == 'POST': image = request.FILES['image'] # profiles = get_object_or_404(Profile,user=request.user) try: profile = get_object_or_404(Profile,user=request.user) except Profile.MultipleObjectsReturned: profile = Profile.objects.filter(user=request.user)[0] profile.picture = image profile.save() return redirect('app:preferences') else: raise Http404 models.py class Profile(models.Model): user = models.ForeignKey(CustomUser, related_name='profile', on_delete=models.CASCADE) picture = models.ImageField(blank=True, default='user.png', upload_to='images/') -
wifi control using django with billing so users can come subscribe and buy online with cards
is there a Django base application to control and tax my WiFi like the case with a cyber cafe . may be using online payments. also i want to be able to to create my own custom page . if you know of any u please recommend me -
Why does an error occur when saving the form?
There are two models models1 class Work(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='employee_projects') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_work') ... responsibility = models.TextField("employee work responsibility", blank=True) models2 class Project(models.Model): name = models.CharField("project name", max_length=64) description = models.TextField("project description") technologies = models.ManyToManyField( Technology, verbose_name="technologies used on the project") I use modeinlineformset to create new objects forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['name', 'description', 'technologies'] ProjectFormSet = inlineformset_factory(Project, Work, fields=['responsibility', 'start_year', 'start_month', 'end_year', 'end_month'], extra=1) and my views.py class WorkCreateView(AuthorizedMixin, CreateView): """ Create new course instances """ model = Project form_class = ProjectForm template_name = 'work_edit.html' def get(self, request, *args, **kwargs): .... def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) project_form = ProjectFormSet(self.request.POST) if form.is_valid() and project_form.is_valid(): return self.form_valid(form, project_form) else: return self.form_invalid(form, project_form) def form_valid(self, form, project_form): self.object = form.save() project_form.instance = self.object project_form.save(commit=False) project_form.instance.employee = Employee.objects.get(pk=self.kwargs['pk']) project_form.save() return redirect('{}#experience'.format(reverse('profile', kwargs={'pk': self.kwargs['pk']}))) def form_invalid(self, form, project_form): ... But get an error null value in column "employee_id" violates not-null constraint I know what this mistake means, but I don't understand why this happens if I assign a value of the current employee to instance.employee. -
Return json response instead of list of Django models
I am new to python and Django, this is my first project. I followed a tutorial which returned a list of objects. I want to return json instead. I have tried JsonResponse, json.dump but I don't think im implementing these right class ListVenuesView(generics.ListAPIView): serializer_class = VenueSerialiser def get_queryset(self): queryset = (Venue.objects.all()) location = self.request.query_params.get('location', None) latitude = location.split('S')[0] longitude = location.split('S')[1] venue_gaps = {} for venue in queryset.iterator(): locationArray = [y.strip() for y in venue.postcode.split(',')] distance = gmaps.distance_matrix([str(latitude) + " " + str(longitude)], [str(locationArray[0]) + " " + str(locationArray[1])], mode='driving')['rows'][0]['elements'][0] m = distance["distance"]["value"] venue_gaps[m] = model_to_dict(venue) sorted_venues = dict(sorted(venue_gaps.items())) #print(sorted_venues) jsonResponse = json.dumps(venue_gaps, sort_keys=True) print(jsonResponse) return JsonResponse({'data':jsonResponse}, safe=False) This currently throws Got AttributeError when attempting to get a value for field `name` on serializer `VenueSerialiser`. If I replace the return line with return Venue.objects.all() I get a 200 but I need it in json class VenueSerialiser(serializers.ModelSerializer): class Meta: model = Venue fields = ('name', 'location', 'capacity', 'photo_url', 'accomodation', 'cost', 'description', 'postcode', 'email', 'website') -
UpdateView is complaining of missing model and queryset Django?
I get this strange error when I use UpdateView to get an instance of my modelobject. UpdateView is missing a QuerySet. Define UpdateView.model, UpdateView.queryset, or override UpdateView.get_queryset(). Its strange to me because I have defined both queryset and model in my UpdateView CBV. What could I be missing out on ? class ContactUpdate(UpdateView): queryset = Contact.objects.all() model = Contact class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField() address = models.CharField(max_length=100) phone = models.CharField(max_length=50) class Meta: verbose_name = 'Contact' verbose_name_plural = 'Contacts' def get_absolute_url(self): return reverse('contact_detail',kwargs={'pk':self.pk}) -
how to communicate between different sessions in django or flask
here is an application case, my description is simplified. here are 3 roles of a website: admin, moderator, and visitor admin can control everything, moderator manages some part of the website, and visitors can post threads and read threads the relationship of the users, roles and permissions are stored in the database in RBAC style now admin want to downgrade a moderator to visitor, it's easy to manipulate the operation in the database. but if the moderator is still online when this action is performed, there will be problem. the admin and the moderator have two different session, and to accelerate the website speed, normally we put the roles and permissions in session, we don't query it every time when the user send request, so the admin's manipulation would not modify the session of the moderator. once the moderator session is not expired, the moderator still has the permissions. so the essential requirement is how to manipulate one session by another session in the web service. my website is based on python. Because RBAC is required, so I prefer flask more than django django.auth module can control the access permission to each model, but what we want to control is … -
Serialize models like with .values(), but also include ManyToMany related field
class Book(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, related_name="books") I'm have pre-existing JavaScript code that works on input that I feed from django like this: json.dumps(list(Book.objects.all().values()), cls=DjangoJSONEncoder) list(Book.objects.all().values()) gives me an array of dictionaries upon which my entire frontend code is based on. [{ "user": 1 }, { ... }, ... ] However, now I've added the tags property. I was expecting to find the tags property in my dictionary but there's not: apparently, Django doesn't serialize ManyToMany managers by default. The offered solution is this: from django.core import serializers serializers.serialize("json", Book.objects.all()) that, however, outputs a dictionary that it's in a completely different form, where all my model properties are inside of a fields parameter. [{"model": "Main.book", "pk": 1, "fields": { "user": ... }] How can I have a tags field like with serializers.serialize while maintaining the .values() form? Do I have to re-write my frontend code entirely to use the format of serializers.serialize or is there a simpler solution? -
Running and controlling python scripts from django Views
My Django View will run a big and quite complex task. It will run a few python scripts to prepare the data and then it will feed generated files to big Java aplication that will run the task. Once run, the Task may run for a few hours. What im aiming at is to create a view that will act as a supervisor for the whole process. It should be able to: Start whole process Get feedback from working python scripts once they are complete Be able to stop the process at any time I have considered things like subprocess or multiprocess but i dont think that they will do the task. Subprocess will either block the View, or i wont be able to get the results. The biggest issue i am facing is the ability to interact django view with running python script. What i would like to achive would look something like this in pseudocode: if 'cancel' in POST: process.stop() #sends kill signal to running instance if 'start' in POST: process.start() #begins the task if 'get_info' in POST: progress = process.communicate() return({'progress':progress}) I am looking for recomendation on how to solve this issue neatly. I am wondering if … -
Django Rest Framework APIClient not handling exceptions during tests
I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model). from rest_framework.test import APITestCase class TestMyView(APITestCase): # ... def test_bad_request(self): # ... response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) However, my test errors out with an exception instead of passing. It doesn't even fail because it gets a 500 instead of 400, it doesn't even get there at all. Isn't DRF's APIClient supposed to handle every exception? I've search online but found nothing. I've read that DRF doesn't handle Django's native ValidationError, but still that doesn't explain why I am not even getting a 500. Any idea what I'm doing wrong? -
I lose data in my serializer (django/angular)
I have data in my front that I get from my serializer except that I lose two data "user" and "establishment". const workplaceBody = { "user": this.currentUser.id, "establishment": response.body.id, "is_main_establishment": false }; When I print validated_data in my serializer I only have one "is_main_establishment" data. {'is_main_establishment': False} I want to create a workplace linked to an establishment. this.workplaceEstablishment.create(workplaceBody).subscribe(response => { console.log(response); }); My workplacesSerializer: class WorkplacesSerializer(ModelSerializer): id = IntegerField(source="establishment.id", read_only=True) name = CharField(source="establishment.name", read_only=True) type = CharField(source="establishment.type", read_only=True) selected = SerializerMethodField() def get_selected(self, instance): #print(instance) #print(self.context["request"].data) return ( get_selected_establishment_id_from_request(self.context["request"]) #"== instance.id ) def create(self, validated_data): print(validated_data) workplace = UserWorksAtEstablishment.objects.create( **validated_data, establishment_id=validated_data.establishment, user_id=validated_data.user ) return workplace class Meta: model = UserWorksAtEstablishment fields = ("id", "name", "type", "is_main_establishment", "selected") I don't see why I'm losing this data. Thank you in advance -
Ajax FormData() is returning null file when uploading a file and a string
I have been looking for a way to upload a file to MongoDB by using the IP string to locate the correct document to upload. However, when I upload the file and check its field value in MongoDB it shows as null. I'm doubting that there might be an issue with the way I'm appending the file OR how I'm uploading it to MongoDB. HTML Code: <h5 class="modal-title h5Modal" id="htmlIP"></h5> <div class="modal-body"> <form method="POST"> <div class="form-group"> <label for="Uploadfile">Choose a File To Upload:</label> <input type="file" id="Uploadfile" accept="image/*,.pdf,.pptx" class="file-path"> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-primary submitFile" data dismiss="modal">Submit</button> </div> Ajax Code: $(document).ready(function() { $('.submitFile').on('click',function(){ formdata = new FormData(); var ID = $('#htmlIP').text(); var file = document.getElementById('Uploadfile').files[0]; formdata.append('Uploadfile', file); formdata.append('IP', ID); $.ajax({ type: "POST", url: 'PythonSubmit/', data: formdata, processData: false, contentType: false, success: function(data){ alert(data.version); window.location.reload(); }, error: function(err){ alert(err); } }); }); }); Python Code: def PythonSubmit(request): if request.method == "POST": PC_IP = request.POST.get('IP', False) FileUploaded = request.POST.get('Uploadfile') res = PC.uploadFileToDB(PC_IP,FileUploaded) data = { 'version' : res, } return JsonResponse(data) res accesses the function uploadFileToDB inside PC class and add the values using $set method which is as follows: uploadFileToDB: @staticmethod def uploadFileToDB(PC_IP, file): PC_collection = PC._get_collection() try: PC_collection.find_one_and_update({"ip":PC_IP}, {"$set":{"file":file}}) … -
How To Track Number of Times Post Was Shared - Django
The task I want to accomplish is simple: track the number of times a post on my blog has been shared because I want the number to be displayed beside the post. However, I cannot figure it out. Here is the the anchors with hrefs that allow the user to click on them and share the post on social media: <ul class="mb-30 list-a-bg-grey list-a-hw-radial-35 list-a-hvr-primary list-li-ml-5"> <li class="mr-10 ml-0">Share</li> <li><a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><i class="ion-social-facebook"></i></a></li> <li><a href="http://twitter.com/share?url={{ request.build_absolute_uri }}"><i class="ion-social-twitter"></i></a></li> </ul> I have a Post model with a variable called share_count. Obviously, I have a view that helps renders out the HTML too. My issue is that I do not understand how to connect the hrefs to my view in order to increment the share_count of the post in the database. I searched all over and could not find an answer, I would appreciate any helps or hints. -
Scrapy concatenate array elements inside div in python
I need to concatenate some text inside a <div> with xpath in Scrapy. The div has the next structure: <div class="col-12 e-description" itemprop="description"> "-Text1" <br> <br> "-Text2" <br> <br> "-Text3" </div> I've created a ScrapyItem in my Spider: class MyScrapyItem(scrapy.Item): name = scrapy.Field() description = scrapy.Field() If I do this, item['description'] = response.xpath('//div[@itemprop="description"]/text()').extract() everything gets mixed and separated by commas, like this: - Text1 ,- Text2 ,- Text3 I think that's because response.xpath('//div[@itemprop="description"]/text()').extract() returns an array so it adds commas to separate the array items. I'm trying to loop over the array and join each item inside the "description" ScrapyItem property. This is what I'm trying: def parse_item(self, response): item = MyScrapyItem() item['name'] = response.xpath('normalize-space(//span[@itemprop="name"]/text())').extract() for subItem in response.xpath('//div[@itemprop="description"]/text()'): item['description'] = " ".join(subItem.extract()) I know it would work if I could do something like this: for subItem in response.xpath('//div[@itemprop="description"]/text()'): item['description'] = " ".join(subItem.xpath('//div[@itemprop="something_here"]/text()')extract()) but the div that contains the text has no more tags inside. Any help would be appreciated, it's my first Scrapy project. -
Stripe API PaymentIntent and Billing with Python
I try to use the new Stripe's PaymentIntent system to be ready when SCA will be launched in EU. I only use one-time payment. I succeed to make the payment with the PaymentIntent following Stripe's documentation. But I'm unable to create a bill for every payment (I must have one according to the law), and I tried a lot of things. But first, I think I need to show my code to introduce the troubles I have. In my view, I create a Stripe Session : public_token = settings.STRIPE_PUBLIC_KEY stripe.api_key = settings.STRIPE_PRIVATE_KEY stripe_sesssion = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'name':'My Product', 'description': description, 'amount': amount, 'currency': 'eur', 'quantity': 1, }], customer=customer_id, success_url=f'{settings.SITE_URL}/ok.html', cancel_url=f'{settings.SITE_URL}/payment_error.html', ) Then, the user click on the "Purchase" button on my web page and is redirected to the Stripe's Checkout page. After the user filled his payment card informations, Stripe call my Webhook (according to the checkout.session.completed event triggered). Here's my webhook function code : @csrf_exempt def webhook_payment_demande(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None if settings.DEBUG is False: endpoint_secret = "whsec_xxx" else: endpoint_secret = "whsec_xxx" try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: … -
Django. Objects from several models, how to correct display url?
I have two models. I do filtering of objects by these models and display them in a template. Everything works fine, but an error occurs with url. my urls.py path('objects_model_A/<int:objects_A_id>', views.objects_A, name='objects_model_A'), path('objects_model_B/<int:objects_B_id>', views.objects_B, name='objects_model_B'), my views.py def index(request): objects_A = objects_A.objects.all().filter(is_published=True) objects_B = objects_B.objects.all().filter(is_published=True) queryset_list = list(chain(objects_A, objects_B)) context = {'queryset_list': queryset_list} return render(request, 'templates/index.html', context) def objects_A(request, objects_A_id): objects_A = get_object_or_404(objects_a, pk=objects_A_id) context = { 'objects_A': objects_A } return render(request, 'templates/objects_A.html', context) def objects_B(request, objects_B_id): objects_B = get_object_or_404(objects_b, pk=objects_B_id) context = { 'objects_A': objects_A } return render(request, 'templates/objects_B.html', context) my template.html {% if queryset_list %} {% for listing in queryset_list %} <div class="col-md-6 col-lg-4 mb-4"> <div> <a href="{% url 'objects_model_A' listing.id %}">Link </a> {% endfor %} {% endif %} Objects from different models are collected, have an appropriate data set, but url are wrong. The object with model_A, url: http://127.0.0.1:8000/objects_A/1 An object with model_B, url too: http://127.0.0.1:8000/objects_A/1 I understand the error in the template. Line <a href="{% url 'objects_model_A' listing.id %}. How to draw up URLs correctly so that objects from different models in the chain are displayed correctly. For object A was url: http://127.0.0.1:8000/objects_A/1 For object B was url: http://127.0.0.1:8000/objects_B/1 -
in search form enter wrong query get's me keyerror with pandas and django
in my basic search form with framework django , when i enter wrong keyword of a drug dataset in my search form gets me wrong like "KeyError" this search form work with pandas lib , so i am just want when i put word wrong do not show me error i want to show to the user message "nothing match try something else" this is the error when i put word not in my dataframe this is the error when i put word not in my dataframe the word is Tramadol this is my code def search_recommender(request): query = request.GET.get('q') if query: indices = pd.Series(df.index, index=df['drugName']).drop_duplicates() idx = indices[query] sim_scores = list(enumerate(cosine_sim[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[0], reverse=True) sim_scores = sim_scores[1:6] mov_indices = [i[0] for i in sim_scores] gg_will = df['drugName'].iloc[mov_indices] json = gg_will.to_json(orient='values') else: qs = DrugDataset.objects.all() df = qs.to_dataframe() json=df.filter(drugName='q') -
Django - Execute python script, pause and start again after user input
I'm building a django app. In the view function, I'm calling a script. Basically, those scripts will operate actions behind the scene for the end user (novice in python). Now I'd like some of my python scripts to interact with my user. For instance, I want to display my user a message telling him to do some specific actions, and also pause the python script as long as the user doesn't give its input so that the script continues. This works well in terminal using input("Please do XXX and press enter when done") which makes the script hang as long as the user doesn't press enter. Would you have any idea 1) how I could make my python scripts communicate (ie print some results on my django app) and also 2) make a pause during python script processing which, after receiving an input from user, starts again. Thanks -
Django Dropbox storage: Validation error in admin
I´m trying to configure Dropbox storage for a Django APP. I´m using "Django Storages" library wich seems quite straight forward. I got my key from dropbox and configures everything I could see in the "Django storages" docs. The problem is that when I try to load an image in the Admin (still didn´t try it any other way) I get the following error: ValidationError at /admin/stockbucket/productosbase/1/change/ 'C:/Users/Lia love/inventory/Kinemed APP/Kinemed APP/image001.png' did not match pattern '(/(.|[\r\n])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' I read several Stack posts but couldn´t get an answer. Any clues welcome. Thanks in advance! Settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stockbucket.apps.StockbucketConfig', 'storages',] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'MyRealDropboxToken' DROPBOX_ROOT_PATH = 'Kinemed APP' Model foto_1 = models.ImageField(upload_to='', default="", blank=True, null=True) foto_2 = models.ImageField(upload_to='', default="", blank=True, null=True) -
Django, running code later/re rendering after page is opened , when token is acquired
I'm building an application in Django that uses a form that needs to gather some data from an API the token to authenticate with this API is gathered by using a login flow. However when the token expires Django refuses to run, so refreshing the token by re-authenticating becomes impossible. Is their a way to run the code from the form after the login has happened so that Django does not try to run it on start-up. Or re-render the form when the page is opened/refreshed However this form requires some data from the that API. To access this API I need to use a token, this token is obtained by going to the login flow in the beginning of the application, which then stores the token for use within the application. However when the Token expires Django won't start. So it's impossible to go true the sign-in flow to obtain a new token. I'm using the Microsoft graph API and requesting data from the AzureAD. I've tried to place the part of the form in a Try: Except: This works however it doesn't reload with the correct information on refreshing or reopening the page containing the form. The form: … -
Vue.js initialization in Django
I'm using django and Vue.js to build some panels. I'm joining Vue.js to Django in test mode and I have this issue: "dist" vue.js folder is served using the django.contrib.staticfiles module, and when I ask for index.html anything is downloaded with no issues. http://127.0.0.1:8000/wwwdocs/index.html However, when vue.js start and download other stuff it fails because it tries to download data from another path: http://127.0.0.1:8000/css/appb17d7483.css http://127.0.0.1:8000/js/app.a322f2ed.js It removed the "wwwdocs" from the url. Is here a fast solution to solve this and have vue.js downloading the modules from the same path it was downloaded ( /wwwdocs ) ? -
Pass a list from view context to template and assign it as an array in the template
I am trying to pass some list from view context: def list_test(request): l = ['a', 'b', 'c'] context = {'l': l} return render(request, 'app/list_test.html', context) to front-end as a JS array: <script> let l = {{ l }} console.log(l) </script> This however, logs Uncaught SyntaxError: Unexpected token & in the console. I have tried putting the variable in double quotes: let l = "{{ l }}" but then the variable gets assigned as a one big string and with unwanted encoding: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;] Template loop will work: {% for x in l %} console.log("{{x}}") {% endfor %} but i don't want to iterate. I want to assign the list at once instead. Is there a simple way to do this? Should I somehow use the template loop to split the string into array items? -
Email is not receiving to reset password django rest-auth react js
I want to reset user password, for this purpose I am using django rest auth and I have react js on front end, the problem is when I request on http://127.0.0.1:8000/auth/password-rest, I got the message Password reset on 127.0.0.1:8000 and the link is provided with token and uid but on console whereas I want link in email,here below my code: settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xyz@hotmail.com' // correct email EMAIL_HOST_PASSWORD = 'xyzzzz' // correct password DEFAULT_FROM_EMAIL = EMAIL_HOST_USER ACCOUNT_EMAIL_REQUIRED = True React part: forgotPassword=(evt)=>{ evt.preventDefault(); const payload={ email:"nabeelayz@hotmail.com" }; axios.post('http://127.0.0.1:8000/rest-auth/password/reset/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) }; I am getting message in console but I want in my email.