Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django, Javascript Ajax - Submit item from select list
Suppose you have a select list and a button to submit your selection. <select class="select_user" id="select_user"> {% for employee in users %} {% if not employee.is_admin %} <option id="{{ employee.id }}" value="{{ employee.id }}">{{ employee.first_name }} {{ employee.last_name }}</option> {% endif %} {% endfor %} </select> <button class="make-admin">Make Admin</button> I am trying to send the id of the selected item to one of my views: Javascript: $(document).ready(function () { $(".make-admin").click(function (e) { var id = $(this).attr('id') e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'work_entries:object_edit' %}', data:{ id: id, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success:function(response){ $(".main-table").html(response) } And the view: def object_edit(request): if request.POST.get("action") == "post": object_id = request.POST.get("id") record = get_object_or_404(User, id=object_id) # Change some stuff about the record... return JsonResponse("Success") I know there is something wrong with the javascript, but I can't quite understand. Any suggestions? -
Why is my Django CORS configuraiton allowing some requests and not others from the same server?
I'm using Django 3, Python 3.7, and I want to configure my local Django server to accept cross origin domain requests, specifically from my React application running on port 3000. I installed corsheaders and configured the below ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'directory', 'phonenumber_field', 'address', 'django_extensions', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ] Oddly, everything is working except for one request, http://localhost:8000/states/US, which consistently produces the below error in the devtools console Access to fetch at 'http://localhost:8000/states/US' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Oddly other requests succeed, as you can see from the screen shot below. What else do I need to do to configure my local Django server to allow requests from any localhost:3000 request? -
Using QuerySet.update() to update specific keys in nested JSONField
So let's say I have a Model defined as below: from django.contrib.postgres.fields import JSONField class Job(models.Model): ... json_data = JSONField(default=dict, blank=True) The json_data field has a key named approval_coefficient with values ranging from 0 to 1. I want to update all the Jobs with json_data__approval_coefficient as 0.25 to 0.75 without firing any post_save Signals, in one Query. Basically, I want to use the .update() to work with JSONfield. Job.objects.filter(json_data__approval_coefficient=0.25).update(json_data...) This doesn't work. (There are maybe 50 more keys for each Job object in json_data field, and I don't want to touch/update them at all. I am just concerned with this specific key.) Although, I can get all the jobs using the filter query, and loop through it and update each of the entries one by one. But, this does multiple Write queries to the DB, and also fires post_save signals, which is not what I want. On doing some digging around, found this and this PR which was never merged in Django. How to go about this? Python 3.6.8 Django (2, 2, 0, 'final', 0) -
creating bold text in mails send by django send_mass_mail
Django send_mass_mail doesn't allow sending html mails but I want to make a portion of the mail bold. I tried: message= ("bla bla '<b>%s</b>'."% title.title) But as you can guess it escapes the tags in the mail. I wonder if there is a solution for that. -
How to pass a queryset to render_to_string (Django view)
Here is the code for my views function: def showCommunityAskQ(request): html = "" student_id = request.user.id student_question_queryset = Question.get_student_questions( request, student_id) if request.method == 'POST': html = render_to_string( 'students/community_askq_view.html', {'myquestions': student_question_queryset, }) return HttpResponse(html) In my template the following code: <tbody> {% for question in myquestions %} <tr> <td class="center"><b>{{ question }}</b></td> .... In the place of {{ question }}, I'm getting a string: (datetime.datetime(2020, 6, 24, 12, 31, 34, 245983), 'Does the English language have cases?') I want to access the timestamp and the question separately. In this use case I believe I must use render_to_string, because it is actually an ajax call that calls the view and returns the template, so I can't use the render function for that. -
How to retrieve objects from foreign key relation in model
so I am trying to retrieve my Post object from my *Bookmark model which is based on a base model. However, it seems it is always returning null, and I was wondering how can I retrieve my post oject? This is my bookmark model: class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(Profile,on_delete=models.CASCADE, verbose_name="User") def __str__(self): return self.user.username class BookmarkPost(BookmarkBase): class Meta: db_table = "bookmark_post" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey('home.Post',on_delete=models.CASCADE, verbose_name="Post") and in my views.py I have the query: posts = BookmarkPost.obj_set.filter(user__id=request.user.id) However, it is not returning anything although I do have posts bookmarked. How can I achieve this? Thanks in advance! -
How to get "print(data)" in ubuntu server
I have this code edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by( 'pk').first() print(edulevel, 'edulevel') how do i get that value or show the of 'edulevel' in my ubuntu server? I am using python language and django framework -
Could not parse the remainder: '=='failed'' from '=='failed''
{% if file_status == 'failed' %} getting the error :Could not parse the remainder: '=='failed'' from '=='failed'' What did I do wrong? -
Unable to get or create object within a form
I am trying to get or create an object when another one is created with a form : def index(request, log_id, token): log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log_id) form = CreateLogMessage(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.reported_by = request.user instance.logbook = log instance.save() logdone = LogDone.objects.get_or_create(logmessage=logmessages, done_status=False) I am trying to figure out a way to get the id of the logmessage created to pass it to my logdone instance. I don't find a way to do it so far, any help will be appreciate it. -
Celery ignore_result not working properly
I have e Django application that calls periodically a serie of Celery tasks that use a redis backend to manage some stuff, I don't really need to store the results of all the tasks. My redis gets quickly populated with entries called celery-meta-data-some-random-id-string, containing the task itself and its result. I wanted to get rid of those so I added 'ignore_result' = True to the tasks I didn't care about the result. My task is defined as: @shared_task(name='my.name','ignore_result' = True) def mytask(foo,bar): //do stuff return I tried to add the default behaviour adding to my Django.settings CELERY_IGNORE_RESULT = True and from celery.py in my django application I loaded the settings like this from django.conf import settings app = Celery('myapp') app.config_from_object(settings, namespace='CELERY') Here is my setting.py CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_BROKER_URL = 'redis://0.0.0.0/0' CELERY_ACCEPT_CONTENT = ['pickle', ] #'json', 'msgpack', 'yaml' CELERY_BACKEND = 'redis://0.0.0.0/0' CELERY_RESULT_BACKEND = 'redis://0.0.0.0/0' CELERY_TIMEZONE = 'Europe/Rome' Using Celery Flower I can check the task configs, the CELERY_IGNORE_RESULT variable is set to True for all of them, so i think the config is correct. Is there something I'm completely missing? I tried to work around this cleaning up the redis periodically but it would be more optimal … -
How to write a nested conditional statement in Django template file to get the number of field-specific form errors
In my Django app I have a template file where I need to amend the layout based on the form errors. In pure Python, what I'd like to be able to write in Django's template syntax is: if form.errors and not (form.errors.length == 1 and form.non_field_errors.length == 1) I know you can't use parenthases in if/else template syntax, so I started with: {% if form.errors and not form.errors|length == 1 and not form.non_field_errors|length == 1 %} But that would just short circuit when the number of form errors is not equal to 1. Now I have: {% if form.non_field_errors|length == 1 and form.errors|length == 1 %} <!-- Do nothing --> {% elif form.errors %} <p>My conditional content</p> {% endif %} ...which does the job, but it's pretty ugly. Is there a better way of writing this in Django's template syntax given the limitations it imposes? It feels like I am missing something obvious here. Basically, if there are 1 or more form errors - and those errors are not all non-field errors - I want to do something. Right now if I raise a non-field error it appears in non_field_errors and errors. If I raise a field-specific error, that obviously … -
Wagtail: How can I display Categories from Child Pages on a List Page
I'm trying to get the hang of Wagtail and have a page that lists all of the posts on the site. I want to display a category tab on the card that holds the info for each post. The text and title are pulling correctly, but I can't get the category data. I have this code, but it pulls every category on the site, not for each post. {% for cat in categories %} <li class="d-inline-flex"> <a href="{{self.get_parent.url}}?category={{cat.slug}}"> <span class="badge badge-pill badge-primary pt-2 pb-2">{{cat.name}}</span> </a> </li> {% endfor %} class LessonCategory(models.Model): """ Set Up Lesson Category In Wagtail Admin """ name = models.CharField(max_length=100) slug = models.SlugField( unique=True, max_length=40, verbose_name="slug", allow_unicode=True, help_text="Add a category slug", ) panels = [ FieldPanel('name'), FieldPanel('slug'), ] class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ["name"] def __str__(self): return self.name Can anyone point me in the right direction? -
All my Project have been erased by Pycharm
I develop a site with Django and PyCharm. I just linked my project to a GitHub repository, pushed the git-ignore file to make a test, and then I closed the project, when I reopened the project, Pycharm started to make some initialization, and all my Django project has been destroyed... I tried to find some files with recuva, the only thing I founded was a xml file. When I open the project, the github repository is not even linked anymore. And in the right upper corner I can see one of my old html file : base.html. (see the capture). I don't know what to do, please tell me we can do something. This is multiple days of works who have vanished. -
Adding custom CSS to card in Bootstrap 4
I have gone through several questions and solutions on StackOverflow but it doesn't seem to work for me. Although, p-5 is working fine for padding but this works for all devices. I want specific CSS for mobile for padding. I tried adding custom CSS and added custom class infocards in the cards div but it's not working. Also, I added !important to override any equal weight styling on bootstrap with my custom one. Note: I am building my page using Django and files are static. They have been properly configured in settings.py. My index.html: <link rel="stylesheet" href="{% static '/custom.css' %}" /> <div class="col-md-6"> <div class="contacts card p-5 infocards"> <h3 class="mb-4">Contact Info</h3> <div class="row mb-4"> <div class="col-1"> <i class="fa fa-user"></i> </div> <div class="col-9"> <span>Naman Chauhan</span> </div> </div> </div> </div> Here's custom.css: /*for mobile*/ .infocards { padding: 10px !important; } /*for desktop*/ @media only screen and (min-width: 768px) { } -
Django Formset : Link a Formset with a Queryset to update the DB with an ajax request
I have 2 models that i will simplify for the purpose of this example. class EventParticipant(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) customerOrder = models.ForeignKey(CustomerOrder, on_delete=models.CASCADE) present = models.BooleanField(default=False) class CustomerOrder(models.Model): paid = models.BooleanField(default=False) And my form ( simplified ) : class EventParticipantForm(ModelForm): participantNationality = forms.CharField(validators=[validate_country], required=True) class Meta: model = EventParticipant fields = ['participantFirstName', 'participantLastName', 'eMail', 'participantStatus', 'participantNationality', 'participantSecondNationality', 'participantThirdNationality', 'participantStreet', 'participantStreetNumber', 'participantCity', 'participantState', 'participantZipcode', 'participantCountryResidency', 'participantSpecialNeeds', 'participantLetter', 'present', 'refund', ] So my view kinda look like ( this view is an example, i rewrote the original one ): def render_event_by_year(request, event_pk): event_details = Events.objects.get(pk=event_pk) event_part = EventParticipant.objects.filter(event=event_pk).select_related('customerOrder') product = Product.objects.get(productName=str(event_details)) totalPart = len(event_part) event_participant_formset = modelformset_factory(EventParticipant, form=EventParticipantForm, extra=totalPart) formset = event_participant_formset( queryset=EventParticipant.objects.filter(event=event_pk)) if request.is_ajax: pass return render(request, 'manager/eventsearch.html', {'event_part_query': event_part, 'product': product, 'totalPart': totalPart, 'formset': formset}) So what i do in the template is rendering the event_part_query in a table. What i want to do, is to add the field present of the formset to this table so one of the row will be the field from the form and the user will be able to update the status of the participant. The ajax part is not a problem, but i cant render the form with a forloop as i … -
DJANGO POST request is submitting but data not updating
I have an application that I'm working on where a user can update a task in an form within an edit view and submit the changes with a button. The terminal shows the post request is going through, but the page doesn't redirect nor does the data change. Another thing I've noticed is towards the bottom right, every time I click the update button, its says "waiting for craftprimes.com", which I don't remember being there before. However, adding tasks and deleting them works perfectly fine. The update functionality was working yesterday, so I'm not sure what is happening. Thank you for the help! Here is my views.py for update and delete @login_required def update_item(request, pk): current_item = todoItem.objects.get(id=pk) create_form = CreateItemForm(instance=current_item) if request.method == 'POST': # 2nd arg ensures it wont create a new item, but rather update it create_form = CreateItemForm(request.POST, instance=current_item) if create_form.is_valid(): create_form.save() return redirect('todo-home') context = { 'create_form': create_form, 'item': current_item } return render(request, 'todolist/edit_item.html', context) def delete_item(request, pk): current_item = todoItem.objects.get(id=pk) if request.method == 'POST': current_item.delete() return redirect('todo-home') context = { 'item': current_item } return render(request, 'todolist/delete_item.html', context) Here is my urls.py from . import views from django.urls import path from .views import ItemListCreateView urlpatterns … -
Django Password reset with token
My Django application uses a token based password reset mechanism, but I'm currently not able to display any error message at my template if "user is not None and str(form_token) == str(user.reset_token)" is not given -> Error if my input is a none existing user: File "/app/App_Accounts/views.py", line 280, in reset_password user = form.save() File "/app/App_Accounts/forms.py", line 315, in save user = User.objects.get(user=form_user) App_Accounts.models.User.DoesNotExist: User matching query does not exist. views.py: def reset_password(request): if request.method == 'POST': form = TokenPasswordResetForm(request.POST) if form.is_valid(): user = form.save() # line 280 .... forms.py: class TokenPasswordResetForm(forms.Form): error_messages = { 'password_mismatch': _('Password fields didn’t match, please try again'), 'user_or_token_mismatch': _('Unable to find user or token match'), } user = forms.CharField( required=True, strip=False, ) reset_token = forms.CharField( required=True, strip=False ) new_password1 = forms.CharField( label=_("New Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), ) ... def __init__(self, *args, **kwargs): super(TokenPasswordResetForm, self).__init__(*args, **kwargs) self.fields['user'].label = 'Username:' ... def save(self, commit=True): """Save the new password.""" form_user = self.cleaned_data.get('user') form_token = self.cleaned_data.get('reset_token') user = User.objects.get(user=form_user) if user is not None and str(form_token) == str(user.reset_token): password = self.cleaned_data["new_password1"] user.set_password(password) user.reset_token_memorized = False user.reset_token = reset_token_generator() if commit: user.save() return user raise forms.ValidationError( self.error_messages['user_or_token_mismatch'], code='user_or_token_mismatch', ) -
How to get static files in javascript?
someone who can help me get the url of static files in javascript. I have tried this: I have a variable that has the path of my file and I want to use it as an argument as follows: function(json) { if (json.status=='1') { var file = "{% static 'path' %}".replace(/'path'/, json.url_file); } } I have also tried it like this function(json) { if (json.status=='1') { var file = `{% static '${json.url_file}' %}`; } } -
hello guys i am using django but it`s not loading JavaScript and jquery
<script src="{% static 'assets/js/jquery.min.js' %}"></script> <script src="{% static 'assets/js/popper.min.js' %}"></script> <script src="{% static 'assets/js/bootstrap.min.js' %}"></script> <script src="{% static 'assets/lib/%40fortawesome/all.min.js' %}"></script> <script src="{% static 'assets/lib/stickyfilljs/stickyfill.min.js' %}"></script> <script src="{% static 'assets/lib/sticky-kit/sticky-kit.min.js' %}"></script> <script src="{% static 'assets/lib/is_js/is.min.js' %}"></script> <script src="{% static 'assets/lib/lodash/lodash.min.js' %}"></script> <script src="{% static 'assets/lib/perfect-scrollbar/perfect-scrollbar.js' %}"></script> <script src="{% static 'assets/lib/fancybox/jquery.fancybox.min.js' %}"></script> <script src="{% static 'assets/lib/plyr/plyr.polyfilled.min.js' %}"></script> <script src="{% static 'assets/lib/select2/select2.min.js' %}"></script> <script src="{% static 'assets/js/theme.min.js' %}"></script> even in settings i have added this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
NoReverseMatch at. Django
I have an error NoReverseMatch at /search_shop_results/5ka/ Reverse for 'search_shop_results' with no arguments not found. 1 pattern(s) tried: ['search_shop_results\/(?P[-a-zA-Z0-9_]+)\/$'] After click on this form product_list.html <div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;"> <form action="{% url 'search_shop_results' curr_slug %}" method="get"> I think that problem deals with invalid argument curr_slug 5ka is a valid slug name. views.py class ProductListView(ListView): model = Product template_name = 'blog/product_list.html' page_kwarg = 'product' context_object_name = 'products' paginate_by = 30 def get_context_data(self, **kwargs): # В первую очередь получаем базовую реализацию контекста context = super(ProductListView, self).get_context_data(**kwargs) # Добавляем новую переменную к контексту и иниуиализируем ее некоторым значением context['CHOICES'] = CHOICES context['shops'] = Shop.objects.all() context['curr_slug'] = self.kwargs['slug'] return context def get_queryset(self): return Product.objects.filter(shop__slug=self.kwargs['slug']) urls.py urlpatterns = [ path('search_shop/<slug:slug>/', ProductListView.as_view(), name='search_shop'), path('search_shop_results/<slug:slug>/', ProductSearchResultsView.as_view(), name='search_shop_results'), ... models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) slug = models.SlugField(null=False, default="Shop") class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="shop") title = models.CharField(max_length=200) -
I want to fetch data from a model in django using xmlhttprequest. I don't want to use drf. Is there a way to do it?
Suppose I have a model post which contains fields such as title, description, image and video. In view I will query the post model using Post.objects.all() but I want to fetch the data in Post using xmlhttprequest. Can I do it? If so, how? -
Filter in ModelSerializer DRF via Query Parameter
I am new to DRF and having difficulty filtering data. My model.py looks like this class ScanHistory(models.Model): last_scan_date = models.DateTimeField() scan_status = models.IntegerField() class ScannedHost(models.Model): subdomain = models.CharField(max_length=1000) scan_history = models.ForeignKey(ScanHistory, on_delete=models.CASCADE) technology_stack = models.CharField(max_length=1500, null=True) And my serializer.py looks like this class ScannedHostSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = ScannedHost fields = '__all__' How do I filter with ScanHistory ID? Suppose http://localhost:8000/api/scannedHost/?scan_history=1 Though ScanHistory has One to Many relationship with ScannedHost, I am aware ID in ScanHistory can be referenced with scan_history__id How do I make scan_history as query param and filter data based on it? -
Unable to deploy Django App to google cloud app engine with MySQL database instance
The response I get is (base) bukenya@bukenya-HP-EliteBook-8460p:~/Downloads/DjangoApplications/ecommerce$ ./cloud_sql_proxy -instances="jumanji-280508:us-central1:ecommerce-instance1"=tcp:3306 2020/06/24 18:35:50 failed to setup file descriptor limits: failed to set rlimit {&{8500 4096}} for max file descriptors: invalid argument 2020/06/24 18:35:53 listen tcp 127.0.0.1:3306: bind: address already in use -
Appending string to dictionary values using jinja template
I have the following code for accessing the values in dictionary using jinja template {% for key,value in names.items %} {% for val in value %} <p class="lead">{{ val }} </p> {% endfor %} {% endfor %} For every value,it is printed I want to append a string.My values are "abc","2456789","28-02-1991".I want the following output: Name:abc Id:2456789 Date: 28-02-1991 How could I do it using jinja template? -
Django changed form field detection
I'm working with Django formset and I receiving new form data every time a (any) field has been changed by the user. So my empty form.data looks like this: MultiValueDict: {} And after user changes any field my form.data becomes like this (I changed country field in the first form): QueryDict: { 'form-0-country': ['1'], 'form-0-region': [''], 'form-1-country': [''], 'form-1-region': [''], 'form-2-country': [''], 'form-2-region': [''], } Here's my form if needed: class SignCreateForm(ModelForm): data_url = '/sign-form-data/' class Meta: model = FormModel fields = ['country', 'region'] class Media: # ajax form refreshing script js = ('js/formset.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: print(self.data) And I need to detect field that has been changed by user on web page. So I want to compare my previous form data with new received data but I'm not sure if it's a good idea because I don't have original data QueryDict with filled keys and empty values. Is there any way to get/calculate the modified form field?