Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
verbose_name_plural Naming convention
Should verbose_name_plural be 'ItemsForSale', 'itemsforsale' or 'items_for_sale'? I've googled, read docs. class ItemForSale -
Simultaneous use of third-party FormFields and AngularJS in Django
In my Contact model I use a few third-party libraries for easier handling of parameters such as phonenumber or address. from django.db import models from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField class Contact(models.Model): """Contact documentation""" firstname = models.CharField(max_length=254) lastname = models.CharField(max_length=254) address = AddressField(on_delete=models.CASCADE) email = models.EmailField(max_length=254) phone = PhoneNumberField() Now I would like to use Django's automatic form creation AND handle the form data with AngularJS for which django-angular is a great tool since it adds the ng-model parameter to form input (which then can be binded to AngularJS's $scope). Unfortunately, django-angular library doesn't support third-party fields. If I try to include them in my form I get the "django.core.exceptions.ImproperlyConfigured: Please use the corresponding form fields from 'djng.forms.fields' for field 'address = AddressField(...)' in form '', which inherits from 'NgForm' or 'NgModelForm'." error. from address.forms import AddressField from phonenumber_field.formfields import PhoneNumberField from .models import Contact from djng.forms import NgModelFormMixin, NgModelForm class ContactForm(NgModelFormMixin, NgModelForm): address = AddressField() phone = PhoneNumberField(label='Phone number') class Meta: model = Contact fields = ('firstname', 'lastname', 'address', 'email', 'phone') Is there any way how to bind ng-model to third-party FormFields so that they can be handled by AngularJS? -
Static files aren't working in production
I run my django project on cPanel. Static files (img, css, js) aren't working. settings.py contains neccesary code for working with static files: STATIC_URL = '/static/' STATIC_ROOT = '/home/untutore/python_apps/berdyansk/south/static' In templates I call static files using {% load static %} in the <head> tag and <img src="{% static "imgfolder/imgname.jpg" %}"> in <body>. I run this command for collecting static files: python /home/untutore/python_apps/berdyansk/manage.py collectstatic --noinput I have a success message after running this command. Django should use static files at this stage, but he does not. Did I miss something? I did the same things when uploaded my project on pythonanywhere. Everything worked fine. There are a lot of questions on stackoverflow about django static files in production, but I didn't find a solution. -
Validating non-attribute in a ModelSerializer
Consider a repair company that wants to add expedited service areas to their regular service areas. In densely populated areas I want to provide an expedited service in addition to regular service. When a client hits my endpoint I want to not just return information about regular service, but some additional information regarding if the expedited service is also available. To accomplish this I have a model Service which represents the jobs that need to be completed. There is a Service to represent the regular pace job as well as the expedited job. I have an established serializer for my endpoint I would like to add to. This established endpoint will always pass the non-expedited version of service to the serializer. I want the ExpeditedServiceSerializer to return if the corresponding expedited service is active. I want to raise a validation exception if neither the regular or expedited services are active. class ExpeditedServiceSerializer(serializers.ModelSerializer): class Meta(object): model = Service fields = ( 'is_expedited_enabled', 'is_expedited_exclusive', 'expedited_active', ) is_expedited_enabled = serializers.SerializerMethodField() is_expedited_exclusive = serializers.SerializerMethodField() expedited_active = serializers.SerializerMethodField() def get_is_expedited_enabled(self, obj): request = self.context.get('request') user = request.user return user.is_quick_match_enabled() def get_is_expedited_exclusive(self, obj): request = self.context.get('request') user = request.user return user.is_expedited_exclusive() def get_expedited_active(self, obj): service = … -
Django form data not being saved, no error being given
I have a simple form where I take some information and allow some files to be uploaded. I'm not getting any errors, yet nothing is being saved when I submit the form. I'm not sure how to troubleshoot this. I've made django forms a bunch of times and can't see what I might be doing wrong here. My models.py: from __future__ import unicode_literals from django.db import models class Quote(models.Model): business = models.BooleanField() first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) zipcode = models.PositiveIntegerField() furnituretype = models.CharField(max_length=30) repairtype = models.CharField(max_length=30) description = models.TextField() imgfile1 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile2 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile3 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile4 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile5 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) datetime = models.DateTimeField(auto_now=True) My forms.py: from django import forms from .models import Quote class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ('business', 'first_name', 'last_name', 'email', 'phone', 'zipcode', 'furnituretype', 'repairtype', 'description', 'imgfile1', 'imgfile2', 'imgfile3', 'imgfile4', 'imgfile5') And my view: def quote_view(request): form = QuoteForm(request.POST, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect('/') template = loader.get_template('/webapps/my_site/ft_django/main_page/templates/main_page/quote.html') return HttpResponse(template.render({'form': form}, request)) And my template code: <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="main-button">Submit</button> … -
What does ProgrammingError at /contact/ mean?
I just added a contact form to my app then it returned this when I submitted the form. I don't have blog_quotes on my code and when I made migrations, nothing has changed. ProgrammingError at /contact/ relation "blog_quotes" does not exist LINE 1: INSERT INTO "blog_quotes" ("name", "email", "description") V... ^ Request Method: POST Request URL: https://myapp.herokuapp.com/contact/ Django Version: 2.1.9 Exception Type: ProgrammingError Exception Value: relation "blog_quotes" does not exist LINE 1: INSERT INTO "blog_quotes" ("name", "email", "description") V... ^ Exception Location: /app/.heroku/python/lib/python3.6/site- packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sun, 16 Jun 2019 23:57:25 +0800 What did I miss? -
Django Rest doesen't declate explicit
I'm installing django rest framework and when I add rest-framework in INSTALLED_APPS in settings.py, I'm receiving error like: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest-framework' Traceback (most recent call last): RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Any ideas what is that? -
In Django display API get request using as criteria data form models
I'm trying to display data from API get request and I want the criteria to be some data from my models. From debitori_list.html (uses IndexView) => detaliu_debitor.html (uses DebitorDetailView). This displays DetailView from my Debitori model. I want to use data stored in Debitori.nr_dosar as input for the variable nr_dosar from function rezultatCautareDosar in class DebitorDetailView. And then display the data received from the API get request in detaliu_debitor.html. The print(rezultatCautareDosar('request')) is just to test if I get any data form the API. Sorry for my poor explanation, but thanks for your support. The code is: IN MODELS.PY class Debitori(models.Model): nr_dosar = models.CharField(max_length=256) IN VIEWS.PY class IndexView(LoginRequiredMixin, ListView): redirect_field_name = '' model = Debitori template_name = 'debitori_list.html' def get_queryset(self): return Debitori.objects.order_by('nume_debitor') class DebitorDetailView(LoginRequiredMixin, DetailView): redirect_field_name = '' template_name = 'detaliu_debitor.html' queryset = Debitori.objects.all() def rezultatCautareDosar(request): cl = Client('http://portalquery.just.ro/Query.asmx?wsdl') req_data = {'numarDosar': 'my_numarDosar', 'obiectDosar': 'my_obiectDosar', 'numeParte': 'numeParte', 'institutie': 'my_institutie', 'dataStart': 'my_dataStart', 'dataStop': 'my_dataStop'} nr_dosar = '1/3/2019' def send_request(client, data): r = client.service.CautareDosare(numarDosar=nr_dosar) return r r = send_request(cl, req_data) return r print(rezultatCautareDosar('request')) IN TEMPLATES 1. DEBITORI_LIST.HTML {% for debitor in debitori_list %} <ul> <a href="{%url 'gapp:debitor_detail' pk=debitor.pk%}">{{debitor.nume_debitor}}</a> </ul> {%endfor%} 2. DETALIU_DEBITOR.HTML HELP -
how to slice text in django html?
I came across a problem in which I get the queryset displayed on the html. I cannot change the variable so i want to slice the output to only get a certain part. for better understanding <QuerySet [<User: testuser>]> this is what my I see on my html page whereas I just want to see testuser my html looks something like this <p>{{ blogs.all }} blog{{ blogs|pluralize }} </p> -
Have a web socket url how do I read its data in Django?
I have been working with Django. But I am new to WebSocket. So I have an API, whose data I wanna read in my Django rest framework view. Something how we do it for HTTP API. Please help me with the best possible way to do this. Tried below code. But it is not working. class checkApi(APIView): renderer_classes = (JSONRenderer,) def get(self,request,*args,**kwargs): # response = requests.get('https://api.github.com/users/kushalkanavi') # geodata = response.json() # return Response(geodata) message = '{"method": "GET", "url": "/api/projects/"}' request = WebSocketRequest(message) response = request.get_response() return Response(response) -
Django form data not being saved, no error being given
I have a simple form where I take some information and allow some files to be uploaded. I'm not getting any errors, yet nothing is being saved when I submit the form. I'm not sure how to troubleshoot this. I've made django forms a bunch of times and can't see what I might be doing wrong here. My models.py: from __future__ import unicode_literals from django.db import models class Quote(models.Model): business = models.BooleanField() first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) zipcode = models.PositiveIntegerField() furnituretype = models.CharField(max_length=30) repairtype = models.CharField(max_length=30) description = models.TextField() imgfile1 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile2 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile3 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile4 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) imgfile5 = models.ImageField(upload_to='quote_photos/', null=True, blank=True) datetime = models.DateTimeField(auto_now=True) My forms.py: from django import forms from .models import Quote class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ('business', 'first_name', 'last_name', 'email', 'phone', 'zipcode', 'furnituretype', 'repairtype', 'description', 'imgfile1', 'imgfile2', 'imgfile3', 'imgfile4', 'imgfile5') And my view: def quote_view(request): form = QuoteForm(request.POST, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect('/') else: form = QuoteForm() template = loader.get_template('/webapps/my_site/ft_django/main_page/templates/main_page/quote.html') return HttpResponse(template.render({'form': form}, request)) And my template code: <form action="." method="post"> {% csrf_token %} {{ form.as_p … -
ManyToMany through Queryset Django 2.2
I have 3 models and their relation: class Itinerary(models.Model): origin_dest = models.CharField(max_length=200, blank=False, default="") travelers = models.ManyToManyField('Traveler') flights = models.ManyToManyField('Flight') class Traveler(models.Model): pass class Flight(models.Model): pass An Itinerary can has one or many flights (stop vs nonstop) and a flight can belong to more than one itinerary. Also, a traveler can have many itineraries and an itinerary can have many travelers. Here is why: Let's say traveler 1 has a flight from JFK-LAX which has 1 stop in MIA. Then the Itinerary will have 2 flights (JFK-MIA, MIA-LAX). Now let's say we have another person, traveler 2 who has an itinerary from MIA-LAX which is the same flight as traveler 1 going from MIA-JFK (different itinerary instance but same flight shared). Therefore in this case, there are 2 itinerary where a single flight (MIA-LAX) belongs to those two itineraries, hence the ManyToMany relationship. Now what I'd like to do ideally is query all travelers that are a a particular flight through the itinerary model. Somethind like this: flight.itinerary_set.travelers #=> return the number of travelers that are on that specific flight. -
QueryDict does not contain hidden form field, gives MultiValueDictKeyError
I'm trying to integrate Razorpay payment gateway with Django. How do I get the hidden field that Razorpay automatically sends inside my view? checkout/payment_details.html <form action="{% url 'checkout:preview' %}" method="POST"> <!-- Note that the amount is in its subunit value = 599 --> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rzp_test_YYUUnrrBMW42iL" data-amount="{{ order_total_incl_tax_cents }}" data-currency="INR" data-buttontext="Pay with Razorpay" data-name="{{ shop_name }}" data-description="{{ basket.num_items }} items ({{ order_total.incl_tax|currency }})" data-image="https://your-awesome-site.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="test@test.com" data-theme.color="#F37254" ></script> <input type="hidden" value="{{ razorpay_token_form }}" name="razorpay_payment_id"> </form> checkout/views.py class PaymentDetailsView(CorePaymentDetailsView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(PaymentDetailsView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) if self.preview: ctx['razorpay_token_form'] = forms.RazorpayTokenForm(self.request.POST) ctx['order_total_incl_tax_cents'] = ( ctx['order_total'].incl_tax * 100 ).to_integral_value() else: ctx['order_total_incl_tax_cents'] = ( ctx['order_total'].incl_tax * 100 ).to_integral_value() ctx['razorpay_publishable_key'] = settings.RAZORPAY_PUBLISHABLE_KEY return ctx def handle_payment(self, order_number, total, **kwargs): print("requst in handle payment") print(self.request.GET) razorpay_ref = Facade().charge( order_number, total, card=self.request.POST['razorpay_payment_id', False], description=self.payment_description(order_number, total, **kwargs), metadata=self.payment_metadata(order_number, total, **kwargs)) source_type, __ = SourceType.objects.get_or_create(name=PAYMENT_METHOD_RAZORPAY) source = Source( source_type=source_type, currency=settings.RAZORPAY_CURRENCY, amount_allocated=total.incl_tax, amount_debited=total.incl_tax, reference=razorpay_ref) self.add_payment_source(source) self.add_payment_event(PAYMENT_EVENT_PURCHASE, total.incl_tax) stacktrace Traceback (most recent call last): File "C:\Users\kingmaker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\oscar\apps\checkout\views.py", line 580, in submit self.handle_payment(order_number, order_total, **payment_kwargs) File "C:\Users\kingmaker\workspace\blackweb_release_2.0\blackweb_services\checkout\views.py", line 44, in handle_payment card=self.request.POST['razorpay_payment_id', False], File "C:\Users\kingmaker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "('razorpay_payment_id', False)" printing print(self.request.POST) gives <QueryDict: {'csrfmiddlewaretoken': ['jmeHeDEeNhaLM591S4113k1nNiXPLlPOT7eO47pqFyweLRw5al5ldrafTQmM9JPR'], … -
Django model's table doesnt contain PositiveSmallIntegerField
I have the following model in Django: class Priority(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) priority = models.PositiveSmallIntegerField However, when I run makemigrations and migrate, the field priority ( models.PositiveSmallIntegerField) doesn't appear in mysql table and I cannot create object of this model. Why? -
Django Rest Frame Performance of nested model
I profiled my Django App using silk and it turns out that for 200000 db-entries a GET list call takes 701ms in total of which only 36ms are spent on queries (I use prefetch_related and select_related and Pagination) Since I assumed the db-queries would take the most time, I am wondering whether I am doing something wrong since 95% of the time is not spent on queries. My main measurement model is very nested and looks like this class Measurement(models.Model): filetype = models.ForeignKey(Filetype) sensor = models.ForeignKey(Sensor) sensorpositions = models.ManyToManyField('Sensorposition') experiment = models.ForeignKey(Experiment, related_name = "measurementexperiment") data = models.FileField(null=True) and the Frontend expects a detailed nested-json output for every field, so the Serializer does not only return the pk but also all the subfields of the Foreign-models: class MeasurementSerializer(MeasurementSerializer): sensor = SensorDetailSerializer(many=False, read_only=True) sensorpositions = SensorpositionSerializer(many=True, read_only=True) experiment = ExperimentDetailForMeasurementSerializer(many=False, read_only=True) filetype = FiletypeSerializer(many=False, read_only=True) class ExperimentDetailForMeasurementSerializer(ExperimentSerializer): persons = PersonSerializer(many=True, read_only=True) conditions = ConditionSerializer(many=True, read_only=True) location = LocationSerializer(many=False, read_only=True) layout = LayoutSerializer(many=False, read_only=True) So am I simply loosing a lot of time because of the nested serialization or are response times like 701ms normal? -
I am not able to print variable in my emotion.html
I am pretty newbie in python, and I am detecting emotion of music using spotify api, but when I am passing dictionary values to the html, It prints nothing. whereas I am able to print in commandline, When I am writing {{ energy }} It prints nothing when I access localhost:8000//emotion This is my function in views.py def emotion(request): from mutagen.id3 import ID3 from mutagen.mp3 import MP3 import sys import spotipy from spotipy.oauth2 import SpotifyClientCredentials import requests import spotify_token as st import requests client_id = '**********************' client_secret = '*****************************' 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) data = { 'energy' : features[0]['energy'], 'key' : features[0]['key'], 'valence': features[0]['valence'], 'danceability': features[0]['danceability'], 'loundness' : features[0]['loudness'], 'tempo' : round(features[0]['tempo']), 'acousticness' : features[0]['acousticness'], 'liveness' : features[0]['liveness'], 'instrumentalness' : features[0]['instrumentalness'], } print(features[0]['energy']) … -
Django Templatetag can't process double brackets correctly
I currently have a issue with a templatetag at my Django/Python application and i don't really know where/how to start here because i don't see an issue here. I'm unable to process double brackets. Each time a Text is formated with a paragraph/double brackets and this templatetag (see below) is used, the whole text i want to display gets formated wrong, or at least the "more" button get's placed somewhere within the displayed text and not at the very end to enable the expansion. readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '<span class="more" style="display:none;">') words.append('</span>') # insert the readmore part words.insert(showwords, '<span class="readmore">... <a href="#" onclick="') words.insert(showwords+1, readmore_showscript) words.insert(showwords+2, '">more</a>') words.insert(showwords+3, '</span>') # Wrap with <p> words.insert(0, '<p>') words.append('</p>') return mark_safe(' '.join(words)) readmore.is_safe = True thankful for any help BR -
Django progect doesnt work with MySql database
I have settings like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT') } in my main init file i added this lines: import pymysql pymysql.install_as_MySQLdb() I have error like this now: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. I have fouded solution in the stackoverflow, but it is bad solution. Becouse when i to try start my django project in the server, this solution doesnt work( Fuc*ing MySql!!!! -
Django [AssertionError: 401 != 201]
I'm writing tests for my API. Now i want to test post method. Here's my views.py: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = serializers.TaskSerializer authentication_classes = (BasicAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser) Here's my tests.py: class UserFactory(DjangoModelFactory): class Meta: model = User username = 'dima' password = 'moonmvm2k14' email = 'admin@admin.com' is_superuser = True is_active = True is_staff = True class TaskFactory(DjangoModelFactory): class Meta: model = Task title = "TASK N1" description = "smth" person = factory.SubFactory(UserFactory) deadline = date.today() class ViewTest(APITestCase): def setUp(self): self.task = TaskFactory() self.username = 'myuser' self.password = 'test' self.email = 'admin@mgmail.com' self.admin = User.objects.create_superuser(self.username, self.password, self.email) self.client = APIClient() self.client.login(username=self.admin.username, password=self.admin.password) def test_post_task(self): url = '/task-list/' json_tasks = serializers.TaskSerializer(self.task) data = json_tasks.data response = self.client.post(url, data) tasks_count = Task.objects.count() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(tasks_count, 2) But when i try to test it i see this error: AssertionError: 401 != 201 I don't know why my test fails with Not Authorized Status Code. So, what's the problem and how can I solve it? -
How do you make Django's 'Duration Field' into a countdown with Ajax?
I am trying to build a little scorekeeping app as a means to learn how to use Django Rest Framework and Ajax together. I have the API all set up but have come unstuck on the Ajax front. What I am trying to build is a "Start/Pause" button to enable timekeeping. I have got an Ajax script calling the API's "duration" field and I have got a Start/Pause button that changes from Start to Pause. I am missing two things. The first is a way to toggle between "Start" and "Pause". I tried Toggle() but I think I was using it wrong. HTML: <div class="col-4" id="jsonresp"> <button class="start_match btn btn-success">Start Match </button><h5> <lable>Time Left:</lable> <span id="duration"></span></h5> </div> script.js: <script> $('.start_match').click(function () { var url = "{% url 'api:API_Match_Detail' pk=object.id %}"; console.log(url); $.ajax({ url: url, dataType: "json", success: function (data) { var match = data; console.log(match); $('#duration').text(data.duration); $(".start_match").removeClass('btn-success').addClass('btn-danger'); $(".start_match").html("Pause Match"); // this is where I tried $(".start_match").toggle() }, }); }); </script> The second I havent been able to find much infomation on. I'm trying to get the duration field to count down to zero and update the API as it goes as I would like to pull that data out onto … -
Django migrate (revert & reapply) not seen in pgadmin
Using Django 2.2 with PostgreSQL I wanted to test something, having the following model in app named main: class Product(models.Model): .... The migration file for this stage is: 0004_... I made a commit of the current situation to the master branch. Then made a new branch named extra_migrations and checked it out. On the new branch I added an arbitrary field to the Product model: class Product(models.Model): .... some_field = models.CharField(max_length=128, blank=True, null=True) Then I made migrations for this change, and applied the migrations. Migration file for this stage is: 0005_... Then I checked out to the master branch, and did: python manage.py migrate main 0004_.. (revert back to the state i started with in the beginning of this question) Django tells me No migrations to apply, but in the Django admin I don't see the some_field anymore. So I thought maybe VSCode is soing some magic here, haha. This leads to question 1: how come Django is telling me there are no migrations to apply, while there are? After deleting the extra_migrations branch, I decided to check out the database in pgadmin, and there I still see the state of migrations 0005. So I thought I was smart and … -
Listview in vanilla function
I am trying to filter more than one objects from model Offer_description shop = models.ShopProfile.objects.filter(shop_name=pk) shop_offers = models.Offer_description.objects.filter(shop_name=pk) second query is not returning objects rather just names of objects. <QuerySet [<ShopProfile: ShopProfile object (ddd)>]> <QuerySet [<Offer_description: ddd>, <Offer_description: ddd>]> -
Unable to access objects from the html
I am making a django project and want to access the characteristics of a user from within the html but am unable to do so can someone please point the mistake in my code? html <img height="125px" width="125px" class="rounded-circle article-img" src="{{ user1.image.url }}"> <h5 class='pr-2'>{{ user1.user }} </h5> views.py def user_blog_list(request, username): user1=Profile.objects.filter(user__username=username) context={ 'user1':user1 } return render(request,'blog/user_posts.html',context) models.py class Profile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True) description=models.TextField(max_length=200, blank=True) def __str__(self): return f'{self.user.username} Profile' -
How to change Django's template.source to render part of HTML's content
I have a basic Django HTML template: <html> <head>...</head> <body> <div id="products"> <div>Product 1</div> <div>Product 2</div> </div> </body> </html> I have to return only content of div[id="products"] from views.py So, I've tried this in views.py: from django.http import HttpResponse from django.template.loader import get_template from lxml import etree from lxml.html import fromstring def products(request): template = get_template('products/products.html') tree = fromstring(template.template.source) el = tree.xpath('//div[@id="products"]')[0] template.template.source = etree.tostring(el).decode('utf-8') print(template.template.source) // Prints exactly what I need // <div>Product 1</div> // <div>Product 2</div> content = template.render({}, request) print(content) // Prints full rendered products.html's HTML return HttpResponse(content) For sure, page also renders full template It seems that redefinition of template.source does not work So, is it possible to change it somehow? -
Django form text field not displaying
I have used django's models and forms to add a comment section to a blog app, however the form's text field will not show when loaded in the in the browser. Only the submit button loads with no textfield to submit with. models.py from django.db import models from datetime import datetime from django import forms class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField("date published", default=datetime.now()) def _str_(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=100) text = models.TextField(max_length=200) created_date = models.DateTimeField(default=datetime.now()) def _str_ (self): return self.text forms.py from django import forms from django.forms import ModelForm from .models import Comment from django.db import models class CommentForm(forms.ModelForm): class Meta: models = Comment exclude = ['post'] form = CommentForm post.html <div> <div class="container"> <h5>New comment</h5> <form method="POST"> {% csrf_token %} {{ form.as_p }} <br> <button class="btn" style="background-color:lightblue" type="submit">Submit Comment</button> </form> In django's admin i can add new comments and the form loads as expected there but does not work on the blog post itself. Admin submitted comments through the admin panel are also saving and displaying fine.