Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extra conditional annotation breaks previous annotation
I have the following models in a game app I'm working on:- class Player(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players') class Game(models.Model): players = models.ManyToManyField(Player, through='GameMembership', related_name='games') class GameMembership(models.Model): game = models.ForeignKey(Game, related_name='memberships') player = models.ForeignKey(Player, related_name='memberships') team = models.ForeignKey(Team, null=True, related_name='memberships') selected = models.BooleanField(default=False) class Team(models.Model): game = models.ForeignKey(Game, related_name='teams') score = models.IntegerField(null=True) I want to get a list of all the Players along with the number of times they were selected, so I annotate the queryset like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1)))) which works exactly as expected. However, I also want the total number of goals that were scored in all the games each player was selected, so I annotate like this:- Player.objects.all().annotate(played=Count(Case(When(memberships__selected=True, then=1))), total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score')))) which gives the right number for total_goals but for some reason, the value of the played count has doubled! All I did was add this annotation:- total_goals=Sum(Case(When(memberships__selected=True, then='games__teams__score'))) So what happened? I strongly suspect I need a distinct() call somewhere but I don't see why the extra annotation has an effect on the first one. Any ideas? -
Best Postgres/DB format for storing an array of strings with a boolean attached to them in Django?
I'm storing an array of URL links in my Postgres database like this: urls = ArrayField( models.CharField(max_length=250, blank=False) ) But I want to track if a URL has been visited or not, as a boolean. What is the best way to do this? -
Cannot redirect when djanog model class is mocked
I have a view here which adds a new List to the database and redirects to the List page. I have get_absolute_url configured in the model class. It seems to works perfectly. def new_list(request): form = ItemForm(request.POST) if form.is_valid(): list_ = List() list_.owner = request.user list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {'form': form}) But the problem happens when I try to mock the model class and the form class with patch from unitest.mock class TestMyLists(TestCase): @patch('lists.views.List') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated( self, mockItemFormClass, mockListClass ): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) When I run the test, I get error like this: Traceback (most recent call last): File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/BAC4BB93C4BB4FFD/codes/tdd/superlists/lists/views.py", line 36, in new_list return redirect(list_) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/shortcuts.py", line 58, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/http/response.py", line 407, in __init__ self['Location'] = iri_to_uri(redirect_to) File "/home/sjsakib/.virtualenvs/superlists/lib/python3.6/site-packages/django/utils/encoding.py", line 151, in iri_to_uri return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "/usr/local/lib/python3.6/urllib/parse.py", line 787, in quote return quote_from_bytes(string, safe) File "/usr/local/lib/python3.6/urllib/parse.py", line 812, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") TypeError: quote_from_bytes() … -
Advices for social-networking
I am a high school student and I like computing. I have bases with C#, R, Python and I have been developing a static website with Html5 and CSS. I'd like now to start a new project. A social network like for riders but I don't know at all which framework or language start with. I already heard about Django, Ruby on Rails, Go, that make alot of choices and I wanted to have advices from experts or connoisseurs in the domain. -
django-rest-framwork Got AttributeError when attempting to get a value for field
i want get all prodcut table values with join product_ratings table . i did somthing like this but this code give me AttributeError ... i did product_ratings = ProductRatingSerializer(many=True) in product serializer and used this value in field but it not work: its full error message: Got AttributeError when attempting to get a value for field `product_ratings` on serializer `ProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'product_ratings'. view : class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs its serializer classes: class ProductRatingSerializer(ModelSerializer): class Meta: model = Product_ratings fields = [ 'p_id', 'commenter', 'comment', 'rating', 'created_date', ] read_only_fields = ['p_id'] class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'filepath', 'price', 'created_date', 'updated_date', 'product_ratings', ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author'] related model class : class Product(models.Model): product_id = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='cat_id') … -
Display output with out refresh using Django, Ajax
I am programming a simple basic calculator where I get the input from the user taking the input and do the calculation and display the output back on the same page I have a basic HTML form <form id="html_calc_form" action={%url 'calculation' %} method="post"> {% csrf_token %} First Number:<br> <input type="number" name="first number" value="0"> <br> Second Number:<br> <input type="number" name="second number" value="0"> <br> Operation:<br> <select name="operation" multiple> <option value="Addition">Addition</option> <option value="Subraction">Subraction</option> <option value="Muntiplication">Muntiplication</option> <option value="Division">Division</option> </select> <br><br> <input type="submit" name "submit" value="Submit"> <output name="result" ></output> </form> Ajax logic to prevent from refreshing the page $(document).ready(function(){ $('#html_calc_form').submit(function(event){ console.log(event); event.preventDefault() $.ajax({ url:'calc/', type:'POST', data:$(this).serialize(), success:function(response){ console.log(response); $('form')[0].reset(); } }); }) }) In django I have creates a model class Calculation(models.Model): first_digit = models.DecimalField(max_digits=7, decimal_places=3) second_digit = models.DecimalField(max_digits=7, decimal_places=3) CALCULATION_CHOICE = (('+', 'Addition'), ('-', 'Subraction'), ('*', 'Muntiplication'), ('/', 'Division')) calculate = models.CharField(max_length=1, choices=CALCULATION_CHOICE) And finaly my view def calc(request): if request.method == 'POST': first_number = request.POST['first number'] second_number = request.POST['second number'] operation = request.POST['operation'] result = do_calc(operation, first_number, second_number) # how to pass the result to my tempelate value = Calculation.objects.create( first_digit=first_number, second_digit=second_number, calculate=operation ) return JsonResponse(model_to_dict(value)) def index(request): return render(request, 'calculation/calculator.html') I want to pass the result to my HTML template and display … -
Django Jquery: Link (a-tag) to specific div on a different template does not work when this jQuery function is added
I have a link in a django template with the following characteristics: <a href="{% url 'rates:index' %}#our-services" class="accent-2">list</a> That link worked as intended until I used the JS code underneath in the same page as linked to above. This code lets the user select different tabs to display certain information. I am a novice when it comes to JS and therefore used a code snippet from Bourbon Refills. When I comment out the code the link works fine. Any suggestions on what part of the JS code affects the link? Any help would be greatly appreciated. $(function() { var containerSelector = '[data-tab-wrapper]'; var tabListSelector = '[data-tablist]'; var tabListItemSelector = '[data-tablist] > li'; var tabSelector = '[data-tablist] > li > a'; var tabPanelSelector = '[data-tabpanel]'; $(tabListSelector).attr('role', 'tablist'); $(tabListItemSelector).attr('role', 'presentation'); $(tabPanelSelector).attr('role', 'tabpanel'); // Setup: Wire up the anchors and their target tabPanels $(tabSelector).each(function(_, element) { $(element).attr({ 'role': 'tab', 'tabindex': '-1', 'aria-controls': getAnchor($(element)) }); }); // Setup: Set the tablist $(tabListSelector).attr('role', 'tablist'); // Setup: Select the first tab var firstTabLinkSelector = tabListItemSelector + ':first-child a'; select($(firstTabLinkSelector)); // Setup: Make each tabPanel focusable $(tabPanelSelector + ' > *:first-child').attr({'tabindex' : '0'}); // Setup: Hide all panels besides the first hide($(tabPanelSelector + ':not(:first-of-type)')); // When focused, … -
Check if user is part of a manytomany relationship django
I have this model for a Set: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') As you can see, the last field is a ManyToMany field. I need a queryset to get all the Sets that the user is part of. How would I do this? -
type char exceed 10485760 limit error still showing after I change the limit to something less than MAX
I have a django app, I'm migrating it's database from sqlite3 to postgres, i get the following error line since i got a field in one of the models set to 500000000 so i changed it to 10485750 and ran: python manage.py makemigrations app python manage.py sqlmigrate app 0001 python manage.py migrate but still got the following error django.db.utils.DataError: length for type varchar cannot exceed 10485760 LINE 1: ...ber" TYPE varchar(500000000) USING ........ how can I make it feel the change I made? -
Is there a way to raise normal Django form validation through ajax?
I found a similar question which is quite a bit outdated. I wonder if it's possible without the use of another library. Currently, the forms.ValidationError will trigger the form_invalid which will only return a JSON response with the error and status code. I have an ajax form and wonder if the usual django field validations can occur on the form field upon an ajax form submit. My form triggering the error: class PublicToggleForm(ModelForm): class Meta: model = Profile fields = [ "public", ] def clean_public(self): public_toggle = self.cleaned_data.get("public") if public_toggle is True: raise forms.ValidationError("ERROR") return public_toggle The corresponding View's mixin for ajax: from django.http import JsonResponse class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) print("VALID") data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response The View: class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' On the browser console, errors will come through as a 400 Bad Request, followed by the responseJSON which has the correct ValidationError message. Any way to get this done server side? -
Django template language extends doesn't work
Hi guys I am studying django framework using "django by example" book. The problem I am facing is that the template language does not work even I copy and pasted source code from book and/or github. A blog application that has post model and is inside the mysite project. You can see the code in picture and the result too: Inside blog\templates\blog . blog\templates\blog\base.html <!-- its base.html --> {% load staticfiles %} <!DOCTYPE HTML> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> Its the list that extends base.html and located in blog\template\blog\post: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} -
How to order initial data in Django-autocomplete-light
I'd like to update many-to-many through model data using Django-autocomplete-light's ModelSelect2Multiple, but when sending data to the form with the get_initial(), the data is not displayed in the order of the data sent; it will be displayed in the database registration order. How should I do to display data in ModelSelect2Multiple in the sorted order in through model? ModelSelect2Multiple works well when new data is registered. Here is my model.py class Writer(models.Model): name = models.CharField() class Event(models.Model): name = models.CharField() writer = models.ManyToManyField(Writer, through="Attend", related_name='attends') class Attend(models.Model): event = models.ForeignKey(Event) writer = models.ForeignKey(Writer) number = models.PositiveSmallIntegerField(default=0) Here is my preview.py class EventUpdateFormPreview(FormPreview): form_template = "app/event_update.html" preview_template = "app/event_update_preview.html" def get_initial(self, request): event = Event.objects.get(id=self.state["event_id"]) return { 'name': event.name, 'writer': [x.pk for x in event.writer.all().order_by('attend__number')], } Here is my forms.py class EventUpdateForm(forms.ModelForm): name = forms.CharField(label='event name') writer = forms.ModelMultipleChoiceField( label='Attends', queryset=Writer.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='app:writer_autocomplete', ) ) Registration order in datababase Writer Mr.A(pk=1) Writer Mr.B(pk=2) Writer Mr.C(pk=3) Writer Mr.D(pk=4) The order of attendees in registered events(It will be successful at the initial registration) Writer Mr.D(pk=4) Writer Mr.A(pk=1) Writer Mr.C(pk=3) The order displayed on the update view Writer Mr.A(pk=1) Writer Mr.C(pk=3) Writer Mr.D(pk=4) Environment: Django==1.11.6 django-autocomplete-light==3.2.10 Please excuse my poor English, Thank you so … -
have issue with foundation dropdown menu in top-bar
I install foundation-sites with yarn or npm. So i have sources in node_modules/foundation-sites. I use django but i have the same issue without it Here is my index.html: {% load static %} {% load sass_tags %} <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>short url</title> {% load compress %} {% compress css %} <link href="{% sass_src 'scss/style.scss' %}" rel="stylesheet" type="text/css" /> {% endcompress %} </head> <body> <div class="top-bar"> <div class="top-bar-left"> <ul class="dropdown menu" data-dropdown-menu> <li class="menu-text">shorturl</li> <li><a href="/shorturl">Racine</a></li> <li><a href="/shorturl/url_list">url list</a></li> <li> <a href="http://www.perdu.com">perdu</a> <ul class="menu vertical"> <li><a href="#">Lien 1</a></li> <li><a href="#">Lien 2</a></li> </ul> </li> </ul> </div> </div> {% block content %} {% endblock %} <script src="{% static "js/jquery/dist/jquery.js" %}"></script> <script src="{% static "js/what-input/dist/what-input.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/foundation.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.core.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.dropdown.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.dropdownMenu.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.keyboard.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.box.js" %}"></script> <script src="{% static "js/foundation-sites/dist/js/plugins/foundation.util.nest.js" %}"></script> <script src="{% static "js/app.js" %}"></script> </body> </html> When i load the web-page, i have this:issue with dropdown menu Someone has an idea to solve it ? Thx for your help -
Session.request and 'Decimal' is not JSON serializable
I try to improve my Django knowledge (I'm a beginner) by developing a Django ecommerce website. I'd like to have two types of cart, one named cart and this other one named composed_cart. I have an error with the composed_cart. I came accross the following error when I try to display the cart: Object of type 'Decimal' is not JSON serializable For my add to composed_cart class, I use the following code: composed_cart.py: class ComposedCart(object): def __init__(self, request): self.session = request.session composed_cart = self.session.get('composed_cart') if not composed_cart: composed_cart = self.session['composed_cart'] = {} self.composed_cart = composed_cart def add_composed(self, product, quantity=1): product_id = str(product.id) if product_id not in self.composed_cart: self.composed_cart[product_id] = {'quantity': 1,'price': str(product.prix_unitaire), 'tva': str(product.taux_TVA.taux_applicable)} else: self.composed_cart[product_id]['quantity'] += quantity #Ajoute +1 à la quantité et met à jour le dictionnaire contenant la quantité. += signifie ajoute à la valeur initiale de quantité. self.save() def save(self): self.session['composed_cart'] = self.composed_cart self.session.modified = True def remove(self, product): #Supprimer le produit, quelque soit la quantité. product_id = str(product.id) if product_id in self.composed_cart: del self.composed_cart[product_id] self.save() def remove_one(self, product, quantity=1): #Méthode permettant de supprimer une unité du produit. product_id = str(product.id) if product_id in self.composed_cart: #Si le produit est dans le panier if self.composed_cart[product_id]['quantity'] > 1: … -
How Can I Restrict One Vote For One User?
My models.py is this and I have created the user registration form. I want to restrict one vote for one user. How Can I do so? class Choice(models.Model): choice_text = models.CharField(max_length= 200) votes = models.IntegerField(default= 0) image2 = models.ImageField(upload_to="Question_Image2", blank=True) question = models.ForeignKey(Question, on_delete= models.CASCADE) def __str__(self): return self.choice_text def vote_range(self): return range(0, self.votes) My views.py is this for vote def vote(request, question_id): question = get_object_or_404(Question, pk= question_id) try: selected_choice = question.choice_set.get(pk = request.POST['choice']) except: return render(request, 'polls/detail.html', {'question':question, 'error_message':"Please select a choice"}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args = (question.id,))) -
Why is my instance in the ModelForm coming through as a NoneType?
I'm trying to obtain a Profile object within a forms.py ModelForm. print(type(self.instance)) will return <class 'user_profile.models.Profile'> as expected, but print(self.instance) will return an error: AttributeError: 'NoneType' object has no attribute 'username' First the form: class PublicToggleForm(ModelForm): class Meta: model = Profile fields = [ "public", ] def clean_public(self): public_toggle = self.cleaned_data.get("public") if public_toggle is True: print(type(self.instance)) print(self.instance) return public_toggle Here is the model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='is_profile_to') def __str__(self): return self.user.username The AUTH_USER_MODEL: class User(AbstractUser): def __str__(self): return self.username I didn't actually set the username field myself. I used django-allauth, and I assume they have a username field. Returning the Profile object as a string representation of it's User's username hasnt given me problems before. So could it be related to the way that my form is indirectly tied to the view? I have a FormView, and a DetailView into which the form is inserted: This is the extent of the FormView: class PublicToggleFormView(AjaxFormMixin, FormView): form_class = PublicToggleForm success_url = '/form-success/' template_name = 'user_profile/profile_detail.html' And the DetailView: from .forms import PublicToggleForm class ProfileDetailView(DetailView): template_name = 'user_profile/profile_detail.html' def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) profile = Profile.objects.get( user__username=self.request.user) context['public_toggle_form'] = PublicToggleForm(instance=profile) return context -
Not authorized to unlink social account?
I am trying to unlink social (Facebook) account from user: axios.post(`/socialaccounts/${account.id}/disconnect/`, { headers: { 'Authorization': 'Token ' + this.getAuthToken, } }).then(res => { console.log(res.data) this.socialAccounts.splice(index, 1) }).catch(err => { console.log(err.response) }) This is giving me a 401 error: "Authentication credentials were not provided." I'm clearly providing credentials, so not sure at this point whether it is my error or something else going on. -
How do I display an alert /message while rendering to a template page in Django?
I have a views function that needs to render to a certain template page once a condition is satisfied. However I would like to display an alert or a message while rendering to that template. I am a novice in Django. Please bear with me if I using the word render inappropriately. How do I display this alert/message while redirecting to that page ? Thanks in advance -
Why did you choose to use the web framework which you are using now?
Looking for experience, not the theory! nodejs, #spring-mvc, #spring-boot, #angular, #django, #rubyonrails, #Meteor, #react -
Django: column spanning multiple rows in template
How can I have a column span multiple rows when that particular column has same values for every row? Column1--------Column2----Column3-----column4 ...............--------Value21----Value31-------Value41 Value1-----------Value22----Value32-------Value42 .............. This is my template: <div class="row"> <div class="table-responsive row col-md-13"> <table class="table table-hover table-striped table-bordered table-condensed "> <thead> <tr> <th>Doctor</th> <th>Clinic</th> <th>Day</th> <th>Time</th> </tr> </thead> <tbody> {% for vis in docClinic_list %} <tr> <td> {{ vis.0 }} </td> {% for vi in vis.1 %} <td>{{ vi.clinic_name }}</td> {% for v in vi.day_time %} <td>{{ v.day }}</td> <td>{{ v.time }}</td> {% endfor %} {% endfor %} </tr> {% endfor %} </tbody> </table> </div> It shows data in one row. That is because of that <tr>. But I don't know how would I achieve that spanning. May be a table' within that`? But its seems like bad coding standard. Any other options? Thank you -
Error while select_related query
I have Question and QuestionChoices models as below, when I try to retrieve the Question and related Answers from the Questionchoices I get the below error saying that the query is expecting string. What could be wrong model/query? class Question(models.Model): Question_Id = models.AutoField(primary_key=True) Question_Text = models.TextField(max_length=1000) def __str__(self): return self.Question_Text def __int__(self): return self.Question_Id class QuestionChoices(models.Model): Choice_Id = models.AutoField(primary_key=True) Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE) Choice = models.TextField(max_length=500) Is_Right_Choice = models.BooleanField(default=False) >>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id = Question.Question_Id) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q split_subq=split_subq, File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1215, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1085, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\lookups.py", line 18, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' -
pass value from extended template to base template in django
In my project in Django 2+, I have created a base.html template which wraps the other content templates. base.html <html> <head> <title>Example.com</title> </head> <body class="homepage"> {% block content %} {% endblock content %} </body> </html> and in one of content template pages/about.html {% extends 'base.html' %} {% block content %} This is about page of example.com {% endblock content %} Now, I have to change the class of body tag on base.html page to aboutpage How can I pass the value aboutpage from content template to base.html? -
Django's builtin cut filter
I need to remove spaces from a variable: the phone number is (123) 456-7891 I need it to be (123)456-7891 I tried <td><a href="ciscotel:1{{question.Phone|cut:" "}}" target="_self">{{question.Phone|cut:" "}}</a></td> But it's not working. -
Green Coloured Titles are showing in my Django Project Files, Atom Text Editor
My Working project files are showing with green color titles in Atom Text Editor. See the Screenshot of Atom Text Editor: https://drive.google.com/open?id=1yEPig9oO-aHBCqorOAWe_5nlnH9l6-vX EDIT: I have noticed that only the viewed files are showing the color change. -
502 Bad Gateway (nginx/1.10.3 (Ubuntu))
i sent my python3 django files to digital ocean server and getting 502 bad gateway error. I tried all the tips given elsewhere in stackoverflow but none worked. I believe there is something wrong with my settings.py. Specifically below lines, please let me know your suggestions: ALLOWED_HOSTS = ['*'] # Find out what the IP addresses are at run time # This is necessary because otherwise Gunicorn will reject the connections def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list # Discover our IP address ALLOWED_HOSTS += ip_addresses()