Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Tasks are executing multiple times in Django Application
I have a Django application where I defined a few @task functions under task.py to execute at given periodic task. I'm 100% sure that the issue is not caused by task.py or any code related but due to some configuration may be in settings.py or my celery worker. Task does execute at periodic task but at multiple times. Here are the celery worker logs: celery -A cimexmonitor worker --loglevel=info -B -c 4 [2019-09-19 21:22:16,360: INFO/ForkPoolWorker-5] Project Monitor Started : APPProject1 [2019-09-19 21:22:16,361: INFO/ForkPoolWorker-4] Project Monitor Started : APPProject1 [2019-09-19 21:25:22,108: INFO/ForkPoolWorker-4] Project Monitor DONE : APPProject1 [2019-09-19 21:25:45,255: INFO/ForkPoolWorker-5] Project Monitor DONE : APPProject1 [2019-09-20 00:22:16,395: INFO/ForkPoolWorker-4] Project Monitor Started : APPProject2 [2019-09-20 00:22:16,398: INFO/ForkPoolWorker-5] Project Monitor Started : APPProject2 [2019-09-20 01:22:11,554: INFO/ForkPoolWorker-5] Project Monitor DONE : APPProject2 [2019-09-20 01:22:12,047: INFO/ForkPoolWorker-4] Project Monitor DONE : APPProject2 If you check above time interval, tasks.py executes one task but 2 workers of celery takes the task & executes the same task at the same interval. I'm not sure why 2 workers took for one task? settings.py .. .. # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True .. .. .. ######## CELERY … -
django - adding userprofile to registration form. getting csrf token error
I have a registration form and am adding a user profile to add another field. but when i submit i am getting CSRF error. need help to find what i a missing. First time when i submitted it was updated, then i am getting the CSRF error models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group = models.CharField(max_length=500) def __str__(self): return self.user.username views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) profile_form = UserProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = RegistrationForm() profile_form = UserProfileForm() context = {'form': form, 'profile_form':profile_form} return render(request, 'registration/register.html', context ) index.html ```python def index(request): if request.user.is_authenticated: username = request.user.username else: username = 'not logged in' context = {'username':username} return render(request, 'index.html', context) urls.py path('Register/', views.register, name='register'), -
Catching bulk events in Django
I have Book model. It has some fields like title, year publish and etc. Also, i have overrided save() method. When new books is adding, it checks if book exsists, it creating new directory with name self.title in MEDIA_ROOT path. def save(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) # check that at least one file is loading if all([self.pdf, self.fb2, self.epub]): raise ValidationError("At least 1 file should be uploaded!") # create book's directory if it not exists if os.path.exists(book_dir): raise ValidationError("This book is already exists!") else: os.mkdir(book_dir) # rename and edit storage location of books to book_dir for field in [self.image, self.pdf, self.fb2, self.epub]: field.storage.location = book_dir super().save(*args, **kwargs) # Call the "real" save() method. Also i have overrided delete() method, that just remove directory of deleted book. def delete(self, *args, **kwargs): book_dir = os.path.join(MEDIA_ROOT, self.title) rmtree(book_dir) super().delete(*args, **kwargs) # Call the "real" delete() method. delete() method works well if i delete only 1 book. But, if i want to delete multiple files (all actions take place in the admin panel), only DB records got deleted. So, i want to just catch this moment to remove directory of deleted book. -
m2m_changed when items added and removed
I'm wondering if it's possible to gather the 'end state' of a m2m field in Django? I'm currently using m2m_changed.connect(myfunction, sender=MyModel.tests.through) And I have: myfunction(**kwargs): action = kwargs.pop('action', None) instance = kwargs.pop('instance', None) if action in ["post_remove", "post_add"]: instance.owned_tests = instance.tests.count() instance.save() My problem is that if I add and remove items from the m2m field and then save, two m2m_changed signals are fired, one for the add, and one for the remove. Is there any way to group these together in order to only have myfunction called once when all changes to the m2m field are finished? -
2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)" in docker-compose up
I'm trying to start the server through docker-compose up I'm get an error: 2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)" docker-compose.yml version: '3' services: db: image: mysql:5.7 environment: MYSQL_DATABASE: 'slack_bot1' MYSQL_USER: 'root' MYSQL_PASSWORD: '' MYSQL_ROOT_PASSWORD: '****' volumes: - /opt/slack_bot/mysql_data:/var/lib/mysql redis: image: "redis:alpine" volumes: - /opt/slack_bot/redis_data:/var/lib/redis web: build: . command: python manage.py runserver 0.0.0.0:8001 ports: - "8001:8001" depends_on: - db Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /home/slack_bot ADD requirements.txt /home/slack_bot/ RUN set -e; \ apk add --no-cache --virtual .build-deps \ gcc \ libc-dev \ linux-headers \ mariadb-dev \ python3-dev \ ; RUN pip install -r requirements.txt ADD . /home/slack_bot/ EXPOSE 8001 CMD ["python", "manage.py", "runserver", "0.0.0.0:8001"] -
Django redirect user after login
i have problem with redirecting user after login into base.html which is in main template folder. Django can't find this template. How to properly setup things for this to work? django structure: accounts main_folder settings.py urls.py staticfiles templates base.html short app structure accounts templates accounts login.html urls.py views.py settings.py templates part TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] accounts urls.py from django.urls import path from .views import* urlpatterns = [ path('', login_view), ] accounts view.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib import messages def login_view(request): if request.method == 'POST': # get posted data username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) # handle user authentication if user is not None and user.is_active and user.is_authenticated: login(request, user) # move user to main page return redirect('base') return render(request, 'accounts/login.html') -
How to implement a button of the searchbar erasing the query? Django environment)
I am developing a webapp in Django. I developed a nice search bar with two buttons. One of these (fa fa-search) is to search and display the results of the database, and it is altrady working. I would like that, when my user clicks on the other one (fa fa-trash), the code erases the query and reloads all the unfiltered results. How do I do it? Here is my code: in views.py: def glossario(request): query = request.GET.get('q') template = "glossario.html" # query apply if query: query = request.GET.get('q') #q è variabile risultante dalla query del database selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query)) return render(request, template, {'all_entries':selected_entries}) # no query else: all_entries = glossary_entry.objects.all return render(request, template, {'all_entries':all_entries}) in glossario.html: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav"> <a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a> <div id="blocco_ricerca_semplice" class="search-container"> <form method="GET" action="{% url 'glossario' %}"> <input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}"> <button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button> <button id="search_button" type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> -
Django fieldset.html override
So I decided to override all the Django templates for a custom look and feel for my WebApp. One problem I'm coming across though, is that I want to change the classes of these fields to form-control (I'm using bootstrap). I see that there's a built in function is_checkbox but there isn't anything to see if it is an input tag or a select tag. What I basically want to do is for Django to iterate over all the fields in the field set if a field is an input tag, I want to add the form-control class to it and if it is a select tag, I want to add the selectpicker class to it. Here's the Django code I'm referencing: <fieldset class="module aligned {{ fieldset.classes }}"> {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %} {% if fieldset.description %} <div class="description">{{ fieldset.description|safe }}</div> {% endif %} {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% … -
I can't get the values from django dropzone into view
I have trouble getting the django Dropzonejs values of the chosen file into django. It just creates an empty file object in the models. The problem is that I can't get the values into the model. It just creates aa blank model. HTML: <form class="dropzone" action="{% url 'teacher_assignment_add_file' OBJECTID %}" method="POST"> {% csrf_token %} <div class="fallback"> <input name="Assignment-File" type="file" multiple /> </div> </form> <ul class="list-group list-group-activity dropzone-previews flex-column-reverse"> {% for file in files %} <li class="list-group-item"> <div class="media align-items-center"> <ul class="avatars"> <li> <div class="avatar bg-primary"> <i class="material-icons">insert_drive_file</i> </div> </li> </ul> <div class="media-body d-flex justify-content-between align-items-center"> <div> <a href="{% url 'file123' file %}" data-filter-by="text">{{ file }}</a> <br> </div> <div class="dropdown"> <button class="btn-options" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="material-icons">more_vert</i> </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Download</a> <a class="dropdown-item" href="#">Share</a> <div class="dropdown-divider"></div> <a class="dropdown-item text-danger" href="#">Delete</a> </div> </div> </div> </div> </li> {% endfor %} View: @login_required def teacher_assignment_add_files(request, assignment_id): if request.method == 'POST': file = request.POST.get('Assignment-File') file = File(file=file) file.save() assignment = Assignment(id=assignment_id) assignment.files.add(file.id) return redirect('teacher-detail-assignment', id = assignment_id) -
How to create form fields dynamically from ChoiceField values?
I created a form with a ChoiceField which have multiple integers like that: And I want to add other fields (like CharField, etc) depending on that integer choice. I explain: if you choose 1, one CharField is added. If you choose 2, two CharField are added, etc etc. BUT, on the same page without reload or refresh the page. I don't know how to process, should I use JavaScript ? Or there is a solution to get ChoiceField value and create fields without reloading the page ? I hope I was accurate, I can tell you more information on what I want to do if you need it. Thanks a lot! -
Dango sends emails twice after form submission
I was trying to send emails when a form is submitted in my app, and I managed to do it but for some reason it sends it twice every time. After some search and debugging I think I know where the problem is but I don't know why. So the email sending function of my app takes place in my forms. py and looks like this: class approvalForm(forms.ModelForm): text1 = forms.ModelChoiceField(disabled = True, queryset = Visit.objects.all()) text2 = forms.ChoiceField(disabled = True, choices = poolnumber) def save(self, commit=False): instance = super(approvalForm, self).save(commit=commit) ready = instance.visible if ready is True: self.send_email() instance.save() print('yay sent') else: None return instance def send_email(self): var = self.cleaned_data tomail = self.cleaned_data.get('visit') tomails = tomail.location.users.all() tomaillist = [] for item in tomails: tomaillist.append(item.email) print(tomaillist) msg_html = render_to_string('myapp/3email.html', {'notify': var}) msg = EmailMessage( 'Text here', msg_html, 'myemail@email.com', tomaillist, headers={'Message-ID': 'foo'}, ) msg.content_subtype = "html" print("Email sent") msg.send() class Meta: model = MyModels fields = ('text1','text2', ) The save() function is runnig 2 times. I've tried to move the email sending function to the views.py in the form_valid() function but it's never called so I've tried the form_invalid() but same results. Is there any way to not let the save() … -
How to download a data table in python as pdf while keeping the formatting as desired?
I want to download a python data table as a pdf. I have tried converting it into an HTML table and then download it. The formatting is not maintained that way. This is possible with js but I need python based solution. Format preview should be able to be viewed in my application( Django or dash). And I would like teh option of changing format templates from my app. ex:- Selecting blue will make the header of each column blue in color, etc. Is there any way to converting datatable to pdf without first converting it into HTML. -
Add photos in Django backend with Froala editor
I'm trying to use Froala Editor in Django backend but I cant add photos. In my urls.py in root directory I've added url as follow: urlpatterns = patterns('', url(r'^$', include('main.urls')), url(r'^froala_editor/', include('froala_editor.urls')) ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In setings.py the I have as follows: STATIC_URL = '/assets/' STATIC_ROOT = "/var/www/frontend/website/public/" FRAOLA_EDITOR_THIRD_PARTY = ('image_aviary', 'spell_checker') FROALA_UPLOAD_PATH = "assets/froala_editor/images" In models.py I have field as follow: content = FroalaField(theme='dark') But when I try to add a photo in django admin I get an error as follows: "IMAGE CANNOT BE LOADED FROM THE PASSED LINK" -
Website made with Django for e-commerce site's post-office workers
I am going to create a new website for an e-commerce website in order to give information from e-commerce web'sites api to the new website and display it. This website should have these: Registration, login and logout parts in the top of navbar, Search input to search people in the e-commerce website's api And it should display information of the person who has been searched. So It is easy website. But I can't. Because I am pretty beginner now. Can anyone help me? Thanx in advance. -
How to display remaining Date and Time from DateTimeField in django
Here I have a simple function for sending leave request and accepting by the admin.This code works for now but I want to add some feature here.For example if the leave days was for 2 then after the leave has been accepted by the function below def accept_leave(request,pk): I want to display the remaining days of leave(Example:1 day 12 hours and 30 sec. remaining to complete leave ).After 2 days completed it should display some message like you leave has been completed. I got no idea for starting this .How can I do it ?Any help would be great. Is there any mistake in my approach ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateTimeField() end_day = models.DateTimeField() #day = models.IntegerField(default=0) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) sent_on = models.DateTimeField(auto_now_add=True) views.py def send_leave_request(request): form = MakeLeaveForm() if request.method == 'POST': form = MakeLeaveForm(request.POST) if form.is_valid(): leave_days = form.cleaned_data['day'] org = form.cleaned_data['organization'] start_day = form.cleaned_data['start_day'] end_day = form.cleaned_data['end_day'] diff = end_day - start_day leave_days = diff.days print('org',org) if leave_days > request.user.staff.organization.max_leave_days: messages.error(request,'Sorry can not be sent.Your leave days is greater than {}.'.format(request.user.staff.organization.max_leave_days)) return redirect('organization:view_leaves') else: leave = form.save(commit=False) leave.staff = request.user … -
Pass list of strings into raw sql query (Python/Django)
I need to pass a dynamic list of strings into raw sql query. Here is my code: myList = ['PREFIX\000\000923', 'PREFIX\000\000CS3'] <- strings I have troubles with myList = ['OK1', 'OK2'] <- ok strings myTuple = tuple(myList) query = "SELECT * FROM public.items WHERE name IN {}".format(myTuple) result = cursor.execute(query, myTuple) rows = dict_fetch_all(cursor) for row in rows: print(row) The above piece of code works just fine. However, there is a problem with strings with special characters with backslashes like this: "PREFIX\000\000923". What is the right way to code it? -
How to display a random video from a file in django?
I'm trying to make a video display randomly on my homepage. A user is able to upload a video and it would be saved to a document in media/documents as well as to a dataset. I tried the code below and it keeps giving me an error, {% load media %} {% for doc in document %} <video width='320' height= '240' controls> <source src="{% media 'doc.document' %}" type='video/mp4'> Your browser does not support the video tag. </video> {% endfor %} Exception Type: TemplateSyntaxError at / Exception Value: 'media' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz I removed if settings.DEBUG: from urls.py, however this didn't work. models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.conf import settings ... class Document(models.Model): title = models.CharField(max_length=100, default='NoTitle') description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField("date published")#(auto_now_add=True) creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path("", views.homepage, name="homepage"), path("myconta/", views.myconta, name="myconta"), path("upload/", views.model_form_upload, name="upload"), path("register/", views.register, name="register"), path('', include("django.contrib.auth.urls")), ] #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def homepage(request): return render(request=request, template_name="main/home.html", context={"sites": Info.objects.all}) return … -
Django Smart Selects Still Showing All Options
I am trying to work with django smart selects for the first time, but I cannot get it to work. I assume I must be doing something wrong in my setup but I cannot identify what it is. I have three models. Customer, BillTo, and Orders. In the Order, the user should select a Customer, and then the BillTo options should be dependent upon the Customer selected. Right now, I am still seeing all BillTo options regardless of Customer. Could someone please help me identify where I am making a mistake or missing something - this is really holding up my project. models.py class Customers(models.Model): ultimate_consignee = models.CharField(max_length=100) def __str__(self): return self.ultimate_consignee class BillTo(models.Model): ultimate_consignee = models.ForeignKey(Customers) c_address = models.CharField(max_length=1000) def __str__(self): return self.c_address class Orders(models.Model): reference = models.CharField(max_length=50, unique=True) #REQUIRED ultimate_consignee = models.ForeignKey(Customers, blank=True) #REQUIRED c_address = ChainedForeignKey(BillTo, chained_field='ultimate_consignee', chained_model_field='ultimate_consignee', show_all=False, blank=True, default=None, null=True) def __str__(self): return self.reference add_order.html {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST" enctype='multipart/form-data'> <br> <h2>Order Information</h2> <br> {% csrf_token %} <div class="column_order"> <label for="form.reference" class="formlabels">Reference ID: </label> {{ form.reference }} <br> <label for="form.ultimate_consignee" class="formlabels">UC: </label><br> {{ form.ultimate_consignee}} <br> <label for="form.c_address" class="formlabels">Ship To: </label> <br> {{ form.c_address}} </form> </div> </div> <script … -
How to save the ManyToManyField to model using POST method.? (Python 3.6, Django 2.2.)
I have 3 models one is Category(Fields = category_name) and another one is SubSategory(Fields = category(ForeignKey to Category),sub_category).and another model is DummyModel. # Model class DummyModel(models.Model): name = models.CharField(max_length=20) email = models.EmailField() category = models.ManyToManyField(Category) sub_category = models.ManyToManyField(SubCategory) This is my form class StartProjectForm(ModelForm): class Meta: model = StartProject fields = ( 'name', 'email', 'category', 'sub_category', ) def __init__(self, *args, **kwargs): super(StartProjectForm, self).__init__(*args, **kwargs) self.fields["category"].widget = CheckboxSelectMultiple() self.fields["category"].queryset = Category.objects.all() self.fields["sub_category"].widget = CheckboxSelectMultiple() self.fields["sub_category"].queryset = SubCategory.objects.all() def save(self, commit=True): clean = self.cleaned_data.get name = clean('name') email = clean('email') category = clean('category') sub_category = clean('sub_category') obj = StartProject() obj.name = name obj.email = email obj.category = category obj.sub_category = sub_category obj.save() When I try to save Error Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. -
Django activity-stream delete verb gives UnicodeEncodeError
in a Django 1.11.24 (python2.7) I'm having problems with a german 'umlaut'. When a resource is deleted I'm creating an acticity stream with following config: action_settings = defaultdict(lambda: dict(actor=getattr(instance, "owner", None), action_object=instance, created_verb=_('created'), deleted_verb=_('deleted'), object_name=getattr(instance, 'name', None), target=None, updated_verb=_('updated'), )) deleted_verb=_('deleted') gives gelöscht. Trying to open this activity in Django-admin ends in UnicodeEncodeError at /de/admin/actstream/action/79/change/ 'ascii' codec can't encode character u'\xf6' in position 9: ordinal not in range(128) I've tried to encode the value to unicode like deleted_verb=_('deleted').encode('utf-8'), or deleted_verb=unicode(_('deleted')), without luck. How can I correctly get rid of the Unicode error? -
How to compare two Django models and display the answer in the third model
I have two completely identical models in structure: class Model_A (models.Model) id_value = models.CharField(primary_key=True, max_length=45) some_value_1 = models.IntegerField(blank=True, null=True) some_value_2 = models.TextField( #and etc. I have many fields class Model_B (models.Model) id_value = models.CharField(primary_key=True, max_length=45) some_value_1 = models.IntegerField(blank=True, null=True) some_value_2 = models.TextField(blank=True, null=True) #and etc. I have many fields First, I try to compare all the field parameters with each other. Second, if the parameters are not the same, and write the answer in the third table(indicating each inequality by its ID and field name) . class Third_Model(models.Model): auto_increment_id = models.AutoField(primary_key=True) id_value = models.CharField(max_length=45, null=False) field_name = models.CharField(blank=True, null=True) value_from_A = models.CharField(blank=True, null=True) value_from_B = models.CharField(blank=True, null=True) How do I perform this action using Python models? Provided that the models have a lot of fields and the models themselves are more than 40 pieces. Here is an example of what I want to do with the sql query example. INSERT INTO `third_table` (`field_name`, `id_value`, `value_from_A`, `value_from_B`) SELECT id_value, manage_objects, param_name, fld_param , ref_param FROM (SELECT id_value, 'Model_name' AS manage_objects, param_name, max(val1) AS fld_param, max(val2) AS ref_param FROM ((SELECT id_value, 'some_value_1' AS param_name, some_value_1 AS val1, Null AS val2 FROM model_a ) UNION ALL (SELECT id_value, 'some_value_2' as param_name, some_value_2 AS … -
how to sum all the consummations for a specific client that is a foreign key in the consummation model?
class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') def get_absolute_url(self): return reverse('clients:consommation_detail', kwargs={'pk': self.pk}) def __str__(self): return 'Consommation numero :' + str(self.id) @staticmethod def get_nom(item, _default=' '): if item: return item.nom return _default @staticmethod def get_price(item, _default=0): if item: return item.price return _default def total_consommation(self): get_price = Consommation.get_price return get_price(self.entree) + get_price(self.food) + get_price(self.dessert) + get_price( self.boisson) + get_price(self.autres) I tried this to get the total of consummation of a client: def total(self): return self.vipcustomer.vip_consommations.annotate(Sum(self.total_consommation())) in the template I have this: {% for consommation in vipcustomer.vip_consommations.all %} <ul> <li> <a href="{% url 'clients:consommation_detail' pk=consommation.pk %}"> </li> </ul> {% endfor %} Total : <strong>{{ vipcustomer.vip_consommations.total}} MRO</strong> ` How to sum the consummations for a vipcustomer that is foreign key to the consummation. Thanks -
How can I fix my modal to work using Javascript?
I decide to make a modal for my homepage using Vanilla JavaScript. I have looked at several examples on how to build a modal from scratch but I'm stuck at getting the display property to change using my JavaScript code. <script type="text/javascript"> var span = document.getElementsByClassName("ex"); var modal = document.getElementsByClassName("vid-modal") function clearModal() { modal.style.display == "none"; } function windowOnClick(event) { if (event.target === span) { clearModal(); } } function fireWhenReady(func) { document.addEventListener('DOMContentLoaded', func) } fireWhenReady(windowOnClick); </script> .vid-modal { position: fixed; background-color: rgba(0, 0, 0, 0.4); width: 1000px; height: 500px; top: 250px; left: 50%; margin: 0 auto; z-index: 1002; transform: translateX(-50%); /* display: initial; */ /* aug 21 still working on modal display */ display: initial; } <div class="vid-modal"> <span class="vexit"><i class="fa fa-window-close ex" aria-hidden="true"></i></span> <div class="vid-box"> <iframe id="front-video" src="https://www.youtube-nocookie.com/embed/Hua4MRTKmy0?rel=0&amp;controls=0&amp;showinfo=0;autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> </div> </div> I expect to set the display property to "none", and apply more advance solutions to this code. -
How to call the correct view method in Django?
I have a project with these files and folders: ... old project new common manage.py ... I access the "old" using http://127.0.0.1:8000/old and there are views, form urls, etc files inside this folder. all works fine. I have similar files inside "new" folder as well. It also runs well: http://127.0.0.1:8000/old However I run into problems when I have a method inside view ("method1") and I declare it inside urls. However it searches for the method1 inside folder "old" not in "new". $.post('{% url "method1" %} inside urls I have path('method/', views.method1, name='method1'), I have no idea why this js searches for method1 inside "old". When I declare method1 inside old folder, it works fine. What am I missing here? -
django all-auth authenticating via twitch
I am trying to authenticate a user from twitch Auth using Django and reactjs. I am able to authorize the user and store its details in the Django admin from backend but not sure how to do it from reactjs. What I tried so far: Following the documents from here: https://django-allauth.readthedocs.io/en/latest/installation.html I configured everything as: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.twitch', 'django_extensions', 'users.apps.UsersConfig', ] SITE_ID = 1 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 = app-name.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 = 'sphinx.wsgi.application' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } I also registered the social application in the Django admin. When I hit: http://localhost:8000/accounts/twitch/login/ It takes me to the twitch authorization page, Which when I click on "Authorize" saves the user details in the Django admin redirects me back to the url: http://localhost:8000/accounts/profile/ The problem is I need to make sure the LOGIN_REDIRECT_URL page '/accounts/profile/' has some authentication so only the logged in user can access it and to display the username of that …