Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a comment form on the post details page
i'm working a bloging site and i would love to add the comment form below the article details, i have created the comment model class Comment(models.Model): post = models.ForeignKey(Article, related_name='comments') user = models.CharField(max_length=250) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.user and this is my comment section can anyone give me a tip i could use <div class="comments-wrapper"> <h2 class="mt-5">LEAVE A COMMENT</h2> <p>Total number of comments <span class="text-danger">{{articles.comments.count}}</span></p> <form action=""> <div class="form-row"> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder="username"> </div> <div class="form-group col-md-6"> <input type="email" class="form-control" placeholder="Email"> </div> </div> <div class="form-group"> <textarea name="" class="form-control" id="" rows="10"></textarea> </div> <input type="submit" class="btn"> </form> <hr> <h2 class="mb-4">COMMENTS</h2> {% for comment in articles.comments.all %} <div class="comments py-2 my-3"> <div class="comments-img-wrapper"> <img src="" class="comment-image" alt=""> </div> <div class="comments-details"> <h5 class="comment-user-name">{{comment.user}} <span class="float-right date">{{comment.created}}</span></h5> <p>{{comment.body}}</p> </div> </div> {% empty %} <p>there are no comments</p>{%endfor%} -
How do you to set model dynamically using django-filter?
From the django-filters doc you set the model for the filter like so import django_filters class ProductFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='iexact') class Meta: model = Product #Here you state the model fields = ['price', 'release_date'] I'd like to have a dynamic model so that I don't have to create a filter for each model. How can I pass information (specifically from the view and more specifically the model) to the filter? I experienced a similar issue with django-tables2 where instead I was able to use table_factory() within the view and pass the necessary object via the context variable. Similarly is there a way to prep the filter in the view already with configured with the model so that I can then pass it in the context variable context['filter'] and then rendered in the template as <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> ? -
How to withdraw a choice from the model
I have a product model that has a quantity in stock and at the entrance to the basket I would like to withdraw this quantity. I created three products and each has one in stock.But for one, I created a quantity of 10.Then i tried to pull out in TypedChoiceField > choices. But I only need one value for this product. from django import forms from shop.models import Product class CartProductForm(forms.Form): product = Product.objects.all() quantity = forms.TypedChoiceField(choices=[(i.stock, str(i.stock)) for i in product], coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py def cart_update(request, product_id): cart = Cart(request) form = CartProductForm(request.POST) product = Product.objects.get(id=product_id) if form.is_valid(): cleaned = form.cleaned_data cart.add(product=product, quantity=cleaned['quantity'], update_quantity=cleaned['update']) return redirect('cart:cart_show') cart.py def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0,'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() I know that I need to somehow convey the product ID and use class CartProductForm(forms.Form): product = Product.objects.get(stock=product.stock) Help me please and sorry for my english -
Pyinstaller with Django 1.11
I have created the REST API using Django REST Framework and it is as expected behaviour. Now i want to make as distribute using pyinstaller. I'm getting error as below, django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django.template.defaulttags': No module named defaulttags [5556] Failed to execute script manage Can anyone suggest me, how to fix this error. -
First project in Django gives me an error
I am a beginner about Python, especially about Django. I tried to use the "python manage.py runserver" command but it gave me an error. PS D:\Programming\Atom_saves\Django_proba1\mysite> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 03, 2019 - 22:20:59 Django version 2.2.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 203, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\servers\basehttp.py", line 67, in init super().init(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 452, in init self.server_bind() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 1: invalid … -
How to implement autosave form using an intermediate model?
I am writing an application on Django. There is a model Article. After a certain period of time, it is necessary to automatically save data from the form in some intermediate model (for example, Draft). And when the user clicks on submit, create an Article and delete the intermediate form. As I understand it, it is being implemented on JS (with ajax). But how best to do it? Any examples? Have ready solutions? Or I need to write yourself (for example, I can send requests after a specified period of time)? <script> //Cycle with given time intervals. //Form processing //ajax request </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="/knowledge_base/add/" class="edit_form new_event" id="id_article_form" enctype="multipart/form-data" onsubmit="submitArticleForm(event, this)"> <div class="content_create"> <div class="field inline textarea"> <input type="text" name="title" id="id_title" style="width: 400px;" required="" class="wide" maxlength="254"> </div> <div class="field inline textarea"> <script type="text/javascript" src="/static/ckeditor/ckeditor-init.js" data-ckeditor-basepath="/static/ckeditor/ckeditor/" id="ckeditor-init-script"></script> <script type="text/javascript" src="/static/ckeditor/ckeditor/ckeditor.js"></script> <div class="django-ckeditor-widget" data-field-id="id_text" style="display: block"> <textarea></textarea> </div> </div> </div> <div class="footer_content"> <div class="footer_select"> <div class="field inline footer_inline select"> <div class="subhead">Category:</div> <select name="category" id="id_category" onchange="changeArticleCategory(event, this);" class="select2 select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"> <option value="" selected="">---------</option> <option value="2">Food</option> <option value="1">Sport</option> </select> <span class="select2 select2-container select2-container--default" dir="ltr" style="width: 82px;"><span class="selection"><span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-id_category-container"><span class="select2-selection__rendered" id="select2-id_category-container"><span class="select2-selection__placeholder"> </span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span></span><span … -
Concatenated django template tag is printing concatenated string instead of value
I'm trying to concatenate a django template grouper with a string so that the whole thing could be used as a template tag. Here's my template: {% block content %} REPORT: </br> {% regroup context by dealid as deal_list %} {% for dealid in deal_list %} {{dealid.grouper}} {% regroup dealid.list by inventory_status as stone_list%} {% for inventory_status in stone_list %} {{inventory_status.grouper}} <table> <thead> <tr> <th>StoneID</th> <th>Ct</th> <th>Cost</th> </tr> </thead> <tbody> {% for stone in inventory_status.list %} <tr> <td>{{ stone.stoneid }}</td> <td>{{ stone.ct_in|floatformat:2 }}</td> <td>{{ stone.cost_purchase|prepend_dollars }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> PROBLEM ---> <b>Subtotal: {{dealid_id.grouper WITH VARIOUS CONCATENATIONS}} <--</b> </br> </br> {% endfor %} {% endblock content %} I've tried: Subtotal: {% with dealid_id.grouper|subtotalT as t %} {{ t }} {% endwith %} - get the string printed and Subtotal: {{"totals."|add:dealid_id.grouper|stringformat:"a/s/r"|add:".Sold.sum_by_deal"}} - get just the last part of the string but I only get the string printed: Subtotal: totals.33.Sold.sum_by_deal, for example which, by the way, works when hardcoded: Subtotal: {{totals.33.Sold.sum_by_deal}} I also tried creating a custom filter: @register.filter def subtotalT(s1): return 'totals.'+str(s1)+'.Sold.sum_by_deal' # https://stackoverflow.com/questions/37933259/how-to-use-django-template-tag-within-another-tag and tried using it like so: Subtotal: {{dealid_id.grouper|subtotalT}} - get the string printed but, again, it prints the string instead of the … -
How to make an appropriate table for mobiles using Bootstrap4
I am trying to make a table with its <td> to appear right below the <th> for mobiles. It currently has several <td> stacked on top of each other but no <td> in between them. It's five <th> stacked together and after that five <td> stacked below together. I want to show below the header is the data in mobiles. Can someone please assist? Your feedback would be helpful. confirmation.html <table class="table table-hover table-bordered table-responsiveness"> <thead class="thead-light"> <tr class="text-center"> <th scope="col">Venue</th> <th scope="col">Quantity</th> <th scope="col">Ticket Price</th> <th scope="col">Hearing Loop</th> <th scope="col">Total Price</th> </tr> </thead> <tbody> {% for ticket in tickets %} <tr class="text-center"> <th scope="row">{{ticket.venue}}</th> <td>{{ticket.quantity}}</td> <td>$25.00 each</td> <td>{{ticket.loop}}</td> <td>${{ticket.total | floatformat:2}}</td> </tr> <tr> <th colspan="4" class="text-right">Sales Tax</th> <td class="text-center">${{ticket.tax | floatformat:2}}</td> </tr> <tr> <th colspan="4" class="text-right">Total</span></th> <td class="text-center">${{ticket.total_price | floatformat:2}}</td> </tr> <tr> <td><a href="/edit/{{ticket.id}}" class="btn btn-primary">Edit</a><a href="/delete/{{ticket.id}}" class="float-right btn btn-danger">Delete</a></td> <td colspan="4"><a href="/payment" class="float-right btn btn-success">Checkout</a></td> </tr> {% endfor %} </tbody> </table> styles.css @media only screen and (max-width: 800px) { /* Force table to not be like tables anymore */ table, thead, tbody, th, td, tr { display: block; } tr { border: 2px solid #ccc; } td { /* Behave like a "row" */ border: none; border-bottom: 1px … -
How can I use AWS's Dynamo Db with Django?
I am developing web applications, APIs, and backends using the Django MVC framework. A major aspect of Django is its implementation of an ORM for models. It is an exceptionally good ORM. Typically when using Django, one utilizes an existing interface that maps one's Django model to a specific DBMS like Postgres, MySQL, or Oracle for example. I have some specific needs, requirements regarding performance and scalability, so I really want to use AWS's Dynamo DB because it is highly cost efficient, very performant, and scales really well. While I think Django allows one to implement their own interface for a DBMS if one wishes to do so, it is clearly advantageous to be able to use an existing DBMS interface when constructing one's Django models if one exists. Can someone recommend a Django model interface to use so I can construct a model in Django that uses AWS's Dynamo DB? How about one using MongoDB? -
how to populate inputs when form is invalid in create view django
What I want How to populate every input of a create view form when it's invalid with the user information has already filled-sended? in so that he does not have to do it again, it only have to correct the information that is wrong. What I've done class RegisterView(CreateView): template_name = 'profiles/register_page.html' form_class = RegisterForm success_url = '/thanks/' def form_invalid(self, form): response = super().form_invalid(form) messages.error(self.request, "Please check your information and try again.") return response def form_valid(self, form): response = super().form_valid(form) email = form.cleaned_data['email'] Mailchimp().add_email(email) form.save() return response def get_initial(self): initial = super(RegisterView, self).get_initial() email = self.request.POST.get('email') company_name = self.request.POST.get('company_name') contact_number = self.request.POST.get('contact_number') password = self.request.POST.get('password') if email: initial['email'] = email if email: initial['company_name'] = company_name if contact_number: initial['contact_number'] = contact_number if password: initial['password'] = contact_number return initial -
How to fix this error while creating superuser?
I am facing this error when I run this command: heroku run python manage.py createsuperuser I tried running makemigrations and then migrate which works fine but I still get this error. You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user -
How to import a class from a directory to the children of another directory
I'm currently trying to import a class from a directory to a child of a different directory. I try not to use sys.path and use relative imports, however it keeps giving the error about attempted relative import with no know parent package. So I do not know if it's feasible to import a class from a directory which has higher level in project tree to a grandchild of a different directory? In this case, I want to import a class ModelTest in model.py in app folder to output.py. All the sub-directories have int.py, except the myproject directory. Thank you Here is my project tree: Myproject: - mainmodel * api - Four spaces again. ├── myproject │ ├── mainModel | | ├──api | | ├──script | | ├──output.py │ │ │ ├── app │ │ ├── model.py myproject - mainModel - api -script -output.py -app -model.py Django REST framework -
Django: Console returns "value must be a decimal number" on a CharField defined field?
Right..... so I'm confused about this. The code function that this error was based on is that a user submits a csv file full of specified data. Django would handle the data processing and add the submitted data to a MySQL database. In the midst of debugging some processing errors, and ensuring that all my defined lists match up with the csv file header order and all, Django's Model.save() function wouldn't work. And so I had exceptions turned on and printed to console, where I get this as the error: [u"'value1' value must be a decimal number."] Where 'value1' is the data value to be entered into a CharField defined field. Both my models.py file is defined as string, and MySQL database table via PHPMyAdmin has this field defined as char(N). I guess here is the model definition of the field as reference: x_version = models.CharField(choices=X_VERSION_CHOICES, max_length=32, blank=True, verbose_name='By X Field Version') And here is an sample definition of the choices: X_VERSION_CHOICES = ( ('value1', 'value12'), ('value3', 'value13'), ) The values for this field must be one of the pre-defined string choices, so there isn't any option of changing this value to a Decimal value. Why would Django show this … -
How to add model values to dropdown field
i want to add a drop down field in template and want to retrieve the values from my model. I'm new to django so i need help with how to and what to do. class DepartmentForm(forms.ModelForm): department = forms.CharField(widget=forms.Select(Department.objects.all().values('department_name'))) class Department(models.Model): department_id = models.AutoField(primary_key=True) department_name = models.CharField("department", max_length=50) -
How do I create a django form that displays radio buttons for all foreign keys on the same page?
I am creating a quiz/survey app. My question about basic use of django forms consists of two elements: How may I use a form (such as a ModelForm) to display the options and a radio button for each question on the same page? (I have read the docs but seem currently incapable of producing an effective ModelForm.) How may I return all of the radio button selections to the view by clicking one submit button? I have spent the day reading the docs, online articles, and as many SO answers as I could find. I suspect that there several factors that I have missed. I have resorted to writing the page using template tags. I would like to know learn to use a django form properly. models.py from django.db import models from django.contrib.auth.models import User class Collection(models.Model): date = models.DateTimeField() def __str__(self): return 'Collection of questions' class Question(models.Model): question_text = models.CharField(max_length=400) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, default=None) date_published = models.DateTimeField('date published') @property def options(self): options = self.option_set.all() return options if options.exists() else 'No options for this question' def __str__(self): return self.question_text class Option(models.Model): option_text = models.CharField(max_length=400) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return f'{self.option_text}' class Answer(models.Model): claim_reference_number = models.IntegerField() date_selected = … -
Simple django DetailView doesn't work, how to pass to pass 2 arguments to DetailView
I want to create detail view for my Playlist model. I followed steps from docs and i keep getting this error: AttributeError at /root Generic detail view PlaylistDetail must be called with either an object pk or a slug in the URLconf. here is my code: model: class Playlist(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension]) tracks = models.ManyToManyField(Track) def __str__(self): return self.title url: path('<slug:author>', PlaylistDetail.as_view(), name='playlist'), view: class PlaylistDetail(DetailView): model = Playlist def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context I suppose its caused because of that there are more than one playlist created by the same user, and it will must get User && title. Any suggestions? -
Handling Bad Inbound ISO8601 DateTime Offset with Django Rest Framework
My mobile client is sending up inaccurate datetime offset information. For example: 2019-05-03T17:55:12-0700 The time is actually the correct UTC time however, the offset should read -0000. I can not currently modify the client to correct the issue causing this. So I need to throw out the offset or change it to -0000. In the above example, for this user who has their account timezone settings set to PST, it stores the date in validated_data as datetime.datetime(2019, 5, 4, 0, 55, 12, tzinfo=<UTC>) If client-based time and offset information were synced up, this conversion by DRF would be correct, as it is seven hours off or PST + the current DST. (west coast us is currently -7:00 UTC) The problem is that by the time I reach my ModelSerializer class, the validated_data already contains what DRF believes is now the correct UTC time. Where is the appropriate place to mutate this field on the POST body so that by the time DRF attempts to create the DateTime it will build the correct timestamp? -
Displaying all Django-taggit tags for each given object
I'm trying to display all the django-taggit tags related to the given object when I'm querying. I've tried adding this function within my search_result.html template like this but no tags are being displayed: {% if page_obj.object_list %} <ol class="row top20"> {% for result in page_obj.object_list %} <div class="showcase col-sm-6 col-md-4"> <a href="{{ result.object.get_absolute_url }}"> <h3>{{result.object.title}}</h3> <img src="{{ result.object.image }}" class="img-responsive"> </a> <!-- I want to display them in the span below --> <div class="text-center"> <span class="label label-info">{{ result.object.ptags.name }}</span> </div> </div> {% endfor %} </ol> </div> {% endif %} My Models: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title My custom forms.py function: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs And I'm passing the forms into … -
Django environment setup 'getting no module found error' and 'Secret code can't be empty'
I am new to Django and I am trying to run the server for one of my projects ,I have the following structure enter image description here I Have two settings one for prod and one for dev ,when i am trying to run the application at this root --./web> py manage.py runserver --settings=webapp.dev_settings. I am getting ImproperlyConfigured: The SECRET_KEY setting must not be empty. error. After some research I tried export Django_settings_Module =webapp.settings.dev and trying to run again I am facing ModuleNotFoundError: No module named 'webapp.settings' please do let me know what to update and how to proceed with this -
Setting the JWT Authorization header
I have been working on Authorisation/Authentication using JWT. I am generating a JWT token while logging in and setting it in the HttpResponse as a header, like so response["Authorization"] = "Token " + jwt_token What I want is, all my subsequent requests should send this header to the server, so that I can check if the user is authorised. How can I achieve this? I used the ModHeader extension in chrome and added my header. Everything works smoothly. I am not able to figure out, how to send the header without using the extension. -
Nothing is written to Nginx access.log/error.log - how to troubleshoot?
I have a Django project deployed with Docker on DigitalOcean. I based it off this tutorial, but had to change some things to get it working. I'm getting a 500 error when I try SMTP email registration live (works fine locally), and the proximate issue is that I can't get any more information about this error because nothing is being written to the nginx access.log/error.log (files are always empty) and there's no output to any docker logs I can find. I've been all over Stack Overflow and the Internet-at-large, but found no help. I've tried changing permissions/owner on the log files to match the Nginx worker, made no difference. I've tried re-specifying the default log files (/var/log/nginx/error.log) in Nginx configuration, even though it seems like I shouldn't have to, and that made no difference either. Here's what I have in nginx/sites-enabled: server { listen 80; server_name 134.209.172.141; charset utf-8; location /static { alias /www/static; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ...and the nginx Dockerfile: FROM tutum/nginx RUN rm /etc/nginx/sites-enabled/default COPY sites-enabled/ /etc/nginx/sites-enabled I don't specify an nginx.conf file, but I notice if I shell into the nginx container there … -
Django paypal returns error : render() got an unexpected keyword argument 'renderer'
I am trying to implement the the paypal checkout button. I'm using django-paypal. I keep getting this error : render() got an unexpected keyword argument 'renderer'. I have no clue what's causing it. I am using django 2.1. Here's my paypal process view: def payment_process(request): template = loader.get_template("payment/process.html") paypal_dict = { "business": "henryemeka34@yahoo.com", "amount": "100.00", "item_name": "name of the item", "invoice": "unique-invoice-id", "currency_code": "USD", "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('payment:done')), "cancel_return": request.build_absolute_uri(reverse('payment:cancelled')), # "custom": "premium_plan", # Custom command to correlate to some function later (optional) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return HttpResponse(template.render(context,request)) -
how to change multiple image src using jquery in django
i'm trying to change the image src for each comment depending on the first letter found in the users name {% for comment in articles.comments.all %} <div class="comments py-2 my-3"> <div class="comments-img-wrapper"> <img src="" class="comment-image" alt=""> </div> <div class="comments-details"> <h5 class="comment-user-name">{{comment.user}} <span class="float-right date">{{comment.created}}</span></h5> <p>{{comment.body}}</p> </div> </div> {% empty %} <p>there are no comments</p> {% endfor %} and the jquery code i'm using is this <script> $(".comment-image").each(function(){ username = $('.comment-user-name').text(); usernameFirstletter = username.charAt(0).toUpperCase(); console.log(usernameFirstletter) $(".comment-image").attr('src', '/static/img/avatars/' + usernameFirstletter + '.svg'); }); </script> but for some reason it keeps repeating the image of the first ccomment for the remaining comments, can anyone help -
Django superuser creation no response
I have been trying to create a superuser but it eventually gives me no response and just sits idle after I fill out the password. (venv) [root@ubuntu:~/folder/pfg]$ python3 manage.py createsuperuser Exception in importing from settings_local, continuing without No module named 'pfg.settings_local' System check identified some issues: WARNINGS: content.Item.category_measures: (fields.W340) null has no effect on ManyToManyField. content.Item.vocab_items: (fields.W340) null has no effect on ManyToManyField. Username (leave blank to use 'root'): django Email address: cewehuj@email-server.info Password: Password (again): I got this exception but even after that the username password forms load, so I am hoping the exception is not serious, but after everything it just sits there with no response. -
Need way to provide Solr boost function in Django Haystack
I need to provide my search results an edismax boost function feed_count follower_count^8.0, which should result in the following URL: http://localhost:8983/solr/ng_core/select?bf=feed_count%20follower_count%5E8.0&defType=edismax&q=shad Closest I came by searching the docs and stackoverflow was to filter using AltParser like this: sqs.filter(text=AltParser('edismax', query, bf='feed count follower_count^8.0') which produces the following query: {!edismax bf='feed count follower_count^8.0' }shad which returns no result at all. I played around in Solr Dashboard and even if I get it to return results, the way Solr parses it is very very different than it does the expected query. I tried reading upon how to add custom query params to the generated query, but the Custom Input method does not fit my need since it can only change the query text and not add parameters. The current workaround I had to do was to do it this way: sqs.query.get_results(defType='edismax', bf='feed_count') So that the extra kwargs get passed on to the final query function, however, I really don't want to jump out of the nice SearchQuerySet chaining, and more importantly, I can't get the paging to work with this nicely: sqs.query.get_results(defType='edismax', bf='feed_count')[offset:offset + page_size] This won't work since the results have already been fetched, and sqs[offset:offset + page_size].query.get_results(defType='edismax', bf='feed_count') This won't work …