Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix IntegrityError?
I have a slug field and unique=True and this save() method for the convert title of model to slug. def save(self,*args, **kwargs): try: self.slug = slugify(self.title) except IntegrityError: self.slug = slugify(self.title + str(self.id)) super(Post,self).save(*args, **kwargs) I want to add id of object when same titles are given but I get an IntegrityError page. Why is this happening? -
DJANGO <OPTION> element with EXTRA ATTRIBUTES
How can we add some extra tags to DJANGO FORM MODEL tag element? I all-read tried change something inside form.py/class META/widgets but without nothing. class MySelect( forms.Select ): def __init__( self, attrs = None, choices = (), option_xtra_attr = '' ): self.option_xtra_attr = option_xtra_attr super( MySelect, self ).__init__( attrs, choices ) def render_option( self, selected_choices, option_value, option_label, option_xtra_attr = '' ): if option_value is None: option_value = '' option_value = force_text( option_value ) if option_value in selected_choices: selected_html = mark_safe( ' selected="selected"' ) if not self.allow_multiple_selected: # Only allow for a single selection. selected_choices.remove( option_value ) else: selected_html = '' return format_html( '<option value="{}"{}{}>{}</option>', option_value, selected_html, option_xtra_attr, force_text( option_label ) ) class MonitoringSpot_InLine_FORM( forms.ModelForm ): class Meta: model = MonitoringSpotClass fields = [ 'monitoringSpot_NODE_monitoringAreaType', ] widgets = { 'monitoringSpot_NODE_monitoringAreaType': MySelect( option_xtra_attr = { 'xdata': 'value' } ) } -
Django with WSGI and Apache issue
I am building an Django Application but having some trouble serving the application. My Server is running on RHEL 7 with apache 2.4.6 My httpd.conf file look like this WSGIPythonHome /home/venv WSGIPythonPath /home/app WSGIScriptAlias / /home/app/test/wsgi.py <Directory /home/app/test> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /home/app/static <Directory /home/app/static> Require all granted </Directory> Alias /media /home/app/media <Directory /home/app/media> Require all granted </Directory> My wsgi.py look like this import os import sys sys.path.append('/home/app') sys.path.append('/home/app/test') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.settings") application = get_wsgi_application() But when i try to run the application apache throw the following error message under the apache log file. ImportError: No module named site ImportError: No module named site -
Graphene Django image field get absolute path
I have an image field in my Django model and I am trying to get absolute path of the image field output from Graphene. I remember getting the absolute uri of a file/image field using HttpRequest.build_absolute_uri. So, I decided to use the same function in Graphene Django: class PersonType(DjangoObjectType): def resolve_photo(self, info, **kwargs): print(info.context) # WSGIRequest print(info.context.build_absolute_uri(self.photo)) # Error here return self.photo class Meta: model = Person Because the request here is not Django's HttpRequest (it is WSGI Request), I am not able to use some utility functions of Django's request. Is there a way to create HttpRequest from WSGIRequest or is there some other way of building full URLs in Graphene Django? Reading docs, source code, or resources in the internet, I am not able to find a solution to my problem. -
How to detect bounce mails to prevent zoho mail block in django
I'm using zohomail as my SMTP service. For some days zoho blocks me because almost each day. I asked them for reason they say your bounce rate has increased. I checked the logs and I found out something. some of new users for signup entered a wrong email address and they try again and again to receive activation email. so their mail counted as bounce mails. How can I handle this problem. I'm using django 2.0.2 and django-allauth as my authentication app. my ACCOUNT_EMAIL_VERIFICATION is set to mandatory. Should I do something with that? Can this kind of issued be handled. -
Django in Docker without exposing to LAN
When running Django in a container, I am unable to access it unless running with python manage.py runserver 0.0.0.0:8000. However, doing so allows anyone on my network to connect, which I do not want. In my docker compose file, I have: ports: - "8000:8000" When accessing 127.0.0.1:8000 by just running python manage.py runserver, I get an ERR_EMPTY_RESPONSE error. Is there any way of accessing my server without opening it to the whole network? -
How to use TimeInput widget in Django forms?
TimeInput is not working for the form given below. But SelectDateWidget() works fine. No error is created for current TimeInput() widget. Suggest the correct way to use TimeInput widget. forms.py class TournmentDetails(forms.ModelForm): class Meta(): model = Tournament fields = ('eventname','venue','date','time') widgets = { 'date': forms.SelectDateWidget( empty_label=("Choose Year", "Choose Month", "Choose Day"), ), 'time': forms.TimeInput(format='%H:%M'), } -
How to get int value from IntegerField in a ModelForm
I was asigned a small "homework" after an interview, but I've been stuck with a silly problem for days now. Technology: Python+Django Homework description: I have to present the user with a form that allows the user to create a task. The task has a description, a category and a duration. When the user creates the task, the site should redirect him/her to a site listing all tasks that are still in progress. That means that I have to calculate the expiry date of the task taking into account holidays and working hours (from 9am to 6pm). Problem: I can't seem to get the task duration (IntegerField) from the ModelForm as an int in order to add it to datetime.now().hours to check if that sum is bigger than 6pm. If that's the case, then I know the task expires on a another day. I've been told to try setting the IntegerField as DurationField, but it didn't help. Here's the relevant code: This is a method in the CreateTask view def calculate_expiry_date(self, start_date, duration): if start_date.hour + duration < WorkHourSetting.end_hour: result_date = models.DateTimeField() result_date.hour = start_date.hour return result_date else: new_duration = duration - (WorkHourSetting.end_hour - start_date.hour) new_date = start_date while Holiday.objects.get(date=new_date) … -
How to properly configure django-rest-swagger
I am trying to implement django-rest-swagger in one of my projects, but I get the following error: Internal Server Error: /api/docs/ Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework_swagger/views.py", line 32, in get schema = generator.get_schema(request=request) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 281, in get_schema links = self.get_links(None if public else request) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 319, in get_links link = view.schema.get_link(path, method, base_url=self.url) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/schemas/inspectors.py", line 217, in get_link fields += self.get_filter_fields(path, method) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/rest_framework/schemas/inspectors.py", line 412, in get_filter_fields fields += filter_backend().get_schema_fields(self.view) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django_filters/rest_framework/backends.py", line 131, in get_schema_fields filterset_class = self.get_filterset_class(view, queryset) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django_filters/rest_framework/backends.py", line 73, in get_filterset_class class AutoFilterSet(self.filterset_base): File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django_filters/filterset.py", line 71, in __new__ new_class.base_filters = new_class.get_filters() File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.6/site-packages/django_filters/filterset.py", line 352, in get_filters "%s" % ', '.join(undefined) … -
How to solve Memory Error with Spacy PhraseMatcher?
Highlevel Background I'm working on a project where in the first step I'm searching for keywords and phrases inside a large text corpus. I want to identify passages/sentences where these keywords occur. Later I want to make these passages accessible through my local postgres db for the user to query information. The data is stored on Azure Blob Storage and I'm using Minio Server to connect my Django application. Actual Problem First my shell was killed and after some try-and-error refactoring/debugging a memory error, when running my script that: samples 30 (I want to sample 10000 but it breaks already at low numbers) random text documents from the blob storage, preprocess the raw text for the nlp task, streams the text through spacy's nlp.pipe to get a list of docs and streams the list of docs to PhraseMatcher (which passes on_match the rule_id, start token of a sentence (with match), the sentence, hash_id to a match_list). At first the shell was killed. I looked into the log files and saw that it was a memory error, but to be honest I'm quite new to this topic. After rearranging the code I got an MemoryError directly inside the shell. within th … -
Trying to create a multiple user signup in Django, where a company can simply add users via email, and the users can complete the signup
I'm creating a piece of software for small/very small companies where I want to be able to partially add users via first name, last name, and email. Basically the admin user adds first, last, and email into a formset factory and the user is partially created, then the user gets an email and may choose to dismiss the signup (delete the user), or set a password and login. I am trying to do this by basically forcing a password reset. I can't get that to work however. :/ @login_required def employees_add(request): # try: u = request.user e, c = some_stuff(u) if e.admin_level <= 2: a_e_formset = formset_factory(Add_Employee_Form, extra=10) if request.method == 'POST': formset = a_e_formset(request.POST) if formset.is_valid(): # c = Company.objects.get(id=request.user.employee.company.id) with transaction.atomic(): for form in formset: if form.is_valid(): if form.has_changed(): _p = User.objects.make_random_password(length=60) _u = User.objects.create_user( username=form.cleaned_data['email'], email=form.cleaned_data['email'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], password=_p ) _u.refresh_from_db() _e = _u.employee _e.company = c _e.save() send_mail( 'Subject here', 'Here is the message.', 'noreply@mysite.com', [_u.email], fail_silently=False, ) return HttpResponseRedirect(reverse('home')) context = { 'formset': formset, } return render(request, 'punchclock/add_employees.html', context) else: formset = a_e_formset() context = { 'formset': formset, } return render(request, 'punchclock/add_employees.html', context) return HttpResponseRedirect(reverse('permission_denied')) # except: # return HttpResponseRedirect(reverse('permission_denied')) I've tried using the PasswordResetForm, … -
Files uploaded through Django admin console have wrong permissions
I have a section of my website cordoned off simply as a repository/free hosting service for projects I make. I have a simple Django project called personal dedicated to this within my website - the process, ideally, is Upload a file to the personal database, via the admin console (via mysite.com/admin) this is saved at /static/media/personal/[foldername]/myproject Assign that file a short tag (e.g. myproject) That file should now be accessible to anyone at mysite.com/personal/myproject, which will redirect to the static file I uploaded. My issue is that the files I upload are getting saved with permissions 0600, so when I try to access them later with my web browser I get a 403 Forbidden error. I can go in to the server manually and change the permissions to 0644 and then it works fine, but I'd like Django to do this for me. I've already tried putting the following in my website's settings.py file: FILE_UPLOAD_PERMISSIONS = 0o644 which was the only real thing I was able to find through my research that I could understand. Unfortunately, this doesn't seem to have helped. The model I'm using for this personal database is as follows: def generate_filename(instance, filename): if instance.folder and len(instance.folder) … -
Django 2.1.7: Makemigrations command result: "No change detected in app"
(I am aware that a number of Django users have had the same issue. I have looked at a number of solutions online but none has worked for me so far.) I have set up my apps.py, settings.py and models.py files as explained in Django official tutorial (please see the 3 files below) When I enter in the terminal: $ python3 manage.py makemigrations munichliving_app it returns: " No changes detected in app 'munichliving_app' " (file settings.py) in INSTALLED_APP --> I added and tested both one at a time: 'munichliving_app' and 'munichliving_app.apps.MunichLivingConfig' apps.py file: https://pastebin.com/raw/qaYy1x44 setting.py file: https://pastebin.com/raw/cSsbfPsx models.py: https://pastebin.com/raw/U0QeM16k Django official tutorial states that I should see something along the lines of: Migrations for 'polls': polls/migrations/0001_initial.py: - Create model Choice - Create model Question - Add field question to choice Thank you. -
Django - how to add another feild in icontains to search
Currently studying django. I'm trying to add genre icontains for my existing search which only fetch title. but i wonder why i'm getting error of "Cannot resolve keyword " this is my search code in views.py def Search(request): queryset = Book.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(genre_icontains=query) ).distinct() context = { 'queryset': queryset } return render(request, 'search_results.html', context) heres is my book model. class Book(models.Model): title = models.CharField(max_length=200) ```some fields``` genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) -
Django web application issue
While accessing the web page https://stockex.n2s.co.uk whether you try to enter any product side you can not see any product there. You can see the error in inspect mode. Can you please provide me the solutions. -
My Django image cant upload when i tried to update it
i am building a blog with django i successfully created a new post but when i tried to update the post everything updated but the image didnt update, it did not upload the image to the upload_to in the Posts model here is my code view.py @login_required def UpdatePost(request, pk): obj = get_object_or_404(Posts, id=pk) myForm = NewPostForm(instance = obj) if request.method == 'POST': myForm = NewPostForm(request.POST, request.FILES, instance=request.user.profile) response_data = { 'SType': 'danger', 'message': "An Error Occured, pls try again later" } title = request.POST.get('title') content = request.POST.get('content') category_id = request.POST.get('category') image = request.FILES.get('image') if myForm.is_valid(): if Posts.objects.filter(pk=pk).update(title=title, content=content, image=image, category_id=category_id, author_id=request.user.id): response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") context={ 'form':myForm, 'title': obj.title, 'category': Category.objects.all() } return render(request, 'blog/update.html', context) update.html <form action="." method="POST" enctype="multipart/form-data" id="PostNew__form"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Update a Blog Post</legend> <div class="form-row"> <div class="form-group col-md-8 mb-0"> {{ form.title | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.category | as_crispy_field }} </div> </div> {{ form.content | as_crispy_field }} <div class=""> {{ form.image | as_crispy_field }} </div> </fieldset> <div class="form-group"> <h6 id="PostNew__show" ></h6> <img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostNew__img"> <button class="btn btn-outline-info float-right" type="submit" id="PostNew__submit">Update</button> </div> </form> … -
django dynamic update forms fields without page refresh
I have build some django form using choose field with foreign key field. All works fine but I want to ask for this fields some things. In my app because needed used to many users works together I need this fields(choose field)to be dynamic and update select values without user refresh page to see last table upadates. is possible to update the values from this choose fields forms or foreign key form field without refresh page ? forms.py class myForm(forms.ModelForm): field_2= forms.ModelChoiceField(queryset=mymodel_2.objects.all(),label="ΔΙΕΥΘΥΝΣΗ") class Meta: model = Mymodel fields = ('field_1', 'field_2', 'field_fk') models.py class Mymodel(models.Model): field_1 = models.CharField(max_length=100, blank=True, null=True) field_2 = models.CharField(max_length=254, choices=EIDOS_PROSWPOU_CHOICES, blank=True) eidos = models.CharField(max_length=254,choices=EIDOS_PELATHS_CHOICES,blank=True, null=True) field_fk= models.ForeignKey('category', blank=True, null=True) class category(models.Model): title = models.CharField(max_length=100, blank=True, null=True) class mymodel_2(models.Model): task = models.CharField(max_length=100, blank=True, null=True) html: <form enctype="multipart/form-data" method="post" action="">{% csrf_token %} {{ form.as_p }} <input type="submit"/> in the html : <div class="row form-group"> <label>field_fk :</label><select name="field_fk" id="field_fk"> <option value="" selected=""></option> <option value="some value 1">some value 1</option> <option value="some value 2">some value 2</option> <option value="some value 3">some value 3</option> <option value="some value 4">some value 4</option> </select></div> -
Need a code approach/recommendation [python,django,html]
I am working with django and python and my goal is to be able to make some type of python function call (without refreshing page) to display different information based on onclick events. Some generic code below shows my setup. Essentially, when a button inside parent2 is clicked I want to be able to make a function call with that buttons id to some python function. Then I want to basically rerender part of the page to display the results inside parent1. Im not sure how realistic this is but, would appreciate any help in the right direction. <div id="parent1"> <div class="child_style"> {%for i in mydata1%} <div> my child 0</div> ... {% endfor %} </div> </div> <div id = "parent2"> <div class="other_style"> {%for j in mydata2%} <div><div><div><div><a id="..">Button0</a></div></div></div></div> ... {% endfor %} </div> </div> -
Django Rest Framework return empty JSON
I juste start to implement Django Rest Framework by following several tuto, however I can't fix my issue. Actually, my API return empty JSON string : [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}] This my code : from rest_framework import serializers from wall.models import Articles serializer.py class ArticlesSerializer(serializers.Serializer): class Meta: model = Articles fields = ('title',) views.py class ArticlesView(generics.ListAPIView): queryset = Articles.objects.all() serializer_class = ArticlesSerializer urls.py url('articles/', ArticlesView.as_view(), name="api-articles"), models.py class Articles(models.Model): title = models.CharField(max_length=100, null=False, verbose_name="Titre") I have many articles, so the JSON is returning as many article as I have in my database, but nothing else is displayed. Why ? -
Django channels - websocket_disconnect being called in loop
I am using Django-channels in order to provide instant notifications when a new instance of a model is created. For this purpose, I am using django-channels and a SyncConsumer. Everything is working as it should, except the websocket_disconnect which is being called in loop n times. Here is my consumer code: class BaseConsumer(SyncConsumer): subscriber = "user" monitored_entity = "entity" user_id = "123456789" def websocket_connect(self, event): self.send({"type": "websocket.accept"}) def websocket_receive(self, event): async_to_sync(self.channel_layer.group_add)\ ("{}.{}.id.{}".format(self.subscriber, self.monitored_entity, self.user_id), self.channel_name) def websocket_forwardticket(self, event): data = event.get("text") self.send({"type": "websocket.send", "text": data}) def websocket_disconnect(self, event): print("websocket_disconnect") Here is the log from my web server: api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect api_1 | websocket_disconnect And this goes on and on until I stop the web server. This behaviour happens for both when I close manually the connection in the frontend (I'm using Javascript, so I call ws.close()) and if I close the browser tab/client. This doesn't look to me to right behaviour, as I can hear my computer fans working like hell. Has anyone else experiences something like this? Thanks! -
Converting formData to forms.Form in django
I would like to allow user to key in a quiz code and gets an alert to tell whether if the code is still invalid without refreshing the page. I already read a lot of Django AJAX and JQuery tutorials but most of them seem outdated because they do not cover the part where csrf token must be send. In my settings.py, I set CSRF_USE_SESSIONS to True. This is my forms.py class codeForm(forms.Form): code = forms.IntegerField(label='Question Code') In my html file, I have this <form class="card__form" id=code-form"" method="POST"> {% csrf_token %} <script type="text/javascript"> // using jQuery var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); </script> {{form.as_p} <center><input type="submit" class="btn btn-primary card__submit" id="submit_code"></center> Just before the tag, I have this : <script> $(document).ready(function(){ $("#submit_code").click(function(){ alert("Text: "); event.preventDefault(); var myform = document.getElementById("code-form"); var form = new FormData(this); form.append('csrfmiddlewaretoken', csrftoken); $.ajax({ data : form, dataType:'json', type: 'POST', method: 'POST', url: '{% url 'student:process_code' %}', contentType: false, processData: false, success: function(context) { alert(context.msg); }, error: function(context) { alert(context.msg); } }); }); }); </script> In my views.py def process_code(request): context = {} if request.method == 'POST': form = codeForm(request.POST) if form.is_valid(): cd = form.cleaned_data code = cd.get('code') print('yay') if code.isdigit(): The unexpected result was the form is not valid … -
Double loop for in template
I've actually a problem with my template and my loops. I have the same problem described here : Double loop in Django template I have tryed the answer but it doesn't work :/ And I don't understand the django documentation about backward relationship I've tryed to prefetch_related and selected_related like in the link above and other search about my problem but I don't really understand what does it do. Models : class Categories(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class SousCategories(models.Model): #subcategories name = models.CharField(max_length=255) categorie = models.ForeignKey(Categories, on_delete=models.CASCADE, null=True) def __str__(self): return self.categorie.name + " " + self.name View : def index(request): response_dict = dict() lst_cat = [] lst_ss_cat = [] for cat in Categories.objects.all(): all_cat = dict() all_cat['id'] = cat.id all_cat['name'] = cat.name lst_cat.append(all_cat) for ss_cat in SousCategories.objects.all(): all_ss_cat = dict() all_ss_cat['id'] = ss_cat.id all_ss_cat['name'] = ss_cat.name all_ss_cat['cat'] = ss_cat.categorie lst_ss_cat.append(all_ss_cat) response_dict['categorie'] = lst_cat response_dict['ss_cat'] = lst_ss_cat print(response_dict) return render(request, "home.html", {'cat': response_dict}) This view give me this (Few datas just for test) : {'categorie': [{'id': 1, 'name': 'playmobil'}, {'id': 2, 'name': 'deguisements'}], 'ss_cat': [{'id': 1, 'name': 'neuf', 'cat': <Categories: playmobil>}, {'id': 2, 'name': 'occasion', 'cat': <Categories: playmobil>}, {'id': 3, 'name': 'propre', 'cat': <Categories: deguisements>}, {'id': 4, … -
Is there a solution to get context from form_valid to get_context_data which disapear after refresh site
I'm trying to print a message after uploading file. My message should disappear after refresh site. In my exercise i have to use get_context_data() . I need to do that without Models. I've tried to do that using __init__ method but I don't know why it is called twice. views.py class UploadView(FormView): template_name = "startup/upload.html" form_class = UploadDocumentForm success_url = reverse_lazy("xxx:upload") def __init__(self, **kwargs): super().__init__(**kwargs) status_logs = {} def form_valid(self, form): file = self.request.FILES['file'] today = 'ts_' + str(time.time()) fs = FileSystemStorage(os.path.join(settings.MEDIA_ROOT, today)) fs.save(file.name, file) file_logs = "dddddd" self.status_logs['file_logs'] = file_logs return super().form_valid(form) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['status_logs'] = self.status_logs return ctx forms.py class UploadDocumentForm(forms.Form): file = forms.FileField() -
map background task related consumer in channel
I am using django-channel so that i can use it for chat related task in near future. Right now, I need to handle some background task like sending activation mail, password reset mail and counting the percentage of profile completeness etc. I wrote the consumer but i have no idea on how i use routing to map that consumer. Here is my settings ASGI_APPLICATION = "config.routing.application" project_name/routing.py (how do i map the consumer here) from channels.routing import ProtocolTypeRouter from django.urls import path application = ProtocolTypeRouter({ }) accounts/consumers.py import logging from django.forms.models import model_to_dict from djoser.compat import get_user_email from djoser.email import ActivationEmail, PasswordResetEmail from apps.accounts.models import Profile logger = logging.getLogger('email') def send_activation_email(user, request): to = [get_user_email(user)] ActivationEmail(request, {'user': user}).send(to) def send_password_reset_email(user, request): to = [get_user_email(user)] PasswordResetEmail(request, {'user': user}).send(to) def profile_percentage(profile_id): weight = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10} total = 0 try: profile_instance = model_to_dict(Profile.objects.get(id=id)) for field in profile_instance: try: total += weight[field] except AttributeError: logger.error("Could not find the field") continue except Profile.DoesNotExist: logger.error("Profile does not exist") return return total Note: I am using django-channel 2. -
How to fix ' Not Found: /{% static 'anyfile.html, css % } '
I am adding the styles and scripts to the templates in Django, the rest of the files are getting added but there are two which the server says 'NOT FOUND' I tried to run a new local host, and it is still the same. Not Found: /{% static 'css/all.css' % } Not Found: /{% static 'css/bootstrap.css ' % } If this works perfectly, the output should run a nice webpage.