Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom M2M validation in Django admin not displaying to user
I have a model where I need to validate that an m2m field and a regular field are exclusive. (i.e. you can only have one or the other, not both.) class EventFrequency(models.Model): weekdays = models.CharField(...) dates = models.ManyToManyField(...) Since one is an m2m, overriding the model save() doesn't work. (the model is saved, then m2m added) I was able to throw the error successfully in the admin class by overriding save_related(), but it doesn't display in the admin form. It is just a regular server error. class EventFrequencyAdmin(VersionAdmin, admin.ModelAdmin): model = EventFrequency filter_horizontal = ('dates',) def save_related(self, request, form, formsets, change): super(EventFrequencyAdmin, self).save_related(request, form, formsets, change) if form.instance.dates.exists() and form.instance.weekdays: raise ValidationError('Cannot select both dates and weekdays.') I am able to catch the error in an attempt to show it to the user by overriding changeform_view(). It appears to work well except for the redirect. form_url has no value, and is therefore ''. def changeform_view(self, request, object_id=None, form_url='', extra_context=None): try: return super(EventFrequencyAdmin, self).changeform_view(request, object_id, form_url, extra_context) except ValidationError as e: print('************* caught error *************') self.message_user(request, e, level=messages.ERROR) return HttpResponseRedirect(form_url) What am I doing wrong? -
Django 3.0: django-notifications giving error: "Notification.recipient" must be a "User" instance
I am using django-notifications-hq package link of django-notifications-hq and getting error: Cannot assign "<Seller: john@gmail.com>": "Notification.recipient" must be a "User" instance. my custom user model: class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, blank=True, null=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) customer = models.BooleanField(default=False) seller = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) my seller model having 1to1 relation with user: class Seller(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) seller_picture = models.ImageField(upload_to='profile_pic/seller', null=True, blank=True) my Book model has foreign key seller: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField('Title', max_length=255) authors = models.ManyToManyField(Author, related_name='book_written_by') seller = models.ForeignKey(Seller, on_delete=models.CASCADE) price = models.DecimalField('Price', decimal_places=2, max_digits=10) description = models.TextField('Description') And somewhere in my views after successfully getting books just bought by some user, I want to notify all respective sellers that someone has bought their book: for book in books: notify.send(Seller, recipient=book.seller, verb="User has just bought book named {} priced as {}".format(book.title, book.price)) I know it works fine recipient = request.user but I have different scenario. How can I make book.seller a User instance ? -
How do you call a custom serializer update method in Django rest framework?
I am trying to make a simple API that takes in an audio file, reverses it, and stores them both. It can accept the file, and overwriting the perform_create() method I reversed it. But now I can't find a way to update the record with the reversed file. This is my viewset class SoundViewSet(viewsets.ModelViewSet): queryset = Sound.objects.all().order_by('id') serializer_class = SoundSerializer def perform_create(self, serializer): serializer.save() sound = Sound.objects.last() root = settings.MEDIA_ROOT.replace('/media','') root = root + sound.audio.url p = Path(root) clip = AudioSegment.from_wav(p) rev = clip.reverse() sound.reversedaudio = rev serializer = SoundSerializer(data=sound) serializer.is_valid() Sound.objects.filter(id=sound.id).update(reversedaudio=serializer.data.get('reversedaudio')) It is returning NULL values. I have to pass it through the serializer first because the audio file has to be parsed for JSON. I just can't seem to find a simple way to call a serializer update() like the perform_create(). I tried Sound.objects.filter(id=sound.id).update(reversedaudio=sound.reversedaudio) but its a viewset update, file gets uploaded un-parsed and is basically then garbage. Here's my serializer class: class SoundSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sound fields = ('name', 'audio', 'reversedaudio') Can someone point out what I'm missing? P.s. I am using DRF for the first time and working under a deadline so I would prefer not having to define everything on my own and … -
HTTP error 502 when uploading files on my page
I just installed SSL certificate using cert bot, I am using gunicorn and Nginx. Now when I am uploading a file to process it, I am getting error 502. I am not sure what's wrong Can anyone help me out Tell me which snippets you need -
How to limit requests to my API to authenticated users?
I am creating an API with Django and uploaded it to Heroku. Then I want to be able to make requests to this API from anywhere. However, I am wondering (since I am a beginner to Django) how I could add that authentication so that no one can come in and make HTTP calls. By the way, I am using the latest version of Django. If you need any other information, please let me know. -
django-filters w/ authentication permsission
I am try to create a view where if you are an admin on the site, you can view all orders regardless of who placed the order. In addition, if you are not an admin, then you can only see the orders you have placed. Now, I have a view that does this: orders/views.py: @method_decorator(login_required(login_url='account_login'), name='dispatch') class OrderListView(ListFilteredMixin, ListView): model = Order template_name = 'orders/order/list.html' filter_set = OrderFilter queryset = Order.objects.all() def get_queryset(self): if self.request.user.is_staff: return self.queryset.all return self.queryset.filter(user=self.request.user) The problem is, if I include the "get_queryset" function in the OrderListView, my django-filters "filter_set" no longer works. I am not receiving any errors when trying to filter...its just doesn't do anything. Any help would be appreciated. Thanks! -
How do I make a model automatically from another model?
Whenever the user makes a new reservation, I want a profile to be made automatically with the 'first_name', 'last_name' and 'email' fields from the reservation class. models.py from django.db import models from django.db.models.signals import post_save class Reservation(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=50) check_in = models.DateField() check_out = models.DateField() num_guest = models.IntegerField() reason = ( ('Birthday', 'Birthday'), ('Anniversary', 'Anniversary'), ('Get Away From Kids', 'Get Away From Kids'), ('Vacation', 'Vacation'), ('Treating Myself', 'Treating Myself'), ('Leave Blank', 'Leave Blank'), ) opt = models.CharField(max_length=120, choices = reason) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Profile(models.Model): guest = models.ForeignKey(Reservation, on_delete=models.CASCADE) def __str__(self): return "%s" % (self.guest) def create_profile(sender, instance, created, **kwargs): post_save.connect(create_profile, sender=Reservation) I am trying not to modify Reservation class as I need the fields as a ModelForm. New to coding and appreciate your guidance! -
How do I display the data of my search query in an html template in django?
I'm writing a django app that lets you search for a movie using the Ghibli API. So far, it works and whenever I look for a movie it appears but only in the terminal. I don't know how to display the results outside of it, in the html. Any advice would be very appreciated. This is the code in views, with the index function I use to access the movies I search for: from django.shortcuts import render, HttpResponse from core.models import Movie from django.views.generic import ListView import requests def index(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() print(results) for result in results: movie_data = { 'Title' : result['title'], 'Release_date': result['release_date'], 'Director' : result['director'], 'Producer' : result['producer'], 'Description' : result['description'] } movies.append(movie_data) print(movie_data) context = { 'movies' : movies } return render(request,'core/index.html', context) This is the html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | Movies</title> <link rel="stylesheet" href="{% static 'core/main.css' %}"> </head> <body> <div class=" header"> </div> <div class="wrap"> <form method="POST"> {% csrf_token %} <div class="search"> <input type="text" … -
Convert QueryDict in Django to an array of object
I am passing array of object within the ajax like this: function sendAjax(ajax_data) { return $.ajax({ url: '/ajax/ajaxprocess/', data: ajax_data, dataType: 'json', success: function (data) { if (data.status) { console.log(data.msg); } else { console.log("Not success in ajax operation!") } } }) } function setResult(word, qType, result) { resObj = {word: word, qType: qType, result: result} allResults.push(resObj) } function sendResults() { jsonData = sendAjax({ 'type': "results", 'results': allResults, }) } Then it would be expressed like this in backend side: >>> print(request.GET) <QueryDict: {'type': ['results'], 'results[0][word]': ['hello'], 'results[0][qType]': ['Meaning'], 'results[0][result]': ['true'], 'results[1][word]': ['okay'], 'results[1][qType]': ['Meaning'], 'results[1][result]': ['false'], 'results[2][word]': ['show'], 'results[2][qType]': ['Meaning'], 'results[2][result]': ['true']}> How can I change this QueryDict such that I can use it in backend side separately like a list of objects: for res in results: # do something like print(res.word) -
Django Rest Framework Nested Serializer with One-to-Many unique value
I have a Model for statuses and a Model for storing several languages for each status: class Status(models.Model): code = models.IntegerField() class StatusValueLang(models.Model): status = models.ForeignKey(Status, related_name="langs", on_delete=models.CASCADE) lang = models.CharField(max_length=3) value = models.CharField(max_length=255) I have a Model uses Status class Order(models.Model): number = models.CharField(max_length=10) status = models.ForeignKey(Status, on_delete=models.PROTECT) Then, I want to serialize this queryset (get orders with status name in english): orders = Order.objects.filter(status__langs__lang='en') using serializers.Serializer: class StatusValueLangSerializer(serializers.Serializer): value = serializers.CharField(max_length=255) class StatusSerializer(serializers.Serializer): langs = StatusValueLangSerializer(many=True) class OrderSerializer(serializers.Serializer): number = models.CharField(max_length=10) status = StatusSerializer() It works, but because of 'Many=True' in line 'langs = StatusValueLangSerializer(many=True)' StatusSerializer returns all rows (languages) despite my filter (status__langs__lang='en') How I can set Serializers to get this result: [ { "number": "123", "status": { "langs": [ { "value" : "Approved" <-- Just one, filtered row. } ] } } ] or may be better: [ { "number": "123", "status": { "value": "Approved" } } ] -
Changes to Django Template is not reflecting
I followed the instructions on https://github.com/tomwalker/django_quiz to use this project. I am able to successfully use the project. However, when I change the template (.html files) nothing changes. Even If I add or delete the entire content. I am not sure if I am missing something. I checked in views.py and I cannot see any html renders. I am new to Django and finding it difficult to understand views.py and make any changes to the templates like questions or category. Any help would be greatly appreciated. -
Django run a test from a view
Trying to use call_command to run a simple selenium test from a view. to let a user run a pre-coded tests from it's browser. urls.py path('', views.button, name='button'), views.py def button(request): if request.GET.get('btn'): print('Clicked!') call_command('test') return render(request, 'button.html') button.html <form method="get" action="{% url "button" %}"> <input type="submit" class="btn" value="Click" name="btn"> </form> The console does print 'Cliked' once the button is cliked, but i'm getting 'Server Error (500)'. -
What is the better way deploy django and angular in same server or separate server?
I want to know the better way of deploying Django and Angular, which way is better : Django and angular in the same machine. Django in separate machine/server and Angular in another machine/server. Note: if there another better ways please tell me. -
I can't make my migrations because of an "django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted" how do I fix?
I'm trying to makemigrations in my terminal but it's saying that it can't due to an empty static prefix in a folder called local-packages\Python38\site-packages\django\conf\urls\static.py, but I don't have a static.py folder? I've been trying to find it for 3 days and I don't know what to do anymore. Any and all help is very much appreciated. -
how to validate dynamically django errors with jquery(ajax)?
I am trying to validate dynamic errors handled by Django from form.errors. I have a JSON response where I sent all errors based on Django if its empty, invalid emails, and all fields from my form. however, how can I validate them in client-side without hardcoding data['error']['field'] == 'Django error' def contact_us(request): form = ContactForm(request.POST) if([..]): return JsonResponse({'message': 'success'}) else: return JsonResponse({"error": form.errors}) jquery ajax success: function (data) { console.log(data) if(data == 'error'){ addErrorTo('name', data['name']); }else{ removeErrorFrom('name') } }, utils function addErrorTo(field, message) { const formControl = form[field]; console.log(formControl) formControl.classList.add('error'); } function removeErrorFrom(field) { const formControl = form[field]; formControl.classList.remove('error'); } errors from Django form error: company: ["must contain letters only."] from_email: ["Enter a valid email address."] name: ["must contain letters only."] surname: ["must contain letters only."] -
Django/Ajax: Why is my request.body empty when I send it via POST with Ajax?
I am trying to handle a button in my Django views without reloading the page using Ajax requests. I already managed to do something similar but when submitting a model formset. Two problems are arising: First, request.body in my view is empty (I get b'') and Django is also expecting a csrf token even when this request is not comming from a form submission. This is my HTML/JavaScript. I still have them together because I haven't made enough things work; will organize later. It has been cut to only have the relevant parts for readability. <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { // Create new buttons and insert them next to each note field. var noteFormList = $(".note-form").find("p").find("textarea"); for (noteElement of noteFormList) { var idText = noteElement.id; var newButton = $("<button></button>").text("Insert"); newButton.attr("id", "ins-after-"+idText.match(/\d+/)); newButton.attr("class", "ins-note-after"); newButton.attr("type", "button"); newButton.attr("value", "ins-after-"+idText.match(/\d+/)); // Insert the button after the textarea element. $("#"+idText).after(newButton); } // All these buttons have the same class. Will send their ID to handle. $(".ins-note-after").click(function(event) { event.preventDefault(); var butValue = $(this).attr("value"); console.log(butValue); $.ajax({ type: 'POST', dataType: 'json', data: {'value': butValue}, success: function(json){ console.log(JSON.parse(response)) } }) }) </script> </head> <body> <form method="POST" class="note-form"> {{ formset.management_data }} {% csrf_token %} {{ formset.as_p }} <input … -
django Error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context
So I have my consumers.py in my project, in websocket recieve, i want to give +1 to an object in my user model but this happened: Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 401, in __get__ rel_obj = self.related.get_cached_value(instance) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'profile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\consumers.py", line 37, in websocket_receive obj = usern.profile File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 409, in __get__ rel_obj = self.get_queryset(instance=instance).get(**filter_args) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 411, in get num = len(clone) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 258, in __len__ self._fetch_all() File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1149, in execute_sql cursor = self.connection.cursor() File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", … -
Replacing items in a list in Django through a form
I have a python list with hundreds/thousands of strings: ['hello', 'good morning', 'evening everyone' ... ] I loop through these items on a Django page and in some circumstances, I need to show an input to allow the user to change the string. It looks something like this: <form method="post"> {% for item in list %} <p>{{ item }}</p> {% if certain_condition %} <input name="replace"> {% endif %} {% endfor %} </form> The user may leave all fields empty, fill all of them out, or anything in between. Now, when the form is posted, I need to create a new list (or replace the old list), in which those items that are sent in the POST are being replaced. However, I'm not totally sure what the best way is to engineer this. I'd like clean and efficient code, but my first doubt is how to convey in the POST which of the items is being replaced. Should I add another input that contains the position of the original item in the list? Or should I send the original name? Or is there a better way? To replace I'm thinking of using list comprehension, but also not sure if this is … -
Which query will be more efficient?
I am using Django Rest Framework with PostgreSQL database and I need to filter data. So while filtering which kind of query will be more efficient? Queryset 1: Calculating statistics from database directly. response = dict() response['count_value1'] = models.TempModel.objects.filter(val='2', value=value1).count() response['count_value2'] = models.TempModel.objects.filter(val='2', value=value2).count() response['count_value3'] = models.TempModel.objects.filter(val='2', value=value3).count() response['count_value4'] = models.TempModel.objects.filter(val='2', value=value4).count() response['count_value5'] = models.TempModel.objects.filter(val='2', value=value5).count() Queryset 2: Calculating statistics after loading data in memory. response = dict() data = models.TempModel.objects.filter(val='2') response['count_value1'] = data.filter(value=value1).count() response['count_value2'] = data.filter(value=value2).count() response['count_value3'] = data.filter(value=value3).count() response['count_value4'] = data.filter(value=value4).count() response['count_value5'] = data.filter(value=value5).count() The insight is: TempModel with contain 7 columns and around 150 rows of data for val='2' So which option should I prefer and please provide a short explanation for the choice? -
How to add a condition to the views.py file in django to not to create the same data objects if it is already present in the database?
Here's the views.py file:- from django.shortcuts import render from .models import News from django.core.paginator import Paginator from django.db.models import Q # For scraping part import requests from bs4 import BeautifulSoup def news_list(request, *args, **kwargs): # fOR scraping part - START:::::::::::::::::::::::::::::::::::::::::::::::::::::::: response = requests.get("http://www.iitg.ac.in/home/eventsall/events") soup = BeautifulSoup(response.content,"html.parser") cards = soup.find_all("div", attrs={"class": "newsarea"}) iitg_title = [] iitg_date = [] iitg_link = [] for card in cards[0:6]: iitg_date.append(card.find("div", attrs={"class": "ndate"}).text) iitg_title.append(card.find("div", attrs={"class": "ntitle"}).text.strip()) iitg_link.append(card.find("div", attrs={"class": "ntitle"}).a['href']) # fOR scraping part - END:::::::::::::::::::::::::::::::::::::::::::::::::::::::: # fOR storing the scraped data directly into the dtatbase from the views.py file - START--------------------------------------------------------------- for i in range(len(iitg_title)): News.objects.create(title = iitg_title[i], datess = iitg_date[i], linkss = iitg_link[i]) # fOR storing the scraped data directly into the dtatbase from the views.py file - END----------------------------------------------------------------- queryset = News.objects.all() #Getting all the objects from the database search_query = request.GET.get('q') if search_query: queryset = queryset.filter( Q(title__icontains = search_query) | Q(description__icontains = search_query) ) paginator = Paginator(queryset, 5) #Adding pagination page_number = request.GET.get('page') queryset = paginator.get_page(page_number) context = { 'object_list': queryset } return render(request, 'news_list.html', context) I have tried different approaches like add the unique=True in my model.py file but still doesn't works, throws som,e more error. I am unable to add or figure … -
Something's Wrong When I Try to Register on my Website
I have been trying to make my Django website. I need to register to my website to test if once I'm logged in, I could log out. But when I try to log in, the log in page does not pop up. Some page pops up instead, and this is what the terminal says: Internal Server Error: /testissue/user_login/ Traceback (most recent call last): File "C:\Users\benic\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\benic\anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\benic\anaconda3\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\benic\Desktop\My Stuff\Programming\Files\Websites\Django Websites\Learning Web Development\Back-End\Django\Django Level 5\DjangoProjectLevel5\DjangoAppLevel5\views.py", line 73, in user_login return render(request, 'DjangoAppLevel5/login.html', {}) File "C:\Users\benic\anaconda3\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\loader.py", line 68, in render_to_string return template.render(context, request) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\backends\django.py", line 66, in render return self.template.render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 207, in render return self._render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 199, in _render return self.nodelist.render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 990, in render bit = node.render_annotated(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 957, in render_annotated return self.render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\loader_tags.py", line 177, in render return compiled_parent._render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 199, in _render return self.nodelist.render(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 990, in render bit = node.render_annotated(context) File "C:\Users\benic\anaconda3\lib\site-packages\django\template\base.py", line 957, … -
Django model error with nested dictionaries
I am relatively new to Django, but not to python, My model is trying to use a class (defined in a separate file) in which data is coming from a REST API, the retrieved data is in a nested dictionary. The code will run fine in python, but when I try it in Django (makemigrations), I get an error: File "c:\blah-blah\Clone_PR.py", line 20, in GetFoundOnSelectItems values = self._issueEdit["fields"]["customfield_13940"]["allowedValues"] TypeError: 'NoneType' object is not subscriptable I tried using type hints, but that does not work either. models.py from dal import autocomplete from django.db import models from django.contrib import messages from .Login import jlogin from .Jira_Constants import ProductionServer, TestServer, StageServer from .Clone_PR import Issue jira = None issue = Issue() class ClonePrLogin(models.Model): username = models.CharField(max_length=30) password = models.CharField(max_length=30) @classmethod def LoginToJira(cls): global jira jira = jlogin(ProductionServer, cls.username, cls.password) class PrEntry(models.Model): prToClone = models.CharField(max_length=20) @classmethod def GetIssueAndMeta(cls): global issue issue.initialize(jira, cls.prToClone) class ClonePr(models.Model): issueKey = issue.issueKey issue.GetFoundOnSelectItems() foundOnList = issue.foundOnSelectItems foundOn = autocomplete.Select2ListChoiceField(choice_list=foundOnList) Clone_PR.py from typing import List, Dict class Issue(): def __init__(self): self.jiraInst = None self.issueKey = '' self._issue = None self._issueEdit = None # self._issueEdit = Dict[str, Dict[str, Dict[str, List[Dict[str, str]]]]] self.foundOnSelectItems = [] def initialize(self, jira, prKey): self.jiraInst = jira … -
Chained dropdown list. Issue with "this.value"- jquery, django
I trying to develop simple chained 2 steps drop down list. I have made fist step which works fine. I have trouble with second step. I using jquery to filter list based on what has changed. In first step "this.value" which is part of filter gets proper value, list is filtered. I second step, if I understand correctly "this.value" should be changed to value of option that has been chosen by user but it remains same as in first step. I looking for a tip how to solve that. jquery $(document).ready(function() { var $clientvar = $("#client"); var $clientssubvar = $("#clientssub"); var $clientssubwvar = $("#clientssubw"); /*first step*/ var $options = $clientssubvar.find('option'); $clientvar.on('change', function() { $clientssubvar.html($options.filter('[value="'+this.value+'"]')); }); /*second step*/ var $options1 = $clientssubwvar.find('option'); $clientssubvar.on('change', function() { $clientssubwvar.html($options1.filter('[value="'+this.value+'"]')); }).trigger('change'); }); HTML <div class='container'> <div class='row py-5'> <select name ="client" id="client" class="form-control"> <option value="" disabled selected="true">wybierz klienta</option> {% for client in clients %} <option value="{{ client.nazwa }}">{{ client }}</option> {% endfor %} </select> </div> <div class='row py-5'> <select name ="clientssub" id="clientssub" class="form-control"> <option value="" disabled selected="true">wybierz filię</option> {% for clientssub in clientssub %} <option value="{{ clientssub.firma }}">{{ clientssub }}</option> {% endfor %} </select> </div> <div class='row py-5'> <select name ="clientssubw" id="clientssubw" class="form-control"> <option value="" … -
AngularJs if statement in ng-href and collpase ng-href
I want to do a similar thing done here https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_collapsible2&stacked=h with a small change using angular js. Let's say I have a variable test, Now my href(Simple collapsible) will display only when the test has some string otherwise no href displayed. I tried below condition in my angular template: Simple collapsible [[test]] Note: I am actually having a condition like this https://django-angular.readthedocs.io/en/latest/template-sharing.html but it doesn't include how to collapse ng-href. Any help would be really appreciated. -
Django how to update image
what should i do, if i want to update the existing image or photo in my database? I have this code in my html and views.py {% for updateproduct in updateproducts %} <input type="text" value="{{updateproduct.id}}" name="id"> <td> <label for="myfile"> <img id="output" src="{{updateproduct.image.url}}" name="image1" class="subimage"/><br> <input type="file" accept="myfile" name="image1" value="{{updateproduct.image.url}}" id="myfile" onchange="loadFile(event)" style="display:none;"> </label> <script> var loadFile = function(event) { var reader = new FileReader(); reader.onload = function(){ var output = document.getElementById('output'); output.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; </script> </td> {% endfor %} in views.py product_id = request.POST.get("id") image = request.POST.get('image') update = Product.objects.get(id=product_id) update.image = image update.save() my models.py class Product(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] image = models.ImageField(upload_to='images', null=True, blank=True) def __str__(self): suser = '{0.product}' return suser.format(self)