Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jquery How to change text of certain class inside $(this) selector
My problem is quite obvious but I don't know why its solution is taking so much time. Look at my html: {% for d in data %} <div class="chat_list" data-id={{d.id}}> <div class="chat_people" > <div class="chat_ib" > <h5><span class="chat_date"> </span></h5> </div> </div> </div> {% endfor %} I want to append text on click of certain div.Things I tried out in jquery: $('.chat_list').on('click', function(event){ event.preventDefault(); $( '.chat_date', this).text('hhh') $(this).find('.chat_date' ).text('hhh') $(this).find( 'chat_people').find('chat_ib').find('.chat_date' ).text('hhh') }); Nothing worked out. When only do $( '.chat_date').text('hhh') text get appears on every div. Any good solution to this? -
How to increment attribute "for" in my dynamic form?
I am new to programming so I really really appreciate if any of you would be able to help me with my code. I managed to solve my problem before this by referring to this link : previous row is not computing/updating from appended rows using jquery But then I have to combine that code with this : function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); fullrowname = selector.substring(0,selector.length - 4) + 'not(:last)' var conditionRow = $(fullrowname); conditionRow.find('.btn.add-form-row') .removeClass('btn-success').addClass('btn-danger') .removeClass('add-form-row').addClass('remove-form-row') .html('<span class="fas fa-minus" aria-hidden="true"></span>'); return false; } $("input.quantity,input.price").on('change', function() { Total($(this).attr("for")); }); The id is increment perfectly everytime I click the add button but the for="0" attribute is not increment. Hence my calculation for the dynamic input is not working :( Can you guys show me the way of how to increment the "for" attribute in the code above ? -
How to use a specific QuerySet for retrieval of related fields in Django?
I have subclassed QuerySet to provide it with an additional method, that annotates the QuerySet of MyModel with a custom field (containing the last related Person, for the purposes of optimization): class MyModelQuerySet(models.QuerySet): def with_last_person(self): people = Person.objects.filter(user_id=OuterRef('id')) people = people.annotate(person=RowToJson(F('id'), output_field=JSONField())) return self.annotate(person=Subquery(people.values('person')[:1])) This works just fine (e.g. [model.person for model in MyModel.objects.with_last_person()]) However, I am now retrieving another model, which has a foreign key relationship to MyModel: other_model = OtherModel.objects.get(foo=bar) #... Understandably, the other_model.my_model field contains the unannotated instance of MyModel. Is there a way to use this specific QuerySet for the retrieval of related MyModels of OtherModel? Something like: OtherModel.objects.filter(foo=bar).select_related('my_model', use_queryset=MyModelQuerySet) I suppose I could just copy and paste the code from MyModelQuerySet.with_last_person into the OtherModel query, but that duplicates the code unnecessarily. Is there another solution I'm missing? -
Shifting of filter section from right sidebar to left side bar in change list page in Django admin
I'm working on Django.And in Django admin I want to change the direction of filter section in the change list from right sidebar to left side bar as shown in the pic : Is there any way so that the filter section can be shifted as I mention?? Thanks in advance!! -
django orm how to get the sum of the first element of an array field?
I have the following django model for postgres. Assume metric_vals are non-empty arrays. Is there a way of getting the sum of all first values of metric_vals? from django.db import models import uuid from django.contrib.postgres.fields import ArrayField class SampleModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list) I tried the following but resulted in error: from django.db.models import F from django.db.models import Sum SampleModel.objects.aggregate(Sum('metric_vals__0')) django.db.utils.ProgrammingError: function sum(double precision[]) does not exist -
Issue regarding download Qgis 3.12 on Windows
I have tried multiple attempts and having 51 Gb in my hard drive, already deleted all the files regarding Qgis. -
i want to get the predicted result while adding the protein in sequence
here is my pickle class code feature engineering perform in jupyter and i put my model in pickle file whCih i'm calling in django here is my pickle class code.. import pandas as pd import pickle #Feature Engineering class protein: def __init__(self): self.features = self._makeFeature() def _makeFeature(self): test_list = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'Y', 'Z'] test_comb2 = [] test_comb1 = [] test_comb3 = [] for i in test_list: test_comb1.append(i) for j in test_list: test_comb2.append(i + j) for k in test_list: test_comb3.append(i + j + k) test_comb = [] test_comb.extend(test_comb1) test_comb.extend(test_comb2) test_comb.extend(test_comb3) print(len(test_comb)) return test_comb def countInputSeq(self, proteinSeq): d = {} for k in self.features: if k not in d: d[k] = 0 if k in proteinSeq: d[k] += 1 print(d) df = pd.DataFrame(d, index=range(len(d))) #df = pd.DataFrame(d) df=df.iloc[:,:420] return df def predict(self, feature): file = open("C:\\Users\\DELL\\Desktop\\Protein project\\model.obj",'rb') model = pickle.load(file) return model.predict(feature) def getSavedModel(self): file = open("C:\\Users\\DELL\\Desktop\\Protein project\\model.obj",'rb') model = pickle.load(file) return model here is my view file method which i call in form method, when i add some protein in text file i got the same output but i want the predicted result def test(request): … -
How to know if a model was modified by another user
I am writing a Django application where users manipulate a Model. A typical session for users is this : they get the model ; they do some actions (vizualise the model's datas, change these datas..); then, they save the model if they modified something. But, if two users are manipulating the same instance of the model, and one save his modification after the second loaded it, I want to be able to "notify" the second that the model has changed, so he can reload it. I could perform a get to check if there was a modification in the database every time a view is called, but it doesn't seems optimal. I have looked at Django's signals too, but I don't know how to send a signal to users manipulating a specific instance of the model. Do you have any ideas on how I can do it ? -
Python DJANGO TESTS test case with mocks not behaving as expected
I have to test an API for 404, so here is my test case @patch('api.services.requests.get') def test_whitelisted_response_failure(self, mock_get): response_body = utils.test_file('get_data.json')["HTTP_ERROR"] mock_get_data = Mock() mock_get_data.status_code = status.HTTP_404_NOT_FOUND mock_get_data.json.return_value = response_body mock_get.return_value = mock_get_data response = self.client.get(self.url, content_type='application/json') And this is my API which I am supposed to test. def get(self, request, id): try: response = Service.get_detail(id) response.raise_for_status() # response.status_code = 404 here except HTTPError as e: print("INSIDE HTTP ERRORS") The code in API never raises an exception for non 200 status codes when I test it through my testcase but works just fine when tested through Postman(not mocked) Am I missing something here? -
override django oscar search app to return specific only merchant specific products?
I am using Django oscar(2.0.2), where I have made foreign key relation of merchant ids with product table so that I can fetch merchant-specific products from the database AbstractProduct with data, (https://prnt.sc/s1ssxx). By default oscar returns all the products in the search results, I want to only return the products specific to a merchant's site. I am using haystack simple search as suggested in oscar documentation, I have tried overriding the search app like all other apps, I have overridden the search_indexes.py file, but it seems that it never gets called from the FacetedSearchView. where will I have to override the query like that Product.objects.filter(user_id=1), to return only merchant-specific products while searching for a product? if my question is not clear, let me know in the comments so I can improve it. -
How to stop a timer from reseting using Django and AJAX?
I am trying to stop a timer from resetting when the user refreshes the page. I don’t want to use cookies or local storage, I want to store how much left in the database. I am using Django and Ajax. I don’t fully understand how to do that, I have tried to send how much left to the view using AJAX POST request but I keep getting that its None hence it does not get stored in the database. I don’t fully understand where to place the AJAX call in my JS and how to use a GET AJAX request. How can I get the value from the database and use it in my timer when the user refresh the page? template.html const TIME_LIMIT = 30; let timePassed = 0; let timeLeft = TIME_LIMIT; let timerInterval = null; startTimer() function startTimer() { timerInterval = setInterval(() => { timePassed = timePassed += 1; timeLeft = TIME_LIMIT - timePassed; seconds_left = timeLeft/100 document.getElementById("base-timer-label").innerHTML = formatTime( timeLeft); $.ajax({ type: "POST", url: server_url+ '/study/attention_view', data: {'seconds_left' : seconds_left}, success: function () { console.log('seconds_left:', seconds_left); } }); setCircleDasharray(); setRemainingPathColor(timeLeft); if (timeLeft === 0) { onTimesUp(); } }, 1000); } function formatTime(time) { let seconds = … -
django rest framework HyperlinkedIdentityField
i've try to hyperlinked serializer in django-rest-framework , django version:2.2 main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/trip/',include('app.api.urls')), ] app urls.py app_name='my_app_api' urlpatterns = [ path('posts/',MyView.as_view(),name='posts'), path('details/<int:id>/',MyView.as_view(),name='post_id'), ] my serializers.py post_deteail_url = HyperlinkedIdentityField( view_name = 'my_app_api:post_id', lookup_field='id' ) but still i get this error django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "my_app_api:post_id". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. i found some solution with the same problem not worked for me , and still keeping getting the error -
How do i insert one table and update another table in django
I have two tables, purchase with four fields (id,supplier,items,and quantity), and i have items table with four fields(id,items_name,quantity). When ever i insert data in purchase table, i want to update the quantity of that item in items table. For example if i purchase one item, the quantity will be updated in items table. -
Django i18n: Django translation file with optional arguments
Is it possible to mark an argument as optional within my .po files? msgid "searchpage_seo_title_%(location)s_%(price)s" msgstr "My special title %(location)s - without using the price argument" If I build my string like that I got this error while compiling my translation files. python3 manage.py compilemessages processing file django.po in /locale/en/LC_MESSAGES CommandError: Execution of msgfmt failed: /locale/en/LC_MESSAGES/django.po:1294: a format specification for argument 'price' doesn't exist in 'msgstr' msgfmt: found 1 fatal error -
how to give condition on displaying value in Django admin
Hi i have user model consist of several fields, in that payment_type is one field which return integer value , so based on that value i need to show some string sentence. class Users(models.Model): payment_type=models.IntegerField() in my admin i need to make condition to display. I am new to django so support -
django orm how to make sure postgres array field is not an empty list?
I have the following model for django. This model creates an array field called metric_vals but it is allowing the array to be an empty array. Is there a way of making sure the array is always a non empty array? from django.db import models import uuid from django.contrib.postgres.fields import ArrayField class SampleModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list) -
Django Receive hidden field value in views on submit form
I have a form set and i have assign each hidden value in a form a different value, i want to get the hidden field value in my views after form is submiited. To keep the problem statement easy, this is my dummy code forms.py class myform(forms.Form): abc = forms.CharField(widget = forms.HiddenInput(), required=False, initial="dummy") // views.py if request.method =='POST': if myform.is_valid(): print(i.cleaned_data['abc']) but this is showing error keyerror abc How can i get value of abc in views.py after form is submiited. -
Adding a description to the change list page in Django Admin
I'm working on django admin and wanted to add a description in the change list page at the red mark as shown in the pic this is my admin file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So what is supposed to be added in the admin file so that description can be added at the mentioned placed?? Thanks in advance!! -
how to deploy django app with python 3.8.1 to heroku?
I am trying to deploy django app to heroku. I am getting error when I install django-heroku. It's getting failed. The error is pg_config is required to build psycopg2 from source I try to install psycopg2 also.It is also getting failed. I am using MacOS 10.15.4 and Python 3.8.1. How can I solve this error to deploy django app? -
Why does django autocomplete dont work on first page visit
before python 2.7 code for autocomplete works fine, but after python3 autocomplete dont work as it is, everytime i visit the page the field is always blank and the select2 is not fount everytime I check in google chrome network <link href="{% static 'autocomplete_light/vendor/select2/dist/css/select2.css' %}" type="text/css" media="all" rel="stylesheet" /> <link href="{% static 'autocomplete_light/select2.css' %}" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="{% static 'autocomplete_light/jquery.init.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/autocomplete.init.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/vendor/select2/dist/js/select2.full.js' %}"></script> <script type="text/javascript" src="{% static 'autocomplete_light/select2.js' %}"></script> <script type="text/javascript"> forms.py widgets = { 'tags': autocomplete.ModelSelect2Multiple(url='tags_autocomplete'), } thanks -
SSO with active directory and django to different multiple sites
I'm developing a web portal with Django , and this web portal leads to 3 different platforms , each platform has it's own login/password authentication method, the 3 links are all on the same server(Apache),but each one is build with different framework. i want to implement a one time authentication for all of the 3 sites. How Can i Do this ? i read a lot of articles before coming here, but it seems that my environment is a bit complicated . we also have an active directory server , should i add that to the mix ? thank you -
How can i use two serializers in an APIView?
I have two serializers. I want to use HelloSerializer for POST request and SchemaSerializer for Get Request. In def get i want to list all the data in my model. How do i do that? class SchemaSerializer(serializers.ModelSerializer): """Serializes Schema""" class Meta: model = models.Schema fields = ( 'id', 'name', 'version') class HelloSerializer(serializers.Serializer): name = serializers.CharField() my Views.py: class HelloApiView(APIView): """Test API View""" serializer_class = serializers.HelloSerializer def get() def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.validated_data.get('name') message = f'Hello {name}!' return Response({'message': message}) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) my models.py class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() def __str__(self): return self.name -
BeautifulSoup4. How to follow such links and then parse the content in them?
For starters, i'm new in Python. I want to iterate over an each title link in my article list, follow each title link and then scrape the data on each of these webpages. But the problem is that the title links have an address like https://qwerty.com/review/first-news-article/ https://qwerty.com/review/second-news-article/ https://qwerty.com/review/third-news-article/ Again, i want to stay on each of the link like these, scrape some data, and then again go to the next article, follow the next title link, scrape some data..So, how can i do that in Python? I need to tell my program that I want to stay on the page that I went to by clicking on the article title, and then parse the data from that page.. but as a person who is not very experienced in data parsing, I don't know how. I will be glad if you help me, thanks! :) My code: def scrape(request): website_url = requests.get("https://loudwire.com/news/").text soup = BeautifulSoup(website_url, "html.parser") articles = [] excarr = [] img = [] mysrcset = [] links = soup.find_all('h2', {'class': None}) excerpt = soup.find_all('div', {'class': 'excerpt'}) myimg = soup.find_all('img', {'class': 'attachment-rc_post_thumbnail size-rc_post_thumbnail wp-post-image'}) for image in myimg: img.append(image.get('src')) srcset = image.get('srcset') mysrcset.append(image.get('srcset')) print(srcset) for l in links: print(l.text) articles.append(l.text) … -
Django Model Admin Not Accepting list_display values
I have These two models: class Transaction(models.Model): store = models.ForeignKey(Store, on_delete=models.DO_NOTHING) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) amount = models.DecimalField(max_digits=9, decimal_places=2) cc_type = models.CharField(max_length=3, choices=CC_TYPES) cc_transaction_id = models.CharField(max_length=200) trans_date = models.DateTimeField() qty = models.IntegerField() def __str__(self): return F'{self.store.title} - {self.cc_transaction_id} - {self.amount}' class Meta: unique_together = ('cc_type', 'cc_transaction_id') class Ticket(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.DO_NOTHING) amount = models.DecimalField(max_digits=9, decimal_places=2) ticket_id = models.CharField(max_length=200, unique=True) def __str__(self): return F'{self.ticket_id} - {self.amount}' and these ModelAdmins: @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): list_display = ['amount', 'cc_type', 'cc_transaction_id', 'user', 'store'] list_display_links = ['amount'] search_fields = ['cc_transaction_id', 'store__title', 'user__username'] @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): list_display = ['ticket_id', 'amount', 'transaction__qty'] list_display_links = ['ticket_id'] search_fields = ['ticket_id', 'transaction__cc_transaction_id', 'transaction__user__username'] It get an error when I try to start the runserver saying: <class 'Sales.Stores.admin.TicketAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'transaction__qty', which is not a callable, an attribute of 'TicketAdmin', or an attribute or method on 'stores.Ticket' The list_search seems to resolve fine but the list_display does not. I'm doing something similar in the TransactionAdmin and everything seems to be fine. -
ProgrammingError at /admin/blog/blogcomment/
enter image description here LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_blogcomment"