Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
im trying to run a url file for my website, but it i keep getting an error in powershell
the file im working in is called C:\users\Kalen\Desktop\django 1\mysite\blog\urls.py and the code inside the file is from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post urlpatterns = [url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date"[:25]), template_name=("blog/blog.html"))] when I go into my PowerShell and run python manage.py runserver I get an error saying the ] at the end of template_name is invalid syntax. so I remove it and then I get an error that says unexpected EOF while parsing. I looked up what the error means but I don't know how to fix it -
Reverse for 'detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['posts/(?P<slug>[-\\w]+)/$']
when i try to access the home page where it shows all the posts i get this error it tells me that the error in this line in my template: ="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> base.html: html template : {% for i in objects %} <div class="card" style="width: 18rem;"> <div class="card-body"> {% if i.cover %} <img src="{{ i.cover.url}}" class="img-fluid" > {% endif %} <h4 class="card-title">{{i.title}} <small style="font-size: small;"> {{i.timestamp | timesince}}</small></h4> <p class="card-text">{{i.content | linebreaks | truncatechars:120}}</p> <a href="{{i.get_absolute_url}}" class="btn btn-outline-dark">view</a> <a href="{{i.get_absolute_url}}edit" class="btn btn-outline-info">edit</a> </div> </div> <br> {% cycle '' '' '</td></tr><tr>' %} {%endfor%} urls.py: urlpatterns = [ url(r'^create/$', views.posts_create), url(r'^$', views.posts_list, name="list"), url(r'^(?P<slug>[-\w]+)/$', views.posts_detail, name="detail"), url(r'^(?P<ID>\d+)/edit/$', views.posts_update, name="update"), url(r'^(?P<ID>\d+)/delete/$', views.posts_delete), ] models.py: class Post (models.Model): title = models.CharField(max_length=200) content = models.TextField() slug = models.SlugField(unique=True, default='-') updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) cover = models.ImageField(null=True, blank=True, upload_to="media/") def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={'slug':self.slug}) views.py: def posts_detail(request, slug): object = get_object_or_404(Post,slug=slug) context = {'title': object.title, 'object': object} return render(request, 'post_details.html', context) -
Send PATCH request to Django Rest Framework
I am sending a PATCH request to my DRF server in Postman and it works perfect However when I do the same in Python I get: <Response [405]> http://127.0.0.1:8000/api/title/8174/ b'{"detail":"Method \\"PATCH\\" not allowed."}' Method Not Allowed My function that sends data: ss_token = os.getenv('SS_TOKEN') headers = { 'Authorization': 'Token ' + ss_token, } source = Source.objects.all().first() url = source.url + str(self.ss_id) + '/' response = requests.patch(source.url, headers=headers, data={'key':'value'}) print(response, url) print(response.content) print(response.reason) return True Do I have to send other headers to the API to make the PATCH work? -
Django make dataframe available in view but read it just ONCE
I'm trying to accomplish the following. I've a simple view, something like the following def view(request): df = pd.read_csv('t.csv') """ Some code to parse parameters from request """ y = parse_some_parameters(request) """ Do something with df. """ if request.method=="POST": x = do_something(df, y) return(JsonResponse(x)) With the current implementation, every call to the view involves reading the file. I want to avoid this. I would like to read the df once when I start the server and make it available in the view. I tried reading the df in the settings.py file but its not visible within the view. How would I accomplish this? -
What modules can I use to ping a website in Django from the database?
I have model that takes a URL and prints the URL in the front end. How would I ping that website using Django? Is there any package/module that I can use? I've seen django-ping but it hasn't been updated in 7 years. This is the model class Table(models.Model): domain = models.CharField(max_length=100) Once the ping returns. How would I be able to display the status on the template? Can anyone help with this? -
how to add onetoone model to django admin?
I added this code: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="profile_pics/", blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) what i am trying to do is running local host, but I am getting this error: <class 'accounts.admin.ProfileInline>: (admin.E202) fk_name 'user' is not a ForeignKey to 'auth.User'. Note: I thought it was the database problem because I had already some users in user model who don't have profile created. I did these following steps: 1. deleted db.sqlite3 file 2. deleted all files in the all migration folders except __init__.py 3. makemigrations and migrate But it didn't work. -
How to make email configuration dynamic in django project's settings.py file?
Here I am configuring my email setting like this in my project's settings.py file.But this is not dynamic.If i wanted to change my email_host from gmail to any other email host providers or if I wanted to change my email_host_user or password then there can be problem, so I want to make this configuration dynamic but how can I make this setting dynamic since it will be in project's settings.py but not in views.py . settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "my_email" EMAIL_HOST_PASSWORD = 'my_pass' EMAIL_PORT = '587' DEFAULT_FROM_EMAIL = "Hello World <my_email>" In my view subject, from_email, to = "Subject", settings.DEFAULT_FROM_EMAIL, user.email text_content = "content" site = get_current_site(request) html_content = render_to_string('send_email.html', {'user': user, 'site_domain': site,}) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
consumer: Cannot connect to amqp://dfmngfek:**@salamander.rmq.cloudamqp.com:5672/dfmngfek: [Errno 104] Connection reset by peer
My site runs with Python 3.5.6, Django 1.11.20, Celery 4.3.0, CloudAMQP (through Heroku), based on RabbitMQ. Celery returns the following error when the app is deployed to Heroku: consumer: Cannot connect to amqp://dfmngfek:*@salamander.rmq.cloudamqp.com:5672/dfmngfek: [Errno 104] Connection reset by peer I can't find where does this issue come from. Here are my settings: CELERY_BROKER_POOL_LIMIT = 1 CELERY_BROKER_CONNECTION_MAX_RETRIES = 100 settings_remote.py: CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] __ init.py __ : from .celery_tasks import app as celery_app __all__ = ['celery_app'] celery_tasks.py: import os from celery import Celery from celery.schedules import crontab from datetime import datetime, timedelta os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'terradiem.settings') from django.conf import settings app = Celery('terradiem') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.CELERYBEAT_SCHEDULE = \ { 'updateavcontribrating_task': { 'task': 'gautocomplete.tasks.updateavplacecontribratingregular', 'schedule': crontab(0, 0, day_of_month='2'), }, } gautocomplete/tasks.py : @app.task(bind=True) def updateavplacecontribratingregular(self): Etc... Error message : Sep 29 16:15:25 terradiem app/beat.1: -------------- celery@6e5f2660-eba2-4db3-9aba-5ac2b9547b70 v4.3.0 (rhubarb) Sep 29 16:15:25 terradiem app/beat.1: ---- **** ----- Sep 29 16:15:25 terradiem app/beat.1: --- * *** * -- Linux-4.4.0-1054-aws-x86_64-with-debian-buster-sid 2019-09-29 16:15:24 Sep 29 16:15:25 terradiem app/beat.1: -- * - **** --- Sep 29 16:15:25 terradiem app/beat.1: - ** ---------- [config] Sep 29 16:15:25 terradiem app/beat.1: - ** ---------- .> app: terradiem:0x7f56212a8550 Sep 29 16:15:25 terradiem app/beat.1: - ** ---------- .> transport: amqp://dfmngfek:**@salamander.rmq.cloudamqp.com:5672/dfmngfek Sep 29 … -
How to retrieve all the data from 3 different tables in one query?
I want to do the following but I don't understand how I will do it: For every class show me all the students in this class and for every student in this class show me all the statistics of the student. my models are: class Classes(models.Model): name = models.CharField(max_length=256) day_and_time= models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("classesapp:class_detail", kwargs={"pk": self.pk}) class Students(models.Model): name = models.CharField(max_length=256) student_class = models.ForeignKey( Classes, related_name = 'students', on_delete=models.SET_NULL, null=True ) def __str__(self): return self.name def get_absolute_url(self): return reverse("classesapp:student_detail", kwargs={"pk": self.pk}) class Statistics(models.Model): student= models.ForeignKey( Students, related_name='statistics', on_delete=models.CASCADE, null=True ) date = models.DateField(blank=True, null=True) dictation_score = models.FloatField() writing_score = models.FloatField() test_score = models.FloatField() grammar_score = models.FloatField() in_class_performance = models.FloatField() class Meta: ordering = ["-date"] def get_absolute_url(self): return reverse("classesapp:classes_list") I know that I have to overwrite the queryset and I tried select_relatad but still can't find a solution. Thank you in advance! -
Is it possible to send a list as you response to a html template in django? How would I reference it?
In django, I am passing a list of dictionaries using response.context_data to a template in my admin file. response.context_data['summary'] = list( qs .values('color_pref') .annotate(**metrics) .order_by('-total') ) I do this to display a table on my admin model page. <tbody> {% for row in summary %} <tr class="{% cycle 'row1' 'row2'}"> <td> {{ row.color_pref }} </td> <td> {{ row.total | intcomma }} </td> </tr> {% endfor %} </tbody> I was wondering if it would be possible to pass a list of items instead of a list of dictionaries and how I would reference them? Instead of response.context_data['table'] = [{'header': 'Color'}, {'header': 'Total Votes'}] I want to do something like response.context_data['table'] = ['Color', 'Total Votes'] However when I reference this in the html template, the headers appear as "['Color', 'Total Votes']" and not "Color", "Total Votes". I am referencing it like this. <tr> {% for row in table %} <th> <div class="text"> <a href="#">{{ row.header }}</a> </div> </th> {% endfor %} </tr> -
DJANGO - How can I pass a variable across function views and CBV?
Sorry for such a rookie question, but I'm stuck and I'm reaching out. I've used the FormWizard to capture subscription data from users. Works great. Now I want them to be able to update their subscription using the same FormWizard. I'm able to show their previous inputs, however, when it comes to actually knowing which record to update, that's where I'm having trouble. I am to get the id from the URL in the view function for that path, but I'm having trouble getting the id to other views. My code is below. I'm stuck on section 9.3. I'm not sure how to get the record id so it can update the correct record. If there is a better approach, feel free to suggest it and thanks in advance. urls.py path('subscription/update/<int:id>/', service_views.wizard_edit, name='wizard-edit'), views.py ## 9.1 Displaying the data in the form def wizard_edit(request, id): ## Collecting the data sub = Subscribers.objects.get(id=id) ## Displaying the data in the appropriate forms initial = { '0': {'industry_search':sub.industry}, '1': {'city':sub.city, 'kilometers':sub.kilometers, 'street_1':sub.street_1, 'street_2':sub.street_2}, '2': {'email':sub.email} } wiz = ContactWizardUpdate.as_view([ContactForm1, ContactForm2, ContactForm3], initial_dict=initial) return wiz(request) ## 9.2 FormWizard class ContactWizardUpdate(SessionWizardView): template_name = 'service/subscribe.html' form_list = [ContactForm1, ContactForm2, ContactForm3] def done(self, form_list, **kwargs): ## Function … -
Override SAVE model and add user to many to many relationship in django
From the code below, what is the best way to override the save method and add the current user to the list of member in the many to many relationship? I have tried a few alternatives but I still have to grasp how the save method works. models.py User = settings.AUTH_USER_MODEL class ChatGroup(models.Model): name = models.CharField(max_length=250, blank=False) host = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hosts') member = models.ManyToManyField(User, related_name='members') group_max_limit = models.SmallIntegerField(null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('core:group_detail', kwargs={'pk': self.pk }) class Meta: ordering = ['-id',] def __str__(self): return self.name def save(self, *args, **kwargs): # self.member = self.host self.member = self.member.set() super(ChatGroup, self).save(*args, **kwargs) Any help would be much appreciated. -
Reverse for 'order_page' with arguments '('',)' not found
i am trying to write a Django project in which i pass data ('cart') from detail.html in the app called 'cart' to another app ('order') and display it in its template. However i get the next error : Reverse for 'order_page' with arguments '('',)' not found. 1 pattern(s) tried: ['order\/order_page\/(?P[0-9]+)\/$'] The parts related to this task of my project are : detail.html <a href="{% url 'order:order_page' request.cart.id %}"> ORDER </a> order/urls.py urlpatterns = [ path('order_page/<int:cart>/', views.OrderPage, name='order_page'), ] order/views.py from django.shortcuts import render def OrderPage(request): return render(request,'order/orderr.html') Can you please help me? Ideally i want the data i pass from detail.html to be displayed in orderr.html -
problem starting nginx / which '}' is unexpected?
It is my first time trying to launch django-website through VPS. I am trying to follow this guide but encountered problem launching nginx. Then I am doing sudo service nginx start command I get following error: "Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details." So after this error I checked journalctl -xe and found out that error was encountered while starting nginx.service: "nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/skaiciuokle_web" and "nginx: configuration file /etc/nginx/nginx.conf test failed" So naturally I checked /etc/nginx/sites-enabled/skaiciuokle_web file for it content with intention to remove that cursed unexpected }, but this is that I found: server { server_name 141.136.44.187; access_log off; location /static/ { alias /opt/myenv/static/: } location / { proxy_pass http:/127.0.0.1:8001; proxy_set_header X-Forwarded_Host $server_name; proxy_set header X-Real_IP $remote_addr; add_header P3P 'CP="All DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } To my understanding there is no additional, not needed "}"... So which one } is unexpected and should be removed? Or error means something different and problem is not here? -
Chained dynamic drop down list
I have a model named Product with a 'category' field on it: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey('Category', on_delete=models.CASCADE) class Category(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') name = models.CharField(max_length=255) ...and I have made a ModelForm for creating products: class CreateProductForm(ModelForm): class Meta: model = Product fields = ( 'title', 'description', 'price', 'year', 'category', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset = Category.objects.filter(parent=None) Once you select a main category from the rendered category <select>, another <select> should appear to select a subcategory and so on until the innermost (most specific) category is selected. So far, I have only been able to populate the rendered category <select> with only main categories (whose parent is None), but now I'm stuck, and also unsure if that was the right move. How can I proceed? I reckon I'll have to use JavaScript but I'm not sure how to access the database from JavaScript, and if that's what I should do in the first place. -
How to use one view by two different users in django?
I have a custom user model as below: class CustomUser(AbstractUser): username = None email = EmailField(verbose_name='email address', max_length=255, unique=True, ) first_name = CharField(verbose_name='First Name', max_length=30, null=True, ) middle_name = CharField(verbose_name='Middle Name', max_length=30, null=True, blank=True, ) last_name = CharField(verbose_name='Last Name', max_length=30, null=True, ) phone_number = CharField(verbose_name='Phone Number', max_length=30, null=True, ) is_partner = BooleanField(default=False, ) is_student = BooleanField(default=False, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email As shown above, a user can be a student or can be a partner, who will be in charge of a few students and have access to their assets. The partner model is as below: class Partner(Model): user = OneToOneField(CustomUser, on_delete=CASCADE) partner_name = CharField(max_length=100, ) The student model is as below: class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE) student_name = CharField(max_length=100, ) partner = ForeignKey(Partner, on_delete=SET_NULL, null=True) As shown, in the Student model, partner can be null. The reason is that a student can either directly enroll in the system without having a partner or he/she can be enrolled by a partner. A student might even specify a partner that is optional when he/she is enrolling. I have a student view and url pattern: path('student_profile/', student_profile, name='student_profile') def student_profile(request): user = … -
Django: detecting request domain in urls.py
I have a Django app that will serve diferent websites. Each one will have it´s own domain Each one will have it´s own sub app with templates and views They all share the same backend, models and data My aproach As I already have the database with the segmentation info I need to show the desired products in each site and I will have different views for each sub app, I don´t need to add another field in the models. I think that it would be easier just to detect the request domain in my main app urls.py and rout home url to the desired sub app. Something like: # urls.py if "name1" in request.domain: urlpatterns += [path('', include('app1.urls'))] if "name2" in request.domain: urlpatterns += [path('', include('app2.urls'))] else: urlpatterns += [path('', include('app3.urls'))] Maybe I should make a middleware and set a global variable I can access in urls.py? Can I use this kind of if statements in urls.py? Django sites I checked the Django Sites Framework, but if I understand ir well, it´s more focused in segmenting the database in the models, not the templates and views. In any case I don´t really catch how the Sites framework detects the … -
Django unclear 404
I have a question, after converting my view (included below) from function based view to class based view I keep getting an error (page not found - 404) after trying to submit a comment on an article. Why is that ? the view now : class CommentCreateView(RedirectView): model = Comment form_class = CommentForm template_name = 'news/add_comment_to_article.html' def form_valid(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs.get('pk')) comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk})) the same view how it used to be, function based (working) : def add_comment_to_article(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) comment form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) -
Django celery run multiple woerks and queues
i try to configure three queues/workers for celery in django. settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_QUEUES = ( Queue('manually_task', Exchange('manually_task'), routing_key='manually_task'), Queue('periodically_task', Exchange('periodically_task'), routing_key='periodically_task'), Queue('firsttime_task', Exchange('firsttime_task'), routing_key='firsttime_task'), ) CELERY_ROUTES = { 'api.tasks.manually_task': { 'queue': 'manually_task', 'routing_key': 'manually_task', }, 'api.tasks.periodically_task': { 'queue': 'periodically_task', 'routing_key': 'periodically_task', }, 'api.tasks.firsttime_task': { 'queue': 'firsttime_task', 'routing_key': 'firsttime_task', }, } I have three tasks and every task should be have their own queue/worker. My tasks look like this: @shared_task def manually_task(website_id): print("manually_task"); website = Website.objects.get(pk=website_id) x = Proxy(website, "49152") x.startproxy() x = None @periodic_task(run_every=(crontab(hour=19, minute=15)), ignore_result=True) def periodically_task(): websites = Website.objects.all() for website in websites: x = Proxy(website, "49153") x.startproxy() x = None @shared_task def firsttime_task(website_id): website = Website.objects.get(pk=website_id) x = Proxy(website, "49154") x.startproxy() x = None Now for the first trial i start only one worker: celery -A django-proj worker -Q manually_task -n manually_task My problem is that the task not execute apparently, "manually_task" not printed. Why its not working? -
logging user in user from ios application with twitter account
I'm creating a django project that intergrate with ios devices through restframe work and I managed to save tokens in the keychain and create posts and get them. so I started my django project to be able to login with twitter accounts using allauth. And from browsers I made it to logging in users. But since it doesn't create a password when loging in user I have no idea how to make them login through swift application and create a token for django. I've been searching for information but I wasn't able to find a solution. Could you help me how it works? -
Django-channels:chatSocket.onmessage or chatSocket.send does not work
I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view: <!-- chat/templates/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <button id="chat-message-submit" type="submit" value="Send">Send</button> </body>z <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { console.log("got to onmessage"); var data = JSON.parse(e.data); var message = data['message']; document.getElementById('chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.getElementById('chat-message-submit').click(); } }; document.getElementById('chat-message-submit').onclick = function(e) { var messageInputDom = document.getElementById('chat-message-input'); var message = messageInputDom.value; console.log("got message : " + message); chatSocket.send(JSON.stringify({ 'message': message })); console.log("This was done?"); messageInputDom.value = ''; }; </script> </html> Here is my consumer view : from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def … -
django KeyError at (request)
I am making a program and I have a small problem. I'm currently designing a web page with python django and requests, and I have an Error which mentions That Key Error at 'main' and here are my codes form: from django.forms import ModelForm, TextInput from .models import City class CityForm(ModelForm): class Meta: model = City fields = ['name'] widgets = {'name' : TextInput(attrs={'class':'input', 'placeholder' :'City Name'})} models: from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views: import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=212c1f52ec8c8bbf34933937a6885114' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temprature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weather_data/weather.html', context) I tried everything I could, and it didn't make it I erased the 'main' part and any other things... finally nothing worked. I have an error message like this: Environment: Request Method: GET Request URL: http://codefair-tripple-wrbdv.run.goorm.io/ Django Version: 2.1 Python Version: … -
How to concept a web application (dashboard) made of Django in terms of backend structure
My goal is to build a python/django based dashboard related to soccer where the user can select a soccer team of his choice in the sidebar and then gets all related data displayed in the dashboard in return. I attached the html frontend so you can get a brief feeling of how it will look like. As for the backend, I am not quiet sure what might be a good or even the best solution structurewise. I hope to get some input/opinions from the community to derive a good approach for my further steps. I inserted numbers to the questions for the sake of clarity ;). Templates Since the web application will contain one main site (= the dashboard) I prefer to wortk with a single template (index.html, apart from "about" and "blog" sites). [1.1] Is there any good reason to maybe split the sidebar and the dashboard part into two templates? [1.2] Or even to create a single template for each "part" of the dashboard (Like one template for each single information container)? Views As I understand from different tutorials/documentations you usually just use one views.py file in a web application. I will grab the soccer data from an … -
django model many to one individual id
i tried to make a ID that depends on parent's Field. like this, My Intention BOOK my new friend is so fun! Some book own diaries! DOCUMENT Parent : my new friend is so fun! book cover table of content content blablaah. Parent: Some book Some Book Cover table of content content ~~ Unintended consequences(problem) BOOK my new friend is so fun! Some book own diaries! DOCUMENT Parent : my new friend is so fun! 1. book cover 2. table of content 3. content blablaah. Parent: Some book 4. Some Book Cover 5. table of content 6. content ~~ class Book(models.Model): publisher = models.ForeignKey(User, on_delete=models.CASCADE) book_id = models.AutoField(primary_key=True) book_name = models.CharField(max_length = 30) def __str__(self): return self.book_name class Document(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) document_id = models.AutoField(primary_key=True) title = models.CharField(max_length = 50) def __str__(self): return self.title for ordering this document i have to make some field instead of pk field. anyway, i have to make a edit page, and user can change their order in edit page. that document_id is overall model. how can i make it? -
django-reversion conflict with models clean method
i use django-reversion to controll changes of my models but i have a problem with the models clean method. For example my model looks like this: class Document(models.Model): name = models.CharField(max_length=255, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) template = models.ForeignKey(Template, on_delete=models.CASCADE) def clean(self): if self.template.only_one and (Document.objects.filter(client=self.client, template=self.template).count() > 0): raise ValidationError('Test') I register this model in the admin.py: @admin.register(Document) class DocumentReversion(VersionAdmin): pass Now i create a record for Document in the admin section referencing to a template where the field only_one is True. If i delete this record and retrieve it, a ValidationError fires. Why? Because i have deleted the only available record. Very curious...