Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic complex queries with Django
I've these models: class Product(models.Model): description = models.TextField() class Client_Type(models.Model): description = models.TextField() product = models.ManyToMany(Product) class Client(models.Model): description = models.TextField() type = models.ForeignKey(Client_Type) class Order(models.Model): client = models.ForeignKey(Client) date = models.DateTimeField() class Detailed_Order(models.Model): order = models.ForeignKey(Order) product = models.ForeignKey(Product) weight = models.FloatField() Note that I have a many-to-many relationship between Client_Type and Product. I do this because I need to show only a limited list of products to a client, depending of his "type". So when the client orders a product, he will only see the ones selected for his type. Ok, I have no problem doing this. The problem comes with the queries. I need to make a daily report that shows the total amount of Kg buyed by all clients of the respective Client_Type, but only displaying the products selected in the "product" field of Client_Type. Better explained with the following: Client Type: VIP | Client1 | Date | Sum_Product1 (kg) | Sum_Product2 (kg) | Sum_Product3 (kg) | Total_Sum_Client1 (kg) | | Client2 | Date | Sum_Product1 (kg) | Sum_Product2 (kg) | Sum_Product3 (kg) | Total_Sum_Client2 (kg) | The desired result may be getted by the following query, but with the detail that the products displayed in … -
Django doesn't redirect to same or other page after successful HTTP 302 and 200
I've been scratching my head all day long but I don't seem to get it working. My redirects work just fine everywhere else in the app, but don't work when I'm using the forms.py with ModelForm class. So what happens when I hit 'Save' on the form is Django actually does the save successfully and then reports couple of lines in the Debug console as follows, but the browser just stays stalled on the same page without even attempting to go to another page (I've tried redirecting to various views with and without reverse, using HttpResponseRedirect, using redirect, using render_to_response, etc. - just about anything I could find, but Django behaves the same way all the time (see below). It's not a browser caching issue since I've tried redirecting to even the external pages such as google for example, and every time all I'm getting is this: [05/Dec/2017 17:00:41] "GET /music/release/test/edit HTTP/1.1" 200 3310 [05/Dec/2017 17:00:46] "POST /music/release/test/edit HTTP/1.1" 302 0 [05/Dec/2017 17:00:46] "GET /music/releases/ HTTP/1.1" 200 13616 Can anyone please help as I'm really stuck, since all the other redirects are working just fine, it's just the form one that fails for whatever reason. Thx in advance! Here's the … -
Session Hijacking in Django 1.7.7 and python3
I have developed a small application for submitting some data to database server(Oracle 11g). When we are reviewing security of this small application, we observed as follows: 1. We have deployed django with https and all secure configurations like Secure Cookie and Secure Session, No Cache, etc. 2. Using BURP tool for this sample review 3. We have created two different user in this system say Normal User and Admin User 4. Opened 2 browsers(Mozilla and IE 11), On mozilla we login with Admin user and captured session id using burp tool. 5. On second browser we login with Normal user and replaced session id Normal User with Admin User. 6. whoila......On second browser, I got Admin user access by just changing the session id I have used default session backend for this application. I would like to know whether this is flaw in django and how to resolve this issue.. Thanks in advance -
Django Caching on front-end
I was working with 2 applications that are within a DJango project: "customer" and "vendors". Each application has a HTML file named "testindex.html". Whenever I typed: http://myhost/customer/basic_info the correct page would show up If I typed http://myhost/vendors/basic_info the page from http://myhost/customer/basic_info would show up I found out that it was due to caching (since both applications use "testindex.html"). So again, "testindex.html" is caching. How can one get around this problem? TIA Details are listed below. I have the following views defined: urls.py for the project urlpatterns = [ ... snip ... url(r'^customer/', include('libmstr.customer.urls')), url(r'^vendors/', include('libmstr.vendors.urls')), ] views.py for customer from django.shortcuts import render def basic_info(request): return render(request, 'testindex.html', {}) views.py for vendors from django.shortcuts import render def basic_info(request): return render(request, 'testindex.html', {}) urls.py for customers from django.conf.urls import url from . import views # list of templates app_name = 'customer' urlpatterns = [ url(r'^basic_info/$', views.basic_info, name='basic_info'), ] urls.py for vendors from django.conf.urls import url from . import views # list of templates app_name = 'vendors' urlpatterns = [ url(r'^basic_info/$', views.basic_info, name='basic_info'), ] -
Django Admin - Cannot Login with Superuser
There are a few questions on this topic, but none of them solved my challenge. I cannot login to Django Admin with a correct username and password. settings.py: import os from django.core.exceptions import ImproperlyConfigured BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_env_variable(variable_name): try: return os.environ[variable_name] except KeyError: error_msg = 'Set the {} environment variable'.format(variable_name) raise ImproperlyConfigured(error_msg) SECRET_KEY = get_env_variable('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['XXXXXXXX'] INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'alerts.apps.AlertsConfig', 'widget_tweaks', ] SESSION_COOKIE_SECURE = False SESSION_EXPIRE_AT_BROWSER_CLOSE = True 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', ] ROOT_URLCONF = 'myProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'XXXXXXXXXXx', 'HOST': get_env_variable('DATABASE_HOST'), 'NAME': get_env_variable('DATABASE_NAME'), 'USER': get_env_variable('DATABASE_USERNAME'), 'PASSWORD': get_env_variable('DATABASE_PASSWORD'), 'OPTIONS': { 'driver': 'XXXXXXXXXXX' }, }, } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False DATE_FORMAT = "m/d/Y" USE_TZ = True STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, 'myProject', 'static')) STATIC_URL = … -
Django call fabric file and restart supervisor
I'm doing update system with fabfile and django admin. All is good to time when script should restart with supervisorctl then I got info: INFO - worker - Shutdown signal received while busy, waiting for loop termination In django admin is button which execute this function: def download(self): _fab=settings.FABFILE_PATH os.system("fab -f %s/fabfile.py update"%(_fab)) and then is execute fabfile.py: def update(): local("git pull") local("python3 manage.py migrate") local("supervisorctl restart hsb_script") What's more I added timeout for response: 1000 (default was 300) Why supervisorctl return error and stop script?. Script in shell work good. -
Import multiple Python scripts based on different virtualenvs with different versions of Django
I have a main script which has to perform some operations importing two old python scripts. Script 1 is based on Django 1.4, script 2 is based on Django 1.7. Main #!/usr/bin/python import script_1 import script_2 Script_1 # ... # activate venv activate_env=os.path.expanduser("~/.foo/django1.4/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) # Set up the Django Enviroment from django.core.management import setup_environ import settings setup_environ(settings) Script_2 # ... # activate venv activate_env=os.path.expanduser("~/.foo/django1.7/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) # Set up the Django Enviroment import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clinicalManager.settings") django.setup() In the way above, the second virtualenv is not loaded. Is there a way to deal with multiple virtualenvs when importing? -
$.post("{% url 'waypoints-save' %} csrf token error Django 1.11
I am using django 1.11 and writing a template in which i defined a code as following $('#saveWaypoints').click(function () { var waypointStrings = []; for (id in waypointByID) { waypoint = waypointByID[id]; waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat); }; $.post("{% url 'waypoints-save' %}", { waypointsPayload: waypointStrings.join('\n') }, function (data) { if (data.isOk) { $('#saveWaypoints').attr('disabled', 'disabled'); } else { alert(data.message); } }); }); activateWaypoints(); }); but it is showing error as following Forbidden (CSRF token missing or incorrect.): /save [05/Dec/2017 16:02:29] "POST /save HTTP/1.1" 403 2502 it is calling the saveWaypoints by following code : <input id=saveWaypoints type=button value='Save your Location' disabled=disabled> my urls.py is from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from waypoints.views import main_page, logout_page, register_page, save urlpatterns = [ url(r'^$', main_page), #url(r'^user/(\w+)/$', user_page), url(r'^save$', save, name='waypoints-save'), url(r'^register/$', register_page), url(r'^login/$', auth_views.login), url(r'^logout/$', logout_page), ] -
How to save an object to be re-used in Django Rest Framework Serializer Method Fields?
The situation is as follows: 2 fields in my serializer uses the Serializer Method Field function to get their respective content. In each of these fields, I am calling the same, exact function to generate the content. Kinda like this: class ProductSerializer(serializers.ModelSerializer): field_1 = serializers.SerializerMethodField() def get_field_1(self, obj): content = generate_content(obj) return content.field_1 field_2 = serializers.SerializerMethodField() def get_field_2(self, obj): content = generate_content(obj) return content.field_2 As you can see, both the methods is calling the same function, with the same argument and therefore getting the exact same result. The generate_content function is very large, so I feel it would be best if I could save the content once, and use that to generate the two fields. How can I pull this off? Thanks! -
Django endless pagination appears to shows double entries
I use django endless pagination to load entries into a webpage. It appears that the same entry is loaded multiple times. To my understanding, that's not supposed to happen. My views.py def results(request): ajax = request.GET.get('ajax', False) if not ajax: materials = SubstanceCategory.objects.filter(material=1) return render(request, 'results.html', {'materials': materials}) @page_template('results/entry_index_page.html') # just add this decorator def results_material( request, template='results/entry_index.html', extra_context=None): material = request.GET.get('material',None) context = { 'entries': Photo.objects.filter( isPainting=1, substance_exists_labels__substance__name=material, substance_exists_labels__exists=True). \ annotate( C=Count('substance_exists_labels')). \ order_by('-C'), 'material':material } if extra_context is not None: context.update(extra_context) return render_to_response( 'results/entry_index.html', context, context_instance=RequestContext(request)) When called,results makes a list of available materials, and sends this to the webpage. The (related) html is shown here: <div id="holder"> {% for c in materials %} <div id="{{c.name}}" onclick="get_materials(this.id)"> <p> {{c.name}}</p> </div> {% endfor %} </div> <div > <div id="refreshed_later"> </div> </div> This looks like this. Once a material is clicked, the following function is called. function get_materials(material) { data = { 'material':material }; $.ajax({ method: "GET", url: "https://annotatie01.io.tudelft.nl/results_material/", data:data, success: function(response) { data_holder = response; $('#refreshed_later').html(data_holder); } }) } Trough results_material this loaded the entry_index.html, which currently only contains {% include page_template %} which leads to the page_template which contains, which is appended to #refreshed_later, as per the success … -
Unable to fetch data by checking if one list is equal to other list in django
I am new to django and i am trying to fetch records from the table UserBookmark where tag is equal to category. My code is as follows: views.py: def home(request): category=Category.objects.values_list('category',flat = True).filter(user=request.user.pk) category = list(category) print category bookmarks = UserBookmark.objects.filter(tag__name__in = category) print bookmarks return render(request,'home.html',{'bookmarks':bookmarks}) models.py: class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) def __str__(self): return '%s %s'%(self.user,self.category) class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) But when i print bookmarks in views.py , i get an empty set.I tried printing category as well , it gives : u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"] And when i try this in shell: UserBookmark.objects.filter(tag__name__in = [u'Data Science', u'Python', u'Android', u'Data Analytics']) I do get a resultset https://github.com/shreyag12?tab=stars>, https://github.com/swapnil?tab=stars>, https://github.com/retme7/My-Slides>, https://github.com/retme7/My-Slides>, https://github.com/retme7/My-Slides>, https://github.com/sunny2krGupta/Bigquery-series>, https://github.com/ctfs/write-ups-2017>]> Can someone guide me in this? -
Django REST Authentication with VUEJS and Axios
I am trying to capture and later send a token from a Django Rest backend with a VUEJS and Axios single page application. Storing the token is working here: methods: { login () { Axios.post('/token-auth/', { username: this.credentials.username, password: this.credentials.password }).then(response => { this.$store.state.token = response.data.token; console.log(response) this.$router.push({name: "Main"}) }).catch(error => { console.log("error logging in") console.log(error) }) this.dialog=false } } When I try to send the token with the JSON request, I am receiving a 403 Forbidden error: methods: { fetchCompaniesList() { Axios.get('companies/', { headers: {Authorization: 'Token '+ this.$store.state.token}} ) .then((response) => { this.items = response.data; console.log(this.items) }) .catch(error => { console.log(this.$store.state.token) console.log(error) }); Here is the Django View I am trying to access: class CompaniesViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Companies.objects.all().order_by('name') serializer_class = CompaniesSerializer And the settings.py file: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ], I also tried setting this in the main.js file (which looks like a better method), however still receive a 403 errror. Axios.defaults.headers.common['Authorization'] = 'Token ' + store.state.token; Please let me know where I am going wrong. Thank you -
Django signals creates for the same model
I am trying to make a signal that creates a Client object or Director object depending on the type of the CustomUser: class CustomUser(AbstractEmailUser): TYPE = ( (0, 'Client'), (1, 'Director'), type = models.PositiveSmallIntegerField(default=0, choices=TYPE) class Client(models.Model): user = models.OneToOneField(CustomUser) class Director(models.Model): user = models.OneToOneField(CustomUser) def post_save_data(sender, instance, created, **kwargs): if created and CustomUser.objects.get(email=instance.email).type == 0: Client.objects.create(user=instance) elif created and CustomUser.objects.get(email=instance.email).type == 1: Director.objects.create(user=instance) post_save.connect(post_save_data, sender=CustomUser) Whatever i do it always creates object for Client, even if i choose type 1. -
nginx - Getting bad gateway for running flask app with nginx,systemd,gunicorn
Here i am getting bad gateway error for running flask app on nginx using systemdand gunicorn. microblog.conf file: server { listen 8086; server_name 0.0.0.0; client_max_body_size 4G; error_log /var/log/nginx/nginx_error.log warn; location / { include proxy_params; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/rizwan/Desktop/flask-example/flask-blog-poc/microblog.sock; } } systemd service file microblog.service : [Unit] Description=Micrblog Platform using gunicorn After=network.target [Service] User=root Group=root WorkingDirectory=/home/rizwan/Desktop/flask-example/flask-blog-poc Environment="PATH=/home/rizwan/.virtualenvs/flask-blog-env/bin" ExecStart= /home/rizwan/.virtualenvs/flask-blog-env/bin/gunicorn --workers 3 --bind unix:microblog.sock -m 007 app:app [Install] WantedBy=multi-user.target /var/log/nginx/nginx_error.log file: 2017/12/05 20:33:05 [crit] 32343#32343: *1 connect() to unix:/home/rizwan/Desktop/flask-example/flask-blog-poc/microblog.sock failed (13: Permission denied) while connecting to upstream, client: 127.0.0.1, server: 0.0.0.0, request: "GET /favicon.ico HTTP/1.1", upstream: "http://unix:/home/rizwan/Desktop/flask-example/flask-blog-poc/microblog.sock:/favicon.ico", host: "0.0.0.0:8086", referrer: "http://0.0.0.0:8086/" then i gave all permision to all user to my directory also changes permission to sockfile then also no luck? -
Django / Python dict values return each letter as item
I've got a problem which I just can't figure out. I've got a dictionary which I get from choices of a django form: forms.py class testForm(forms.Form): TEST_CHOICES = ( ("1", "One"), ("2", "Two"), ("3", "Three"), ) test_choice_field = forms.MultipleChoiceField(choices=TEST_CHOICES, widget=forms.CheckboxSelectMultiple) In my views.py I iterate through that dict of choices and try to return those choices in a string like this: "One / Two / Three" def test_func(request): if request.method == 'POST': form = testForm(request.POST) if form.is_valid(): test_choice_field = form.cleaned_data["test_choice_field"] empty_string = "" for numbers in test_choice_field: empty_string += dict(form.fields['test_choice_field'].choices)[numbers] subject = "[{}] is the Number you are looking for.".format(empty_string) What I wish for is that my "subject" holds the string "One / Two is the Number you are looking for", depending on which checkbox the user has checked. So if he/she picks all three checkboxes he get: "One / Two / Three is the Number you are looking for" and if it's only one "Two is the Number you are looking for" etc Now I simply just wanted to do a " / ".join(empty_string), but ended up getting this "O/n/e/T/w/o is the...." What am I doing wrong? And please don't remove the " / ".join(), I know I could … -
Django ORM Get users not assigned to the Team
models.py from django.db import models class UserGroup(models.Model): members = models.ManyToManyField(User, related_name='members', through='UserGroupMember') class UserGroupMember(models.Model): user = models.ForeignKey(User) usergroup = models.ForeignKey(UserGroup) class Cohort(models.Model): user_groups = models.ManyToManyField(UserGroup) class Team(models.Model): cohort = models.ForeignKey(Cohort) members = models.ManyToManyField(User, related_name='team_members', through='TeamMembers', blank=True) class TeamMembers(models.Model): team = models.ForeignKey(Team) user = models.ForeignKey(User) I need to write the query to get the users for a given cohort that are not assigned to any team. Single user can be part of only one team within a cohort. I tried this: User.objects.filter( members__cohort=cohort ).filter( team_members__isnull=True ) but that does not give me the user if he is part of the team in another cohort. I am using Python 2.7.13 and Django 1.9.8. Thanks. -
DJango 2, reverse URL,
The new DJango 2 update broke my way of reversing url and printing it to the template. Using regular expression, it would work fine but when using the new simplified way, it returns an error. NoReverseMatch at /blog/archive/ Reverse for 'article' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['blog/article/<int:id>/$'] Here is what I use to print the url, <h3 class="item-title"><a href="{% url 'blog:article' id=article.id %}">{{ article.title }}</a></h3> Here is the url pattern, url(r'^blog/article/<int:id>/$', views.article, name='article'), and here is the article function, def article(request, id): try: article = Article.objects.get(id=id) except ObjectDoesNotExist: article = None context = { 'article': article, 'error': None, } if not article: context['error'] = 'Oops! It seems that the article you requested does not exist!' return render(request, 'blog/article.html', context) I haven't found a solution to this yet. Hopefully this post will help others. -
How do i use Django groups and permissions using content type
I know about the login and authentication procedures but I wanted to know how to implement user groups with permissions with content type model? I searched the permission documents and content type documents but it was a little confusing for me. -
Django model with more than 255 fileds
Hi I have a Django Model with more than 255 fields, but I´m facing the "more than 255 arguments" SyntaxError when I want to save a new object of the model. I´ve been looking for a workaround and in this question (Pass more than 255 arguments to a function) the answer suggests to use a list for the arguments, but I can not use this approach since the function is directly the constructor of the Model. I would appreciate any idea on how to workaround this situation. Thanks in advance! -
Circular import error after enabling i18n
After enabling i18n in my project, circular import errors started to appear, LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ] USE_I18N = True on USE_I18N = False everything works fine. Django 1.16.11 DjangoCMS 3.2.5 At first started to fixing imports, but there is too many files... Any ideas? -
My custom django-admin command won't call celery task
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try. from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print "starting task" my_celery_task.delay() print "task has been sent" The output I receive when calling the command is: starting task I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view. -
Django + ajax dynamic table content rotation
This is the second question in the row about my Django project. The code I use here is partly copied from this question:Stack Overflow What I aim to achieve is a dynamic table, that loops through objects in a list. Let's say I have 21 records. The table first displays records of 1 to 10, on the displaykala.html table. Then it replaces only the table content with records of 11 to 20(with AJAX, without page refresh. The new contents come from get_more_tables_kala.html, and those table rows coming from there, are appended to the displaykala.html table). At no point should the table be empty (UNLESS there is simply no objects to display). Basicly it always displays first ten records(even if there is only one). Then the code increments the startindex and endindex of the rows, and checks if there is records between those. If there is more than 10 records, it will empty the table and instantly load up the next records (as long as there is even 1 record). Else, the program should wait X amount of seconds, until checking again. The code has been going through various experimentations, I'm sorry for any dumb coding. I'm still learning Django and … -
Python - Compare birthdate
I have 2 variables which are 2 birthdates. I want to compare both for displaying a message telling 'Hey it seems you have almost the same age !" try : his_birthdate = player.profile.birthdate my_birthdate = request.user.profile.birthdate except: pass Well... I think if both persons are maximum 3 years of difference, we can considere that they have almost the same age. So I can do many conditions like this if you know what I mean : try : his_birthdate = player.profile.birthdate my_birthdate = request.user.profile.birthdate if his_birthdate > my_birthdate + 3: .... if his_birthdate > my_birthdate - 3: .... except: pass But I think there is a better solution ? Thanks for your help ! -
Django How can i split string using template tag
Hello I want to know that how can I split string of dictionary values This is my crawler which is returns dictionary data looks like data = { {0 'http://..., product name, product price'} {1 'http://...2, product name2, product price2'} n. {n 'http://...2, product name2, product price n'} } I want to split these data by comma like, for value in data.values(): href, product_name, product_price = str(value).split(",") in Django This is my crawler.py import requests from urllib import parse from bs4 import BeautifulSoup def spider(item_name): url_item_name = parse.quote(item_name.encode('euc-kr')) url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name resp = requests.get(url) resp.raise_for_status() resp.encoding='euc-kr' plain_text = resp.text soup = BeautifulSoup(plain_text, 'lxml') mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]}) #for link in soup.select('div.list_info p.info_tit a') : data = {} count = -1; for link in mytag: if(link.find('a')): count+=1 href = link.find('a').get('href') product_name = link.find('a').string data[count] = str(href) + ", " + str(product_name) else: product_price = link.string if(product_price): data[count] = data[count] +", " + str(product_price) for value in data.values(): print(value) resp.close() return data and this is my views def post_shop_list(request): posts = spider("product name") return render(request, 'blog/post_list.html',{'posts' : posts}) and this is my post_list.html {% for key, value in posts.items %} <div> <td>{{key}}</td> <p>product name :{{value}}</p> <h1><a href=href> </a></h1> … -
Print out a list of items with Django
I'm developing a Django project and i'm trying to solve an issue. My main scope is getting a JSON file through a url and print out the data into a table(HTML). To be more clearly, i got an Object like referred below and every record i would like to printed into my table. { "myData": [{ "name": "John", "surname": "Williams", "birthday": "05/12/1997", }, { "name": "John", "surname": "Williams", "birthday": "05/12/1997", },]} <table class="table table-striped table-hover table-bordered"> <thead class="thead-dark"> <tr> <th>First Name</th> <th>Last Name</th> <th>Birth Day</th> </tr> </thead> <tbody> {% for myData in range(20) %} <tr> <td> {{ myData.name }} </td> <td> {{ myData.surname }} </td> <td> {{ myData.birthday }} </td> </tr> {% endfor %} </tbody> </table> I find it as a very common implementation but still i can't find a solution. Also when i'm trying to run the code below inside my views.py file everything works great but If i'm trying to send data into an .html file i got multiple errors. for i in range(5): print ada[i] The first one when i wrote {% for x in range(20) %} I got this error : Could not parse the remainder: '(20)' from 'range(20)' Then I'm trying to pass range(20) as …