Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set initial value of a field using foreign field of a model in django?
I wish to set initial value in profile form. Profile model has a OneToOne relation with User model. I get the following error when I set initial field in init method, 'ForwardOneToOneDescriptor' object has no attribute 'email' Traceback File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py" in get 190. return super().get(request, *args, **kwargs) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py" in get 133. return self.render_to_response(self.get_context_data()) File "/home/drogon/Crowdsocial_project/users/views.py" in get_context_data 90. context = super(ProfileSettingsView, self).get_context_data(**kwargs) File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py" in get_context_data 66. kwargs['form'] = self.get_form() File "/home/drogon/Crowdsocial_project/venv_ubuntu/lib/python3.6/site-packages/django/views/generic/edit.py" in get_form 33. return form_class(**self.get_form_kwargs()) File "/home/drogon/Crowdsocial_project/users/forms.py" in init 144. self.initial['profile_email'] = Profile.user.email Exception Type: AttributeError at /users/12/profile/settings Exception Value: 'ForwardOneToOneDescriptor' object has no attribute 'email' Profile Model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=30, null=True, blank=True) Profile Form class ProfileSettingsForm(forms.ModelForm): full_name = forms.CharField(required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) profile_email = forms.CharField(required=False, widget=forms.TextInput(attrs={'readonly': 'readonly'})) def __init__(self, *args, **kwargs): super(ProfileSettingsForm, self).__init__(*args, **kwargs) self.initial['profile_email'] = Profile.user.email self.initial['full_name'] = Profile.user.name class Meta: model = Profile fields = ['image','full_name','biography','profile_email','linked_in','facebook', 'twitter','phone','education'] -
Problems with mysqlclient in python virtualenv on OSX
I'm trying to make a Django application that uses mysql as database engine. I have followed a tutorial where it says I have to download pymysql packages using pip. I used the next command pip install pymysql. Unitl here all working. The next step is to make migrations in the django project, but when I try to do it, it throws me the next error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, … -
How to add other url paths to django_channels app
I'm currently trying to create chat app using django channels but adding path to the urls.py is working like it does on all other apps. What i mean is when a user clicks on the link that directs them to the chat app, it doesn't send them to where i want it to, funny thing is it was working for about 2 minutes then everything changed It tried making some changes in the javascript, routing.py, consumers.py but nothing worked views.py @login_required def load_chat(request, receivers_id): requesting_users_id = request.user.id request_user = request.user receivers_user = User.objects.get(id=receivers_id) if requesting_users_id > receivers_id: chat_room_id = str(requesting_users_id) + str(receivers_id) else: chat_room_id = str(receivers_id) + str(requesting_users_id) try: Chat.objects.get(chat_id=chat_room_id) return HttpResponseRedirect(reverse('rooms', kwargs={'room_name':chat_room_id})) except Chat.DoesNotExist: combined_users = [] combined_users.append(request_user) combined_users.append(receivers_user) Chat.objects.create(chat_id=chat_room_id) get_chat = Chat.objects.get(chat_id=chat_room_id) get_chat.participants.set(combined_users) get_chat.save() print(get_chat.participants) return HttpResponseRedirect(reverse('rooms', kwargs={'room_name':chat_room_id})) @login_required def dm(request, room_name): return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)) }) @login_required def room(request, room_name): return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)) }) urls.py urlpatterns = [ path('', index, name='index'), path('directmessage/<int:receivers_id>/', load_chat, name='message'), path('room/<int:room_name>/', dm, name='dm'), path('<str:room_name>/', room, name='room'), ] I expect the request to go through the load_chat function first before it goes to the room directly -
How to access a model's parent fields through a foreign key
Two things that are stumping me in Django: 1. How to access parent fields within a child model that has a one-to-many parent/child relationship and 2. How do I set the default value in a CreateView form to be equal to the url parameter. For the first question, I have made child fields into foreign keys to access a parent field, but I'm assuming there is a cleaner way to do this. Code for part 2 of Question models.py class Parent(models.Model): parent_name = models.CharField(unique=True, max_length=40) parent_slug = models.SlugField(unique=True) class Child(models.Model): child_name = models.CharField(unique=True, max_length=40) child_slug models.SlugField(unique=True) parent_name = models.ForeignKey(Parent, on_delete=models.CASCADE) urls.py urlpatterns = [ ... path('<parent_slug>/children/', ChildListView.as_view(), name='child_list'), ... ] views.py class ChildCreateView(CreateView): model = Child form_class = NewBranchForm template_name = 'child_new.html' def form_valid(self, form): form.instance.parent_slug = self.kwargs['parent_slug'] return super(ChildCreateView, self).form_valid(form) forms.py class NewChildForm(forms.ModelForm): class Meta: model = Child fields = ['child_name'] -
Django: Store functions in DB
I'm developing a math app. I want to know how to implement the Problem class. I want to do something like the following: Store problems in DB: problem=Problem.objects.get(id=1) problem has two functions: problem.text and problem.answer problem.text generates the text of the problem. For example, problem.text(x,y)=str(x)+"+"+str(y)+"=?".This generates texts such as "1+2=?", "5+2=?", ... problem.answer calculates the answer of these problems. For example, problem.answer(x, y)=x+y. This is the answer to problem.text(x, y). However, models.FunctionField() does not exist in Django. Should I store problem.text and problem.answer as python codes in models.TextField and use eval()? -
Adding/changing logic in send_email method within django-registration-redux
My site runs multiple domains. Users can register on each of these domains. As a result, I need to make django-registration-redux: use the correct email address for sending registration/password reset emails use the correct email password for sending registration/password reset emails use the correct domain within registration/password reset emails I've been digging into the source code for django-registration-redux and believe that I need to update the send_email method within registration/models.py (https://github.com/macropin/django-registration/blob/master/registration/models.py) with my required changes. I'm assuming the best way to add this cusomtization is as follows: run 'pip uninstall django-registration-redux==2.2' from the source code, pull the 'registration' folder into my project go into myproject/registration/models.py and manually update the send_email method so that it includes my changes. Is there an easier or more correct way to build my custom logic into def send_email without making the changes noted above? Thanks! -
Abstract urls that are not part of your website in Django
Say for example on your django site, you have many buttons/links that redirect someone to http://stackoverflow.com. Instead of having to hardcode that in every time like <a href="http://stackoverflow.com" target="_blank" rel="noopener"> Is there a way abstract it so that you have one big list of urls, and you can just refer to with in your template with django tags? stackoverflow = "http://stackoverflow.com" <a href="{{ stackoverflow }}" target="_blank" rel="noopener"> -
MultiValueDictKeyError when attempting to retrieve ImageField
I'm trying to retrieve an ImageField from a form in a view so I can attach it to an email, however no matter which way I try to assign it, I get the following error: MultiValueDictKeyError at /url/ 'imgfile1' Request Method: GET Request URL: https://example.com/url/ Django Version: 2.2.1 Exception Type: MultiValueDictKeyError Exception Value: 'imgfile1' My view is simple enough: def form_view(request): last_name = request.POST.get('last_name', False) phone = request.POST.get('phone', False) email = request.POST.get('email', False) description = request.POST.get('description', False) form = TestForm(request.POST, request.FILES or None) imgfile1 = request.FILES['imgfile1'] if request.method == 'POST': if form.is_valid(): try: mail = EmailMessage('Test', '', ['noreply@example.com'], ['bob@example.com']) # mail.attach(imgfile1.name, imgfile1.read(), imgfile1.content_type) mail.send() template = 'email_templates/mail.html' except: return "Attachment error" form.save() template = loader.get_template('/myapps/mq_site/mq_django/main_page/templates/main_page/sent.html') return HttpResponse(template.render({}, request)) template = loader.get_template('/myapps/mq_site/mq_django/main_page/templates/main_page/form.html') return HttpResponse(template.render({'form': form}, request)) I can comment out imgfile1 = request.FILES['imgfile1'] and it will load, but this leaves me at a loss how ti access imgfile1 and attach it to my email, or at least to get it's url so I can provide a link to it. What am I doing wrong? -
Printing results of a QuerySet in template grouped by a Number
I have a model in my django app which is a list of contacts to be showed as bootstrap4 tabs as 12 results per tab in a single request without using pagination. So far I have decided to give it a try by looping through query by a division of 12 and manipulate code by using a hack from great thread here Is there a filter for divide for Django Template? and try to divide query by compute A/B: {% widthratio queryset 12 1 %} method. and printing out tab numbers by checking {{ queryset|divisibleby:"12" }} but it turns to be it only print one item from query set for each 12 pieces group. ## Tabs Header <ul id="tabs" class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a id="ref-tab-1" href="#ref-pane-1" class="nav-link active" data-toggle="tab" role="tab"> 1 # Counter for 12 pieces </a> </li> </ul> ## Tabs Content <div id="content" class="tab-content" role="tablist"> <!-- Tab Page 1 --> <div id="ref-pane-1" class="card tab-pane fade show active" role="tabpanel" aria-labelledby="ref-tab-1"> <div class="card-header" role="tab" id="heading-1"> <h5> <a data-toggle="collapse" href="#collapse-1" aria-expanded="true" aria-controls="collapse-1"> # Counter for 12 pieces </a> </h5> </div> <div id="collapse-1" class="collapse show" role="tabpanel" data-parent="#content" aria-labelledby="heading-1"> <div class="card-body"> ## This is item to be looped through queryset <div class="partner"> <div … -
Django - Grouping by one column (using count)
I would like to get such an effect SELECT "restApi_comment"."id", "restApi_comment"."text", "restApi_comment"."movie_id", COUNT("restApi_comment"."id") AS "count" FROM "restApi_comment" GROUP BY "restApi_comment"."movie_id" ORDER BY "count" DESC but django is based on this obj = Comment.objects.annotate(count=Count('movie_id')).order_by('-count') give me SELECT "restApi_comment"."id", "restApi_comment"."text", "restApi_comment"."movie_id", COUNT("restApi_comment"."id") AS "count" FROM "restApi_comment" GROUP BY "restApi_comment"."id", "restApi_comment"."text", "restApi_comment"."movie_id" ORDER BY "count" DESC the problem is grouping which is based not on one column (movie_id) but on three (id, text, movie_id). [models.py] class Comment(models.Model): text = models.CharField(max_length=50, blank=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) I tried this method obj=Comment.objects.values('movie_id').annotate(count=Count('movie_id')).order_by('-count').values('movie_id', 'text') which gave me such an effect and did not return all the columns SELECT "restApi_comment"."movie_id", COUNT("restApi_comment"."movie_id") AS "count" FROM "restApi_comment" GROUP BY "restApi_comment"."movie_id" ORDER BY "count" DESC -
gevent django remote connection closed
I wrote the following code: from django.core.management.base import BaseCommand, CommandError from sbbetting.models import Team, League, Fixture, Country import requests from bs4 import BeautifulSoup from django.core.exceptions import ObjectDoesNotExist from datetime import datetime, timedelta pool = gevent.pool.Pool() class Command(BaseCommand): def get_page(self, url, use_headers=None): headers = { "Host": "d.flashscore.com", } if(use_headers): response = requests.get(url, headers=headers) else: response = requests.get(url) return BeautifulSoup(response.content, features="lxml") def find_ids(self, input): return_value = [] for index in range (0, len(input)): if(input[index:index + 3] == "AA÷"): return_value.append(input[index+3:index+11]) return return_value def create_related_fixtures(self, fixture, related_fixtures): for match in related_fixtures[0:10]: gevent.sleep(10) match_code = match.get('onclick')[17:25] base_url = "https://www.flashscore.com/match/" + match_code summary_url = "https://d.flashscore.com/x/feed/d_su_" + match_code + "_en_1" fixture_data = self.get_page(base_url) summary_data = self.get_page(summary_url, True) teams = fixture_data.find_all('div', {'class': 'side-images-row'}) home_id = teams[0].find('a').get('onclick').split('/')[3].split("'")[0] away_id = teams[1].find('a').get('onclick').split('/')[3].split("'")[0] home_name = teams[0].find('img').get('alt').split(" (")[0] away_name = teams[1].find('img').get('alt').split(" (")[0] country_name = str(fixture_data.find('div', {'class': 'fleft'}).find_all('span')[1].text.split(":")[0]).lower().title() league_name = fixture_data.find('div', {'class': 'fleft'}).find_all('span')[1].text.split(":")[1].split(" -")[0].replace(" ", "", 1) league_url = "https://flashscore.com" + fixture_data.find('div', {'class': 'fleft'}).find('a').get('onclick').split("'")[1].split("'")[0] league_data = self.get_page(league_url) season = league_data.find('div', {'class': 'tournament-season'}).text country = Country.create(country_name) league = League.create(league_name, season, country) home = Team.create(home_name, league, home_id) away = Team.create(away_name, league, away_id) fh_goals_home = 0 fh_goals_away = 0 sh_goals_home = 0 sh_goals_away = 0 all_fields_populated = True if(len(summary_data.find_all('div', {'class': 'detailMS__incidentsHeader'})) > 1): fh_goals_home = int(summary_data.find_all('div', {'class': … -
Filtering a queryset with foreign key value in ListView
I am trying to filter a queryset by setting the value of the foreign key equal to a url slug. models.py class Parent(models.Model): parent_name = models.CharField(unique=True, max_length=40) parent_slug = models.SlugField(unique=True) class Child(models.Model): child_name = models.CharField(unique=True, max_length=40, default=1) child_slug = models.SlugField(unique=True, default=1) parent_slug = models.ForeignKey(Parent, on_delete=models.CASCADE,default = 1) urls.py from .views import ChildListView urlpatterns = [ ... path('<parent_slug>/children/', ChildListView.as_view(), name='child_list'), ... ] views.py class ChildListView(ListView): template_name = 'child_list.html' context_object_name = 'child' def get_queryset(self): slug_param = self.kwargs['parent_slug'] qs = Child.objects.filter(parent_slug = slug_param) return qs This is the error result: Exception Value: Cannot resolve keyword 'parent' into field. -
Django - most pythonic way to add HTML to template from AJAX call
I have a web app where a user can search for a list of cameras and the search will return the cameras in an HTML table. This is the functionality I am trying to add: 1) User is brought to a barebones homepage with nothing but a search bar (think google) 2) On every keystroke the user makes in the search bar, JQuery should send an AJAX GET request to the server with the search term, and the results of the search should be shown in a table beneath the search bar. 3) If the search returns a list of cameras where they all share the same value for an attribute, a button should appear. Here is my current code. <!-- siren_search.html --> <div class="row"> <div class="col-sm-8 col-md-7 col-xl-5 mx-auto"> <form id="searchform" action="{% url 'siren_search' %}" method="GET"> <input id="searchbar" name="query" autocomplete="off" onkeyup=getCameras(this.value) placeholder="Search for the name of a jobsite." class="form-control" type="search" /> </form> </div> </div> <div class="row"> <div id="results-section" class="col-sm-8 col-md-7 col-xl-5 mx-auto"> {% if cameras.count > 0 %} <button id="trigger-all-btn" type="button" class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn">Trigger all sirens</button> <table id="camera-table" class="table table-hover"> <thead> <tr class="header"> <th scope="col" style="width:33%;">Asset Name</th> <th scope="col" style="width:33%;">Job Site</th> <th scope="col" style="width:33%;"></th> </tr> </thead> … -
Passing Values in stripe checkout.js form
How can I pass a name, city, postal code and country value in the checkout.js form? <form action="" method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ data_key }}" data-amount="{{ stripe_total }}" data-name="Store Name" data-description="{{ description }}" data-image="{% static 'img/img.png' %}" data-locale="auto" data-currency="cad" data-shipping-address="false" data-billing-address="true" data-billing-name="{{ fullname }}" data-billing-city="{{ city }}" data-billing-postal="{{ postal }}" data-billing-country="{{ country }}" data-allow-remember-me="false" data-label="Pay with card"> </script> </form> Is there any way to do it? -
Error while sending emails from godaddy hosted emails in Django
have a mail hotwd on godaddy say verify@mydomain.com I want to send mails from my backend using EmailMultipleAlternative. But I am getting error saying "connection closed unexpectedly" Here is my views and settings : views.py subject = 'Welcome to MySite! Confirm Your email.' htmly = get_template('account_activation_email.html') d = { 'user': user, 'domain':current_site.domain, 'uemail':urlsafe_base64_encode(force_bytes(user.email)), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user)} text_content = "" html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, text_content, '', [user.email]) msg.attach_alternative(html_content, "text/html") try: msg.send() except Exception as e: print(e) #this throws connection closed unexpectedly! print("Error while sending email!") user.save() settings.py MAIL_USE_TLS = True EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = verify@mysite.com EMAIL_HOST_PASSWORD = 'randompass' EMAIL_PORT = config('EMAIL_PORT') DEFAULT_FROM_EMAIL = 'MySte Verification <verify@mysite.com>' Please help me!!! -
Django Wagtail: Is it bad practise access data using own object.method instead of rewriting object.get_context method?
I am playing with Django Wagtail. Concerning rendering data in templates, I know that official way is rewrite get_context method in my page object. But I can just write my own method, I find it better and more clear for me. Just want to ask if this is possible way how to do that or is there any problem, catch, performance issues? Thank you very much. standard way: class Blog(Page): template = "blog/blog.html" def get_context(self, request): context = super().get_context(request) get_posts = self.get_children().live().order_by('-first_published_at').all() context['list_all'] = get_posts return context using own method: class Blog(Page): template = "blog/blog.html" def list_all(self): get_posts = self.get_children().live().order_by('-first_published_at').all() return (get_posts) Render in template - standard way: {% for post in list_all %} {{post.title}} {% endfor %} Render in template - own method: {% for post in self.list_all %} {{post.title}} {% endfor %} -
How to save fields only of the child model, and not to affect the fields of the parent model Django?
I have app 'profile' and two models: 'Human' and 'Client'. The 'Human' model extends the built-in 'User' model. And the 'Client' model expands the 'Human' model. from django.contrib.auth.models import User class Human(User): city = models.CharField(max_length=100, blank=True) address = models.CharField(max_length=150, blank=True) phone = models.CharField(max_length=30, blank=True) def __str__(self): return "{0} ({1})".format(self.username, self.get_full_name()) class Client(Human): company = models.CharField(max_length=100, blank=True) discount = models.DecimalField(max_digits=4, decimal_places=2, default=15) def __str__(self): return "#{} : {} | {} ({})".format(self.id, self.username, self.get_full_name(), self.company) In the shell, I create a new entry through the Human model: from profile.models import Human hu = Human(username='first', email='first@test.test', first_name='Mr.First', city='First City', phone="+9876543210") hu.set_password('12345678') hu.save() In the database, I see that records appear in the auth_user and profile_human tables Suppose my user has become my client. And now I need to add additional data to the Client model. This is not a new user! A record of it already exists (for example, id = 3). If I do this: from profile.models import Client cli = Client(id=3, company='FST', discount=10.00) cli.save() That, in the profile_client table an entry appears with information in the specified fields. But also, in the auth_user and profile_human tables, all information from all fields disappears. Question: How to save fields only of the child … -
Django Test Case Writing for Multiple Models
I am trying to write Django TestCase for last few days but i failed to write testcase for multiple models this is my models.py from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.TextField(max_length=50) class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) And i tried to write TestCase like this. this is my tests.py from django.test import TestCase from blog.models import Article, Author, Category class TestContactModel(TestCase): def setUp(self): self.article = Article(author='jhon', title='how to test', body='this is body', category='djangooo') self.article.save() def test_contact_creation(self): self.assertEqual(article.objects.count(), 1) def test_contact_representation(self): self.assertEqual(self.article.title, str(self.article)) Can anyone tell me how can i craft this test? Your time and caring is much appreciated -
How to include javascript function in django html file
I want to create a Partially collapsing static sidebar following https://bootstrapious.com/p/bootstrap-sidebar within django project but the click to collapse sidebar doesn't work. I tried putting the script in /static/JaS.js but seem like I don't know how to do this correctly {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'app1/main.css' %}"> <link rel="stylesheet" href="{% static 'app1/JaS.js' %}"> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3>Bootstrap Sidebar</h3> <strong>BS</strong> </div> <ul class="list-unstyled components"> <li class="active"> <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <i class="fas fa-home"></i> Home </a> <ul class="collapse list-unstyled" id="homeSubmenu"> </ul> </li> <li> <a href="#"> <i class="fas fa-briefcase"></i> About </a> <a href="#pageSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <i class="fas fa-copy"></i> Pages </a> <ul class="collapse list-unstyled" id="pageSubmenu"> </ul> </li> <li> <a href="#"> <i class="fas fa-image"></i> Portfolio </a> </li> <li> <a href="#"> <i class="fas fa-question"></i> FAQ </a> </li> <li> <a href="#"> <i class="fas fa-paper-plane"></i> Contact </a> </li> </ul> <ul class="list-unstyled CTAs"> <li> <a href="https://bootstrapious.com/tutorial/files/sidebar.zip" class="download">Download source</a> </li> <li> <a href="https://bootstrapious.com/p/bootstrap-sidebar" class="article">Back to article</a> </li> </ul> </nav> <!-- Page Content --> <div id="content"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info"> <i class="fas fa-align-left"></i> <span>Toggle Sidebar</span> </button> <button class="btn btn-dark d-inline-block … -
about auth.models.User trying to get the detailview page
I am using the ( from django.contrib.auth.models.User ) model and over riding it. when i am trying to access to the detail page it wont let while i am returning my pk. tryd to work with get_object_or_404 in models.py: class User(models.User,models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) in views.py: class Profile(DetailView): model = models.User template_name = "account/profile.html" in urls.py: path('profile/<int:pk>',views.Profile.as_view(),name="profile"), in html template: <a href="{% url 'profile' pk=user.pk %}" -
Celery and Rabbit works well on Local but tasks are not received on production server
Sending email as background tasks works well on local rabbit Url, but it seems tasks are not relayed to Celery on Heroku using Rabbit:cloudAMQP Python3.6, Django2.2, Celery 4.3, Django-celery-mail 2. I tried adding BROKER_POOL_LIMIT=1 in setting but that didn't solve the problem on Local: Settings.py INSTALLED_APPS = [ ... djcelery_email, ... ] CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672/' EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' celery.py from __future__ import absolute_import from django.conf import settings import os from celery import Celery # setting DjanoSETTTINGS as default os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') app = Celery(broker=settings.CELERY_BROKER_URL) app.config_from_object('django.conf.settings') app.autodiscover_tasks(settings.INSTALLED_APPS) if __name__ == '__main__': app.start() running celery with celery -A vault worker -l info Works well receives tasks and executes. on Heroku: However; setting Broker url to: CELERY_BROKER_URL = os.environ['CLOUDAMQP_URL'] on heroku tasks are never received. Rather request timeouts, Result on Local: [2019-06-16 14:36:56,923: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2019-06-16 14:36:56,950: INFO/MainProcess] mingle: searching for neighbors [2019-06-16 14:36:58,017: INFO/MainProcess] mingle: all alone [2019-06-16 14:36:58,100: INFO/MainProcess] celery@Pavilion ready. [2019-06-16 14:36:58,103: INFO/MainProcess] Received task: djcelery_email_send_multiple[aa4ed64d-f91e-488a-a640-c35ea39a6646] [2019-06-16 14:37:02,306: INFO/ForkPoolWorker-8] Task djcelery_email_send_multiple[aa4ed64d-f91e-488a-a640-c35ea39a6646] succeeded in 4.09453737900003s: 1 Result on Heroku: 2019-06-16T17:22:17.269761+00:00 app[worker.1]: [2019-06-16 17:22:17,264: INFO/MainProcess] Connected to amqp://abcdefhh:**@llama.rmq.cloudamqp.com:5276/abcdefhh 2019-06-16T17:22:17.317147+00:00 app[worker.1]: [2019-06-16 17:22:17,316: INFO/MainProcess] mingle: searching for neighbors 2019-06-16T17:22:18.383655+00:00 app[worker.1]: [2019-06-16 17:22:18,383: INFO/MainProcess] mingle: all alone 2019-06-16T17:22:18.449618+00:00 app[worker.1]: [2019-06-16 17:22:18,449: INFO/MainProcess] celery@eaa4cb0e-de01-4307-96cd-bdace12e418b … -
django.core.exceptions.ImproperlyConfigured: WSGI application '{project_name}.wsgi.application' could not be loaded; Error importing module
cant understand why im facing an error while running heroku run python manage.py runserver tried changing folder names tried removing and adding whitenoise in middleware ```MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django.middleware.security.SecurityMiddleware', # 'whitenoise.middleware.WhiteNoiseMiddleware', ]``` database settings ```DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } django_heroku.settings(locals()) wsgi.py ```import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{{PROJECT}}.settings') application = get_wsgi_application() application = DjangoWhiteNoise(application) atleast the server should run so that i can see whats the issue with heroku -
Django Test Case writing for Two models relation with foreign key
I am new in Django TestCase Writing and not getting how to write TestCase for Two models. This is my Models.py from django.db import models class UserId(models.Model): userId = models.IntegerField(unique=True) class Contact(models.Model): userId = models.ForeignKey('UserId', on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.EmailField(unique=True) phone = models.IntegerField(unique=True) def __str__(self): return self.name and this is my tests.py from django.test import TestCase from ng.models import Contact class TestContactModel(TestCase): def setUp(self): self.contact = Contact(userId=25, name='jhon doe', email='testt@fk.com', phone=215448) self.contact.save() def test_contact_creation(self): self.assertEqual(Contact.objects.count(), 1) def test_contact_representation(self): self.assertEqual(self.contact.name, str(self.contact)) My Test was worked nice once there was only one models and no foreign key. Now i created two models and connect them with foreign key, that is why my TestCase not working now. Can anyone tell me how to write test for two models? or if anyone help me to write this testcase, it whould be very much appreciated -
using blocks within a loop in a Django template
use_case is a list of dictionaries that I'm passing to the template you see below. So entry is going to hold each dictionary. The values in the dictionary such as entry.picture_tagline are the correct data to put into the blocks that appear below. But apparently this is not allowed. Is there any way to use blocks like this within a loop? {% for entry in use_case %} {% block picture_tagline %} {{ entry.picture_tagline }} {% endblock %} {% block picture %} {{ entry.picture }} {% endblock %} {{ entry.picture_description }} {% block picture_description %} {% endblock %} {% endfor %} -
local variable 'data' referenced before assignment - python
I am getting the error in my code Request Method: GET Request URL: http://localhost:8000/emotion/ Django Version: 2.2 Exception Type: UnboundLocalError Exception Value: local variable 'data' referenced before assignment Exception Location: C:\Users\Sant\Desktop\music_demo\music_site\views.py in emotion, line 314 Python Executable: C:\Users\Sant\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Sant\Desktop\music_demo', Server time: Sun, 16 Jun 2019 17:27:51 +0000 def emotion(request): from mutagen.id3 import ID3 from mutagen.mp3 import MP3 import sys import spotipy from spotipy.oauth2 import SpotifyClientCredentials client_id = '26473c91fefc43eca3a6531e0f062723' client_secret = '9d7c8ddb18594838ae5db6ad10b3ddf0' title = 'lollypop' artist = 'pawan singh' client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) sp.trace=False search_querry = title+ ' ' + artist result = sp.search(search_querry) for i in result['tracks']['items']: # Find a songh that matches title and artist if (i['artists'][0]['name'] == artist) and (i['name'] == title): print (i['uri']) break else: try: # Just take the first song returned by the search (might be named differently) print (result['tracks']['items'][0]['uri']) uri = result['tracks']['items'][0]['uri'] client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) sp.trace=False features = sp.audio_features(uri) print ('Energy:', features[0]['energy']) data = { "energy" : features[0]["energy"], "valence" : features[0]["valence"], "key" : features[0]["key"], "link" : features[0]["valence"], "danceability" : features[0]["link"], "loudness" : features[0]["loudness"], "tempo" : features[0]["tempo"], "acousticness" : features[0]["acousticness"], "liveness" : features[0]["liveness"], "instrumentalness" : features[0]["instrumentalness"] } except: # No results for artist …