Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'lib' has no attribute 'X509_get_notBefore'
WARNINGS: ?: (2_0.W001) Your URL pattern '^complete/(?P<backend>[^/]+)/$' [name='complete'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^disconnect/(?P<backend>[^/]+)/$' [name='disconnect'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^disconnect/(?P<backend>[^/]+)/(? P<association_id>\d+)/$' [name='disconnect_individual'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^login/(?P[^/]+)/$' [name='begin'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Hp\anaconda3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\utils.py", line 62, in inner ret = func(self, *args, **kwargs) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 262, in handle self.inner_run(options) File "C:\Users\Hp\anaconda3\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 339, in inner_run … -
Djangochannelsrestframework websocket firstly connects and disconnect
I'm working on a project which uses WebSockets,I'm trying to create websocket connection with djangochannelsrestframework. I tried all like in documentation and I got an error after I start my code by daphne. Everything works fine but when I start a project with daphne turned on the socket keeps connecting and disconnecting with a gap of split second. Any ideas? -
How to pass a variable in a function to update many to many field
I have several functions like: def update_m2m(): ... ... book.author.add(*authors_ids) ... I have the same piece of code for updating other many to many fields. How can I make a separate function for it. For example def update_m2m(obj, field_name, ids): ... ... setattr(obj, field_name, ids) ... But setattr doesn't work for m2m field. Is there any other solution for this? -
Django: Save with related fields via forms
I am fairly new to Python and Django so please bare with me. I have two classes which are related via a ForeignKey. I am trying to save both of them via one screen, create.html which links to view.py. I then specify the models used in form.py. My setup is below and I get the print of Not Valid. I'm not sure what I am doing wrong. model.py class Request(models.Model): title = models.CharField(max_length=50, null=True) description = models.CharField(max_length=200, null=True) class RequestDocument(models.Model): request = models.ForeignKey(Request, related_name='documents', on_delete=models.CASCADE) document = models.FileField(upload_to=request_document_upload_handler) view.py def requests_create_view(request): obj = Request form = RequestForm(request.POST or None) formset = RequestDocumentForm(request.POST or None) context = { "form": form, "formset": formset, "object": obj } if all([form.is_valid(), formset.is_valid()]): parent = form.save(commit=False) parent.save() child = formset.save(commit=False) child.request = parent child.save() context['message'] = 'Data saved.' context['created'] = True else: print('Not Valid') return render(request, "requests/create.html", context) forms.py class RequestDocumentForm(forms.ModelForm): document = forms.FileField() class Meta: model = RequestDocument fields = ['document'] class RequestForm(forms.ModelForm): class Meta: model = Request fields = ['title', 'description'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # django-crispy-forms for field in self.fields: new_data = { "class": 'form-control', } self.fields[str(field)].widget.attrs.update( new_data ) self.fields['description'].widget.attrs.update({'rows': '10'}) create.html {% if not created %} <div style="margin:80px"> <h1>New Request</h1> … -
How to create chart from a dict?
I have a dict like: print(assigned_incidents) => [ {'name': 'Eda', 'case_type': 'Med'}, {'name': 'Deniz', 'case_type': 'High'}, {'name': 'Alex', 'case_type': 'Med'} {'name': 'Eda', 'case_type': 'High'} ] I want to display it in a chart.js chart as a stacked bar chart. For example 'eda' has 2 Med and 1 High case: var assignedIncidents = new Chart(document.getElementById('assigned_incidents').getContext('2d'), { type: 'bar', data: { labels: assigned_incidents-->name, datasets:assigned_incidents-->case_type }' options: { plugins: { }, scales: { x: { stacked: true, }, y: { stacked: true } }, responsive: true } }); How can I do that? -
How to add list field in the django restframework sqlite
how to add list field in the sqlite db in django restframework camera = models.ForeignKey(Camera, on_delete=models.CASCADE) updated_time = models.DateTimeField(auto_now_add=True) objects_inself = models.???? -
How to assign a user to a model in my database
from django.db import models from datetime import datetime from django.contrib.auth import get_user_model User = get_user_model() class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) headline = models.CharField(max_length=250) content = models.CharField(max_length=2050) time_created = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.user.username every time I migrate this "(venv) PS C:\Users\user\Desktop\APPS\web_app_project> python manage.py makemigrations" I always get this message: "It is impossible to add a non-nullable field 'user' to blog without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. Select an option:" How do I go about this -
Django form submit not working without refreshing the whole page
I want to submit the values of the form to views.py. I have tried doing it through jQuery but it's not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. Please let me know where I am going wrong. index.html <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" id="in3" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </div> </div> </form> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val = document.getElementById("value"); const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; form.addEventListener("submit", (e) => { e.preventDefault(); const newform = new FormData(); newform.append("dropdown_val", dropdown_val.value); newform.append("val", val.value); newform.append("csrfmiddlewaretoken", csrf); fetch("{% url 'home' %}", { method: "POST", body: newform, }); }); </script> views.py def home(request): if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) -
Elasticsearch container keeps exiting with these logs
I have a docker container with elasticsearch in it. I think when too much requests is sent to my server this container crashes (exits). Could you approve that this is because of the pressure on server? As we see in logs: Logs Thanks in advance! -
How to show the list_display feature in Inline admin in django?
class CartItemInline(admin.StackedInline): model = CartItem class CartInlineAdmin(admin.ModelAdmin): inlines = [ CartItemInline, ] admin.site.register(Cart, CartInlineAdmin) Trying to display some extra fields in Cart Admin Model. How to do that? -
rabbitmq.conf consumer_timeout not working in docker
I'm trying to execute a longer task with celery, so to test I made a sample task sleep for 5 minutes and set the rabbitmq.conf file with a single line containing consumer_timeout = 10000 expecting the task to fail with precondition error after 10seconds(or at least after 60 seconds as per this answer), but it never did. The task completes after 5mins. I can see the rabbitmq.conf file shows up on top of logs(which I think it means it loaded the file successfully??) main_rabbitmq | Config file(s): /etc/rabbitmq/rabbitmq.conf main_rabbitmq | /etc/rabbitmq/conf.d/10-default-guest-user.conf My Dockerfile: FROM rabbitmq:3.9.13-management # Define environment variables. ENV RABBITMQ_USER user ENV RABBITMQ_PASSWORD password ENV RABBITMQ_PID_FILE /var/lib/rabbitmq/mnesia/rabbitmq COPY ./myrabbit.conf /etc/rabbitmq/rabbitmq.conf ADD init.sh /init.sh RUN chmod +x /init.sh # Define default command CMD ["/init.sh"] The init.sh file is similar to this. -
Django set initial pre-filled field value
I have two models: class Budget(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField(default=now) datecompleted = models.DateTimeField(blank=True, null=True) class Meta: ordering = ['-date'] def __str__(self): return self.name class Expenses(models.Model): name = models.CharField(max_length=25) quantity = models.DecimalField(max_digits=10, decimal_places=2) budget = models.ForeignKey(Budget, on_delete=models.CASCADE, related_name='budget_expense') category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateField(default=now) def __str__(self): return self.name class Meta: ordering = ['-date'] and my Form as follow class ExpenseForm(forms.ModelForm): date = forms.DateTimeField( widget=forms.widgets.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}), label='Data', input_formats=['%d/%m/%Y %H:%M']) class Meta: model = Expenses fields = ('name', 'quantity', 'budget', 'category', 'date') and now I trying to create an instance of Expense with pre-filled (existing) Budget instance with below code: def expense_add(request, pk): if request.method == 'GET': budget = get_object_or_404(Budget, pk=pk) form = ExpenseForm(initial={'budget': budget.name}) return render(request, 'budget/expense-create.html', {'form': form}) else: form = ExpenseForm(request.POST or None) if form.is_valid(): form.save() return redirect('list') return render(request, 'budget/expense-create.html', {'form': form}) but, as you may guess there is nothing in budget field inside my formfield. Please help. Thank you all! -
How to can change the format of date from year-month-date to date-month-year?
Am new in Django so any help will be appreciated, I have a model that contain 3 fields , one of them is date , i want to change the display of date in Django Admin(now it's 2022-05-20 but i want it to be 20-05-2022). How i can do that please ! this is my models.py: class reports(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project_name = models.CharField(verbose_name="Project name", max_length=60) date = models.DateField(verbose_name="Date", default=date.today) def __str__(self): return str(self.user) and this is my admin.py: class reportsAdmin(admin.ModelAdmin): @admin.display(description='date') def admin_date(self, obj): return obj.date.strftime('%d-%m-%Y') list_display = ('user', 'project_name', 'admin_date') admin.site.register(reports, reportsAdmin) and in my settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False USE_TZ = True but nothing work , still display to me in format 2022-05-20(year-month-date). I need to change to date format because i need to render a html to a pdf(xhtml2pdf) and display all fields including the date that should be with the format date-month-year.( that i will get it from the models Table) so How i can correctly change the format date to be date-month-year in Django admin??? -
Can you make a many-to-many field that only selects specific objects from the model
So I'm currently developing an e-commerce store, where I have a model called OrderItem and a model called Order, the OrderItem contains a BooleanField that tells you whether that item has been ordered or not. The Order contains a many-to-many field to OrderItem to show you what items you have ordered, but the problem is that it also selects the items where ordered=True. Is there any way I can have my many-to-many field only select the items where Ordered=False -
Form not submitting CSRF token missing although it is in rendered html
I'm getting a "CSRF token missing" error, when submitting a form in Django. I'm using django-crispy-forms in combination with htmx. The form is rendered via render_crispy_form: def SwapFormView(request, partialform): ctx = {} ctx.update(csrf(request)) mitglied = model_to_dict(request.user.mitglied) if request.method == 'POST': # do form things return HttpResponse("""POST""") else: form = ChangeDataForm( initial=mitglied, partialform=partialform, ) html = render_crispy_form(form, helper=form.helper, context=ctx) return HttpResponse(html) My helper is contructed like this: def __init__(self, *args, **kwargs): super(ChangeDataForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'change-form' self.helper.attrs = { 'hx-post': reverse('back-to-same-url'), 'hx-target': '#change-form', 'hx-swap': 'outerHTML', } self.helper.add_input(Submit('submit', 'absenden')) The thing is, that as soon as I change the helper to a 'normal' POST-Request it works - but I need this to be done via HTMX to only change out the specific parts in the DOM. Weirdest thing for me is, that the token is rendered into the final html of the form: <form hx-post="/profil/nameform/" hx-swap="outerHTML" hx-target="#change-form" id="change-form" method="post" enctype="multipart/form-data" class=""> <input type="hidden" name="csrfmiddlewaretoken" value="token-value"> <label for="id_title" class="">Titel</label> <input type="text" name="title" value="Hau" maxlength="50" class="textinput textInput form-control" id="id_title"> <label for="id_first_name" class=" requiredField">Vorname<span class="asteriskField">*</span> </label> <input type="text" name="first_name" value="Test" maxlength="50" class="textinput textInput form-control" required="" id="id_first_name"> <label for="id_last_name" class=" requiredField">Nachname<span class="asteriskField">*</span></label> <input type="text" name="last_name" value="aBVIpzRJoBKP" maxlength="50" class="textinput textInput form-control" required="" id="id_last_name"> … -
Calling a model method from url parameter
model method: def category_name_en(): return "categoryname" urls: path('<str:region>/<slug:category>/', views.category, name="category_view") template: {% for iteration, article in results_main %} . <a href="{% url 'category_view' region=article.region category=article.category_name_en %}"> . {% endfor %} stack trace: NoReverseMatch at /search/ Reverse for 'category_view' with keyword arguments '{'region': 'en', 'category': ''} The method does not return anything ,so I'm guessing it's either a syntax problem or django does not allow calling methods like that. I am hoping I can resolve this without adding a new field to the model. -
How to calculate numbers of days between two dates and subtract weekends DJANGO MODELS
hope you're all fine! I have a model called Vacation and I'm struggling with one field: days_requested, this field is the number days from vacation_start and vacation_end, it works and gives me an integer as result. The problem I'm facing now is that I need to subtract the weekends (or not count them). What I have: vacation_start = '2022-05-20' vacation_end = '2022-05-24' days_requested = 5 What I'm trying to have: vacation_start = '2022-05-20' vacation_end = '2022-05-24' days_requested = 3 #21/05 and 22/05 are weekends Vacation Models: class Vacation(models.Model): department = models.ForeignKey( 'departments.Department', on_delete=models.SET_NULL, null=True) responsible = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='responsible_vacation') status = models.CharField( max_length=20, choices=STATUS_CHOICES_VACATIONS, default='open') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='created_by_vacation') vacation_start = models.DateField(blank=False) vacation_end = models.DateField(blank=False) days_requested = property( lambda self: (self.vacation_end - self.vacation_start).days + 1 ) def __str__(self): return str(self.created_by.first_name + ' ' + self.created_by.last_name) I have tried: days_requested = property( lambda self: [(self.vacation_start + datetime.timedelta(days=i)).date() for i in range(0, (self.vacation_end - self.vacation_start)) if (self.vacation_start + datetime.timedelta(days=i)).weekday() not in [5, 6].days()]) But I get the following error: 'datetime.timedelta' object cannot be interpreted as an integer And as I perform operations with the amount of days asked I need to … -
AutocompleteSelect broken after moving from django 2.2 to django 3.2
Hello :) After upgrading Django version to 3.2, widget AutocompleteSelect that I use in django admin panel (to have a drop-down from which I can choose an object) is broken. The error I see is AttributeError at /admin/demand/ 'QuerySet' object has no attribute 'name' Request Method: GET Request URL: http://localhost:8000/admin/demand/ Django Version: 3.2.13 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'name' Exception Location: /home/django-app/env/lib/python3.8/site-packages/django/contrib/admin/widgets.py, line 412, in build_attrs Python Executable: /home/django-app/env/bin/python3 Python Version: 3.8.10 Python Path: ['/home/django-app/testsite', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/mb/proj/usun/django-app/env/lib/python3.8/site-packages'] Server time: Fri, 20 May 2022 10:13:27 +0000 Error during template rendering In template /home/django-app/testsite/polls/templates/admin/question_export.html, error at line 18 'QuerySet' object has no attribute 'name' 11 12 {% block content %} 13 <div id="content-main"> 14 <p>Select question to export:</p> 15 <form method="post" enctype="multipart/form-data"> 16 {% csrf_token %} 17 <table> 18 {{form.as_table}} 19 </table> 20 <div class="submit-row"> 21 <input type="submit" value="Export Question" /> 22 </div> 23 </form> 24 </div> 25 {{form.media}} 26 {% endblock %} 27 AutocompleteSelect inherits from AutocompleteMixin When I compare AutocompleteMixin for django 3.2 and django 2.2 https://github.com/django/django/blob/3.2.13/django/contrib/admin/widgets.py#L410-L412 https://github.com/django/django/blob/2.2.7/django/contrib/admin/widgets.py#L411 I see that they added new attributes 'data-app-label': self.field.model._meta.app_label, 'data-model-name': self.field.model._meta.model_name, 'data-field-name': self.field.name, in django 3.2 but there is no name on self.field and probably … -
Django Graphene, order data returned nested response
I have two table that contains data regarding orders and data regarding products in those orders. I would like to return the data from the products table but alphabetical order. schema # region Purchase Orders class PurchasesProducts(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders_products class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {} connection_class = ArtsyConnection class PurchasesQuery(ObjectType): purchases = ArtsyConnectionField(Purchases) @staticmethod def resolve_purchases(self, info, **kwargs): return purchase_orders.objects.filter(user_id=info.context.user.id).all().order_by("-date") purchasesSchema = graphene.Schema(query=PurchasesQuery) # endregion The purchase order data that is return is ordered correctly but date descending. However the data that is returned for the products in a order is not order by anything. I would like to order the products but name alphabetically. response ... "edges": [ { "node": { "id": "", "cmOrderId": "", "username": "", "date": "2022-04-28T20:16:05", "articles": 10, "merchandiseValue": "", "shippingValue": "", "trusteeValue": "", "totalValue": "", "cardMarketPurchaseOrdersProductsOrderId": [ { "id": "", "productId": "", "productName": "Yasharn, Implacable Earth", "productNumber": "148", "quantity": 1, "foil": false, "condition": "NM", "language": "ENG", "cost": "", "status": "INCOMING" }, { "id": "", "productId": "", "productName": "Magmatic Channeler", "productNumber": "240", "quantity": 3, "foil": false, "condition": "NM", "language": "ENG", "cost": "", "status": "INCOMING" }, ... -
EDITING ONE FOR ALL
how to make it so that if you change the value from true to false or vice versa in one place, all others change. class Ralevant default is True class Rooms default is True class Registration value changes and if in the registration class you change from true to false, then the Room class and Ralevant should also change from django.contrib.auth.models import User import datetime class Ralevant(models.Model): bool_roo = models.BooleanField(default=True) def __str__(self): return f'{self.bool_roo}' year=datetime.datetime.now().year month=datetime.datetime.now().month day = datetime.datetime.now().day class Rooms(models.Model): room_num = models.IntegerField() room_bool = models.ForeignKey(Ralevant, on_delete=models.CASCADE, related_name='name1') category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField(default=datetime.datetime(year=year,month=month,day=day+1,hour=12,minute=00,second=00)) guest_count = models.IntegerField() room_bool = models.ForeignKey(Ralevant, on_delete=models.CASCADE, related_name='name2') def __str__(self): return self.rooms,self.last_name,self.first_name -
How to block external requests to a NextJS Api route
I am using NextJS API routes to basically just proxy a custom API built with Python and Django that has not yet been made completely public, I used the tutorial on Vercel to add cors as a middleware to the route however it hasn't provided the exact functionality I wanted. I do not want to allow any person to make a request to the route, this sort of defeats the purpose for but it still at least hides my API key. Question Is there a better way of properly stopping requests made to the route from external sources? Any answer is appreciated! // Api Route import axios from "axios"; import Cors from 'cors' // Initializing the cors middleware const cors = Cors({ methods: ['GET', 'HEAD'], allowedHeaders: ['Content-Type', 'Authorization','Origin'], origin: ["https://squadkitresearch.net", 'http://localhost:3000'], optionsSuccessStatus: 200, }) function runMiddleware(req, res, fn) { return new Promise((resolve, reject) => { fn(req, res, (res) => { if (res instanceof Error) { return reject(res) } return resolve(res) }) }) } async function getApi(req, res) { try { await runMiddleware(req, res, cors) const { query: { url }, } = req; const URL = `https://xxx/api/${url}`; const response = await axios.get(URL, { headers: { Authorization: `Api-Key xxxx`, Accept: "application/json", … -
getting multi values from CSV to DB
I have a CSV file that goes like this 1,CA5D23 ,1410,111, Detail,"/assets/images/thumb/1537.png, /assets/images/thumb/1536.png" 2,C7F91E ,1525,109, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1452.png" 3,C4263D,1375,40, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1201.png" 4,C1595W,600,39, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/1136.png" 5,C3145M,585,39, Detail,/assets/images/thumb/1537.png, /assets/images/thumb/0216.png" the URLs for images are in the same cell. This is my model.py class Account(models.Model): code = models.IntegerField(__("code")) orbs = models.IntegerField(__("orbs")) price = models.IntegerField(__("price")) detail = models.CharField(__("detail"), max_length=255) image = models.ImageField(__("image")) I then import the CSV file to the DB using sqlite3.exe db.sqlite3 command. After that, I go to my index.html and write this code. <tr > {% for account in account %} <td style="text-align:center;vertical-align:middle;">{{account.code}}</td> <td style="text-align:center;vertical-align:middle;"><img src=" {% static 'assets/images/assets/orb.png' %} " width="22" height="22" style="padding-bottom:3px;" />{{account.orbs}}</td> <td style="text-align:center;vertical-align:middle;">{{account.price}}</td> <td style="text-align:center;vertical-align:middle;"><a target="_blank" href=" {% static 'account61f3.html?id_xml=001660' %} " ><input type="button" class="btn btn-success btn-sm" value={{account.detail}} ></a></td> </tr> <tr> <td colspan="5"> <div class="parent"><img class="img" title="" src=" {% static account.image.url %} "width="64" height="64"></div> </td> </tr> {% endfor %}<tr > Focus on the account.image.URL which shows only one image on the site or none if there's more than one URL. How can I include more than one URL to the DB and iterate over it without messing with the next cell? PS: I did try to change from ImageField to CharField and paste the whole image reference on … -
Djangochannelsrestframework websocket firstly connects and disconnect after a second [closed]
I'm trying to create websocket connection with djangochannelsrestframework. I tried all like in documentation and I got this error (venv) user@user-pc:~/Projects/igroteka$ daphne igroteka.asgi:application 2022-05-20 15:20:24,560 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2022-05-20 15:20:24,560 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2022-05-20 15:20:24,561 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2022-05-20 15:20:24,561 INFO Listening on TCP address 127.0.0.1:8000 127.0.0.1:40216 - - [20/May/2022:15:20:30] "WSCONNECTING /ws/" - - 127.0.0.1:40216 - - [20/May/2022:15:20:30] "WSCONNECT /ws/" - - 2022-05-20 15:20:30,569 ERROR Exception inside application: Multiple exceptions: [Errno 111] Connect call failed ('::1', 6379, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 6379) Traceback (most recent call last): File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/utils.py", line 58, in await_many_dispatch await task File "/home/user/Projects/igroteka/venv/lib/python3.8/site-packages/channels/utils.py", line 50, in … -
Display join date and last_login in Django
I have User default Django User model to register user. I want to print user last_login and join_date on the template. And also I want to check if user is active or not. I want to check user active status like this, If user is currently using my website the status should be "Active" If User logged out Then status should be "Loged out" if it is possible please provide me solution for this as well I am filtering user data like this data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Model.py class Profile(models.Model): user = models.OneToOneField(User,default="1", on_delete=models.CASCADE) image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' -
Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct?
I installed django with django and got this eror in runtime: Error reading webpack-stats.json. Are you sure webpack has generated the file and the path is correct? alongside manage.py: vue create frontend Default ([Vue 3] babel, eslint) cd frontend npm run serve list of files in frontend directory is: babel.config.js jsconfig.json node_modules package.json package-lock.json public README.md src vue.config.js npm --version 6.14.15 nodejs --version v10.19.0 node --version v14.17.6 npm list webpack-bundle-tracker └── webpack-bundle-tracker@1.5.0 pip install django-webpack-loader pip freeze django-webpack-loader==1.5.0 INSTALLED_APPS = ( ... 'webpack_loader', ... ) # vue.config.js const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true }) index.html {% load render_bundle from webpack_loader %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <title></title> {% render_bundle 'app' 'css' %} </head> <body> <div class="main"> <main> <div id="app"> </div> {% endblock %} </main> </div> {% render_bundle 'app' 'css' %} </body> </html>