Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model and Template Connection
Here is my code: {% extends "blogapp/base.html" %} {% load static %} {% block page_content %} <h1>Projects</h1> {% for project in projects %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{% static 'sampleimg.jpg' %}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a class="btn btn-primary" href="{% url project.detail %}">Read More</a> </div> </div> {% endfor %} {% endblock %} models.py from django.db import models class Project(models.Model): title = models.CharField(max_length=260) description = models.TextField() technology = models.CharField(max_length=260) #image = models.FilePathField(path='/images') views.py from django.shortcuts import render from .models import Project def project_index(request): projects = Project.objects.all() context = { 'project':projects } return render(request,'blogapp/project_index.html',context) def project_detail(request,pk): projects = Project.objects.get(pk=pk) context = { 'project':projects } return render(request,'blogapp/project_detail.html',context) I added 2 post from admin but i cant see when i run the server. Here is a ss : I have 2 blog post but i dont see them. What can be the problem? -
Cleaning up empty sessions in django side effects
I am already familiar with django's management command clearsessions, But we had some legacy logic in our code base that used to create session objects for all the visitors - if they did not have a previous session value assigned to them. It was for A/B testing purposes (We had to fix the test for each user and figured the session key would be a good value for this usage) The problem is now that we have gotten rid of this redundant session creation logic, we have ended up with something around 180 million empty session records. $ echo NjU3ODI5ZTg5MDY0OWE1YzYzNTczMzEzM2ExMGQ4NTI4ODNlZGFiNTp7fQ== | base64 -d $ 657829e890649a5c635733133a10d852883edab5:{} Obviously this session_data is an empty session. In [9]: Session.objects.filter(session_data="NjU3ODI5ZTg5MDY0OWE1YzYzNTczMzEzM2ExMGQ4NTI4ODNlZGFiNTp7fQ==").count() Out [9]: 175163446 Now you can see that we have something around 180 million records associated with this session_data. Question Are there any side effects regarding deletion of these empty sessions? I can not think of any problems occurring to any of our users. Any insights or clarifications would be appreciated. -
register a function inside another function to celery
def send_email_verification(user, site, email=None): some_variable someprocessing @celery_app.task(name="user.send") def send(): print(some_variable) send_mail(some_variable.some_email) send.delay() when I start celery -A proj worker -l info the user.send is not recognised in tasks. -
Searching on other website text which user entered
i am quite new in Django and i want create something like this: User will enter on my django website name of a football club, and then i will go to the other site to search it in their browser. For example user will enter text "Sheffield United" and i will paste this phrase to this link: https://www.transfermarkt.com/schnellsuche/ergebnis/schnellsuche?query=Sheffield+United&x=0&y=0 Then my app should enter that link and click on first score. Is that possible to implement it in Django? If yes, what are the steps? -
How can i select only class elements on my bootstrap list
I want user that to select only a elements from my class. class Player(models.Model): PLAYER_CHOICES = ( ('Adam','Adam'), ('John','John'), ('Tom','Tom'), ) title = models.CharField(max_length = 100, choices = PLAYER_CHOICES) Don't want to make a seperate list in my bootstrap <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">Adam</a> <a class="dropdown-item" href="#">Jhon</a> </div> </div> -
How to make favicon to be shown in web page?
All the static files appear except favicon whenever I refresh the page. I tried a lot made changes but didn't get the required result. index.html {% load static %} <link rel="shortcut icon" href="{% static 'images/W.png' %}" type="image/png" sizes="16x16"> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') urls.py urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) command prompt message "GET / HTTP/1.1" 200 20804 Folder structure -
Getting unable to load configuration from /home/.../... in Django project when trying to run external python script
I tried hosting a web app via Python Anywhere and the website hosted successfully but when I tried to run the external Python script as I did in the local project I couldn't get the output in the HTML page. This is my views.py def external(request): inp=request.GET['param'] out=run([sys.executable,'/home/.../.../file.py',inp],shell=False,stdout=PIPE) out=out.stdout out=str(out) out=out.strip('b') out=out.splitlines() st=" " out=st.join(out) out1=out.replace("\n"," ") out2=out1.replace("\r"," ") eval(out2) return render(request,'home.html',{'data':out2}) This is the external script that runs in the HTML page import xlrd import sys loc = ("xel.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) st1="%s is safe for now " % (sys.argv[1]) st2="%s is critical " % (sys.argv[1]) st3=sys.argv[1] s1=[] c1=[] for i in range(1,sheet.nrows): if int(sheet.cell_value(i, 5)) > 2698.54: s1.extend([sheet.cell_value(i,2),sheet.cell_value(i,5)-2698.54]) else: c1.extend([sheet.cell_value(i,2),2698.54-sheet.cell_value(i,5)]) for i in range(0,len(s1)): if(st3 == s1[i]): print(st1,"Gap to safe zone:",s1[i+1],"Ham") for i in range(0,len(c1)): if(st3 == c1[i]): print(st2,"Gap from safe zone:",-c1[i+1],"Ham") And this is the main HTML page where the output needs to be at <form action="/external/" method="GET" enctype="multipart/form-data"> {% csrf_token %} Choose district <select name="param" required> <option value=""></option> .... </select> {{data_external | safe}}<br><br> {{data | safe}} The option from this form is sent to the Python file where it runs and gives the output via PIPE. This is not coming after … -
Django inspectdb take account of camel casing
I have models that I am keeping track of with nodeJS knex. in the migration, I am using Camel casing for both table names and the column names. I expected the django inspectdb to take account of camelcasing and produce snake case result as the class fields; however, column logoImgName ends up translating to logoimgname where I would like it to be logo_img_name. Is it possible to let django know that the column names are in camel casing and it should be converted to snake case when running inspectdb? class Company(models.Model): name = models.CharField(unique=True, max_length=255) logoimgname = models.CharField(db_column='logoImgName', max_length=255, blank=True, null=True) # Field name made lowercase. type = models.CharField(max_length=255) createdat = models.DateTimeField(db_column='createdAt') # Field name made lowercase. updatedat = models.DateTimeField(db_column='updatedAt') # Field name made lowercase. class Meta: managed = False db_table = 'company' -
How to update memcached in Django Rest API
I have django memcached used in our project but problem is when i have change in database using rest api PUT method of API view but cache data not change instancally, after some time value should be reflected. Any one suggested how its possible?. I have only change in setting.py or cache applied on whole project. using below code refer: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware’, 'django.middleware.cache.FetchFromCacheMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" I have only used Memcached and one more question is Anyone Suggested, How to Memcached Status view and Memcached Data views? if Any UI form there then I will see to my cache data. Note : I have used Centos 7 . -
How to implement Pagination with dynamic HTML table data via AJAX?
I want to display incoming data from my database to a dynamic HTML table (via AJAX) that should include pagination. I have read about DataTables pagination but I am not sure how to implement it here. This is the code: JS code: $.ajax({ cache: false, url: {% url 'grab_records' %}, method: 'GET', datatype: 'json', success: function(data) { var htmlData = ''; var res = data[0]; if (res) { var count = res.data.length; for (i = 0; i < count; i++) { htmlData += '<tr>' +'<td id = "records"> '+res.data[i]+' </td>' +'</tr>'; } } else { htmlData += '<tr>' +'<td id = "records"> No data </td>' +'</tr>'; } $("#details").append(htmlData); }, }); HTML code: <table id="myTable"> <thead> <tr class="header"> <th> Employee Records </th> </tr> </thead> <tbody id='details'> </tbody> </table> How can I add pagination here? -
How to make favicon visible in web page?
Whenever I refresh the page, all the static files load except the favicon whose link is this. index.html {% load static %} <link rel="shortcut icon" href="{% static 'images/W.png' %}" type="image/png" sizes="16x16"> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') urls.py urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How to update graphene schema in Django dynamically
I have been inspired by this post (creating-dynamic-schema-on-runtime to build my graphene schema in django in a dynamic way, and as soon as the underlying data model changes i would like to trigger an update in this schema. Every time i restart the server it updates, so the build_dynamic_model_query() works fine. Right now it looks something like this, in the root schema.py file: class Query( users.schema.Query, build_dynamic_model_query(), graphene.ObjectType): debug = graphene.Field(DjangoDebug, name='__debug') schema = graphene.Schema(query=Query) How can i achieve that? -
Django docker user permissions
I recently published a site using Django and docker. The 'guide' used is: Quickstart: Compose and Django It says: If you are running Docker on Linux, the files django-admin created are owned by root. This happens because the container runs as the root user. Change the ownership of the new files. All fine, except when I upload files using Django-filebrowser, the newly uploaded files are saved as root, making them inaccessible on the website. How can I solve this? Setup: - Nginx (installed on host) - Container containing website, having a volume on host with media - Container with DB. -
django - api: to verify OTP which is the best way - (store in database OR hash + secret key OR encrpt + secret key) + send + recieve + verify
I am trying to create an api to check the OTP sent to an email. The client will pass an email. In response he will recieve the OTP related info. Then he will pass back it along with OTP he recieved in email. For that i found that there are few options: 1) Is to store the OTP in database and send a unique_id of the row in the api response and client will send back the unique_id with the OTP to verify the OTP 2) To HMAC (hash + secretkey) the OTP and send it in response and client will send back the HMAC with the OTP to verify the OTP 3) To encrpt + secret key the OTP and send it in response and client will send back the encrpt with the OTP to verify the OTP So which of the methods is most recommended. -
Django: How to send two pk when Update?
When I update moneylog which relation with moneybook, the error occur : NoReverseMatch at /moneylogs/update/8/ Reverse for 'delete' with arguments '('', 8)' not found. 1 pattern(s) tried: ['moneylogs/(?P[0-9]+)/delete/(?P[0-9]+)/$'] I guess this is because there is no moneybook.pk, but I can't find out how to deal with. could anyone kindly help me please? models.py class Moneylog(core_models.TimeStampedModel): moneybook = models.ForeignKey( moneybook_models.Moneybook, on_delete=models.CASCADE) pay_day = models.DateTimeField(default=NOW) payer = models.ForeignKey( tempfriend_models.Tempfriend, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( tempfriend_models.Tempfriend, related_name="dutch_payer", blank=True) price = models.IntegerField() category = models.CharField(max_length=10) memo = models.TextField() views.py class moneylog_update(UpdateView): model = moneylog_models.Moneylog form_class = forms.UpdateMoneylogForm template_name = "moneylogs/update.html" def form_valid(self, form): moneylog = form.save(commit=False) moneybook = moneybook_models.Moneybook.objects.get( pk=moneylog.moneybook.id) moneylog.save() form.save_m2m() return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk})) urls.py app_name = "moneylogs" urlpatterns = [ path("create/<int:pk>/", views.moneylog_create.as_view(), name="create"), path("update/<int:pk>/", views.moneylog_update.as_view(), name="update"), path("<int:moneybook_pk>/delete/<int:moneylog_pk>/", views.moneylog_delete, name="delete"), ] template(moneylog_Form_update.html) ... <button class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</button> <a href="{% url 'moneylogs:delete' moneybook.pk moneylog.pk %} " > <div class="px-2 py-1 rounded bg-red-500 text-white">삭제하기</div> </a> </form> -
Django, when changing data, he creates a new one, how to fix it? whatever he creates
views.py ''' def detail_edit(request, id): if request.user.username == 'admin': item = get_object_or_404(Buses, id=id) form = ItemForm(request.POST or None,instance=item) if request.method == 'POST': form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('index') return redirect('index') return render(request, 'buses/detail_edit.html', {'form': form, 'bus': item}) return redirect('index') ''' models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Buses(models.Model): company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) name = models.CharField(max_length=200) state_number = models.CharField(max_length=200) route = models.IntegerField() phone = models.IntegerField(blank=True) paid_until = models.IntegerField(blank=True) photo_person = models.ImageField(upload_to='photos/%Y/%m/%d/', default='avatar.jpg') photo_front = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_back = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_car_pass = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_license = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') photo_route = models.ImageField(upload_to='photos/%Y/%m/%d/', default='carcas.png') def __str__(self): return self.name urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('buses.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) detail_add.html {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <nav class="navbar navbar-expend-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'index' %}">ТрансМашХолдинг - ОШ</a> <a href="{% url 'detail' bus.id %}" class="btn btn-outline-success btn-mob"><i class="far fa-arrow-alt-circle-left"></i> Назад</a> <div class="text-white">Admin</div> <a href="{% url 'logout' %}" class="btn btn-outline-secondary btn-mob"><i class="fas fa-door-open"></i> Выйти</a> </nav> </div> </div> <form action="{% url 'detail_edit' bus.id %}" method="post" enctype="multipart/form-data"> {% … -
How to validate forms using django and how many ways to validate form using django
I tried many ways to validate forms using Django. but It cannot validate a Django form I see much documentation and many videos to implement validation in form. but it won't work. anybody can give the solution. 1. How many ways to handle form validation using Django? 2. which is the best way to handle form validation using Django? I tried this way to handle validation error. but it cannot work my code forms.py from django.core.validators import validate_slug,validate_email from django import forms from .validators import validatenames class validform(forms.Form): firstname = forms.CharField(max_length=10) class Meta: fields = ['firstname'] def clean_firstname(self): name = self.cleaned_data.get('firstname') name_req = 'hari' if not name_req in name: raise forms.ValidationError("Not a name") return name views.py from django.shortcuts import render from .forms import validform # Create your views here. def index(request): form = validform() return render(request,'index.html',{'form':form}) index.html <form> {{ form.as_p }} <input type="submit" value="submit"> </form> I tried another way to handle validation error. this also cannot work my code forms.py from django.core.validators import validate_slug,validate_email from django import forms from .validators import validatenames class validform(forms.Form): firstname = forms.CharField((validators=[validatenames])) class Meta: fields = ['firstname'] views.py from django.shortcuts import render from .forms import validform # Create your views here. def index(request): form = … -
Chrome v76 CORS problem, Amazon S3 bucket and Heroku-Django Web app
I have a django/wagtail application running on Heroku pulling a .epub file out of an Amazon S3 bucket. The following code and configuration works in IE, Firefox, and Samsung Internet. However it only works in Chrome's incognito mode: let book_url = "{{ book.get_url }}"; let book = ePub(book_url); let rendition = book.renderTo("area", {width: "90%", height: "700px", spread: "always"}); The error that I receive from Google Chrome's console is: Access to XMLHttpRequest at 'correct-link/to/.epub' from origin 'http://www.custom.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. That "book.get_url" points to an Amazon S3 bucket and so the other browsers use some CORs request (GET?). Here is my bucket configuration from AWS: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> As far as I understand there is some way to do this request either without CORS or, more likely, by making the CORS request run on a background page. Would that make the request work in Chrome? Could someone please explain how to do this and if that is correct? Also, note the ePub in the Javascript code is from the future press epub.js reader, the documentation is here. -
Django ALLOWED HOST does not work properly when using ECS, Docker, uWSGI
I made a server using ALB, ECS, Docker and python Django app. In docker, I run python+ Django using uWSGI. I added domain that mapped to ALB in django ALLOWED HOST and it worked fine. However a problem occured when I tried to log in django admin site. When I try to login, I get 5xx error. I checked cloud watch log and it says disallowed host. the host was container's address. so I make allow all hosts for temporary and tried, and admin login worked. This kinds of problem never happened when I used EC2 instance server. The differences between EC2 server and fargate is nginx. on EC2 server I use nginx, but in fargate docker I use only uwsgi. So, I want to know why django admin login needs to allow all hosts when using ECS fargate container and How can I log in django admin only allowing domain that mapped to load balancer. -
Icecast2 privte stream with django website
I have a django website i stream on my website with icecast 2 server with the link http://ip number:port number/mount but if any one use this link he can use my radio i want to make my radio work on my website only -
How to link template of html to start working in django
By running this code in normal HTML it runs with style also. But whenever I run it in django it runs and just show me a text. I applied ../static/css/animate.css, ../css/animate.css and css/animate.css but none of them are working. I made changes in settings.py by giving STATIC_ROOT but still showing me just text. views.py def index(request): return render(request, 'index.html'); main url urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html {% load static %} <!-- Animate.css --> <link rel="stylesheet" href="{% static '../static/css/animate.css' %}"> <!-- Icomoon Icon Fonts--> <link rel="stylesheet" href="{% static '../static/css/icomoon.css' %}"> <!-- Simple Line Icons --> <link rel="stylesheet" href="{% static '../static/css/simple-line-icons.css' %}"> <section id="fh5co-home" data-section="home" style="background-image: url(../static/images/W1.png);" data-stellar-background-ratio="0.5"> <div class="gradient"></div> <div class="container"> <div class="text-wrap"> <div class="text-inner"> <div class="row"> <div class="col-md-8 col-md-offset-2 text-center"> <h1 class="to-animate">Welcome in the World of White Hats</h1> <h2 class="to-animate">Your Problem with auto Solution</h2> </div> </div> </div> </div> </div> </section> Folder structure -
How to add a calculation in Django model?
I just want to be Per Amount to Paid Amount and result will be posted in balance automatic this is my admin.py @admin.register(StudentPaymentSchedules) class StudentPaymentSchedulesAdmin(admin.ModelAdmin): list_display = ('Fullname','Grade_Level','Payment_Schedule','Amount','Student_Payment_Date','Paid_Amount','Balance','Remarks',) ordering = ('pk','Students_Enrollment_Records__Education_Levels') search_fields = ('Students_Enrollment_Records__Student_Users__Firstname','Students_Enrollment_Records__Student_Users__Lastname',) list_filter = ('Students_Enrollment_Records__Education_Levels',) def Fullname(self, obj): return obj.Students_Enrollment_Records.Student_Users def Grade_Level(self, obj): return obj.Students_Enrollment_Records.Education_Levels actions = ["export_as_csv"] def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response I have this models.py class StudentPaymentSchedules(models.Model): Students_Enrollment_Records=models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Payment_Schedule =models.CharField(max_length=500,null=True,blank=True) Amount = models.FloatField(null=True,blank=True) Student_Payment_Date = models.DateField(null=True, blank=True) Paid_Amount = models.FloatField(null=True,blank=True) Balance = models.FloatField(null=True,blank=True) Remarks=models.TextField(max_length=500,null=True,blank=True) for example if the Amount is 1,950 and the Paid Amount is 1500 if the admin click the Save button it will cocompute. -
Django form is refreshing on its on
The form is refreshing on its on. whenever i click on a field to put data, it refreshes. It seems that all the fields are hyperlinked. <form action="" method="post"> {% csrf_token%} {{ form.as_p }} <input type="submit" value="Save"> <form> image of the form given below -
docker volume after upload to github?
I am using docker and created the postgres db within the container( not on my local machine). This is my docker-compose.yml file. I pushed all my code to github and deleted my code on my laptop. But when i clone it. The database was deleted and I had to re create database. Why was it deleted and what should i do so that the db exists. Thanks -
Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)\\/$']
I am trying to build an ecommerce website, but i am can proceed due to the error shown above. Thanks url.py file from django.urls import path from .**views import ItemDetailView, HomeView, checkout app_name = 'core' urlpatterns =[ path('', HomeView.as_view(), name='homepage'), path('checkout/', checkout, name='checkout'), path('product/<slug>/', ItemDetailView.as_view(), name='product') views.py file from django.shortcuts import render from .models import Item from django.views.generic import ListView, DetailView class HomeView(ListView): model = Item template_name = "home-page.html" class ItemDetailView(DetailView): model = Item template_name = "product-page.html" def checkout(request): return render(request, 'checkout-page.html') html template <a class="nav-link waves-effect" href="{% url 'core:product' %}" target="_blank">Products</a>