Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't find img pythonanywhere django
I put the project on both heroku and pythonanywhere and on both platforms there is a problem with the fact that it does not find exactly images. Path to static at pythonanywhere Staic settings in project: STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] -
Multiple Formsets on Same Page Submission through Ajax
So I have two formsets being rendered on the same page, which I intend to submit through AJAX. The problem is whenever I try to submit the forms, I get the error: code='missing_management_form', django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] I've tried changing the prefixes and adding the management form tags in the template but still doesn't change. Here's my forms.py; from .models import Declaration, Spouse, Child from django import forms from django.forms import inlineformset_factory from django.contrib.auth import get_user_model User = get_user_model() class ChildrenForm(forms.ModelForm): class Meta: model = Child fields = ['declarant','surname', 'first_name', 'other_names'] class SpousesForm(forms.ModelForm): class Meta: model = Spouse fields = ['declarant','surname', 'first_name', 'other_names'] SpousesFormSet = inlineformset_factory(User, Spouse, form=SpousesForm, extra=1) ChildrenFormSet = inlineformset_factory(User, Child, form=ChildrenForm, extra=1) And the view: def add_newly_recruited_officers_step_2(request): if request.POST: if request.is_ajax: spousesformset = SpousesFormSet(request.POST, instance=request.user) childrenformset = ChildrenFormSet(request.POST, instance=request.user) if spousesformset.is_valid() and childrenformset.is_valid(): return JsonResponse({'success': "Data Saved Successfully"}) else: return JsonResponse({'error': {'spousesformset': spousesformset.errors, 'childrenformset': childrenformset.errors}}) else: spousesformset = SpousesFormSet(instance=request.user) childrenformset = ChildrenFormSet(instance=request.user) context = { 'spousesformset': spousesformset, 'childrenformset': childrenformset, } return render(request, 'declarations/newly_recruited/form_step_2.html', context) The URL path is: path('add-newly-recruited/step2/', add_newly_recruited_officers_step_2, name='add-newly-recruited-officers-step-2'), And the template: <!-- Form 1--> <form action="{% url 'add-newly-recruited-officers-step-2' %}" method="POST" id="form1"> {% csrf_token %} {{ spousesformset.management_form }} <table … -
Django grouped annotation percentage with a single query
What I'm trying to do is work out the percentage of amount for each weekday, I know how to do it in two queries, but I'm wondering if there is a way to do it in one? For example, if I have the model: class DailyAmount(models.Model): date = models.DateField() amount = models.DecimalField() I can get the percentage amounts for each weekday in two queries like so: total_amount = models.DailyAmount.objects.all().aggregate(total=Sum("amount"))["amount"] result = models.DailyAmount.objects.all().annotate( weekday=ExtractWeekDay("date") ).values("weekday").annotate( percentage=ExpressionWrapper( Sum("amount") * 100.0 / total_amount, output_field=DecimalField() ) ) Is there a way to combine them? I've looked into both Subquery and Window, but I can't get either to quite work and I'm sure I'm missing something. -
Django, how to use filter to check if string field is a substring of a parameter?
I have a model in Django like this - class City: name = models.CharField(max_length=255) Now the below query can filter if the parameter string is a substring of the name field in the City model -- results = City.objects.filter(name_icontains=<some_string>).all() So suppose one of the rows in the database for city table has name = "new york city", so if the give the querystring as "new york", the above filter query will match with it since "new york" is contained in the "new york city". Now after reading the answer to this question -- Django, how to use filter to check if string field is contained in parameter I could solve this by breaking the querystring into words and then applying filter query for each of them. However, how to solve this if my querystring is not two separate words but a long word. Here is an example - Suppose one row for city table contains name as "newyork" and my query string is "newyorkcity", now I can not break the "newyorkcity" querystring into separate words and apply separate filtering. So how can I solve this problem so that when I search for rows matching name as "newyorkcity", it should return … -
Django ORM : model with a list of items from another model
In my Django models, I have two models : one called Site and the other SiteFeature. Object-wise, it is very clear how this should work : every instance of the Site class should have as property a list containing instances of the SiteFeature class, simply because the SiteFeature objects should only exist in relation to a Site object. Database-wise, it is also very clear how it should work : the SiteFeature table should contain a not-nullable column referencing the primary key id column of the Site table, with a foreign key. But in terms of Django ORM, I don't know how to code this. Based on this question, and this other example, it seems the classical way to proceed works the other way round : The Site model class contains no ORM model field referencing the SiteFeature list. Instead, the SiteFeature ORM model class has a ForeignKey field referencing the Site class. I see there is a way to code this out : by adding a function to the Site model class that searches all the related SiteFeature, and make this function a property (decorator @property): @property def site_features(self): return SiteFeature.objects.filter(site_id=site_id) But that leaves me doubts : The proper logic … -
How to load javascript file in django templates
i want to make countdown timer in django website,for that i use javascript.but javascript file is not loading in templates(i also load css file which works fine) countdown.js alert('hello'): index.html {% load staticfiles %} <head> <title>Countdown</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> <link rel="stylesheet" href="{% static 'js/countdown.js' %}"> </head> <body> <p>Hello World</p> </body> setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') -
Nested serializers: Not showing all data
class RacuniizlaznifinancijskiSerializers(serializers.ModelSerializer): pp = PoslovnipartneriSerializers(many=True, read_only=True) class Meta: model = Racuniizlaznifinancijski fields = ('kupacid', 'datumdospjeca', 'pp') I'm getting shown kupacid and datumdospjeca but pp is not showing up. I did this by watching documentation. Not sure what is wrong here... -
Adding extended Profile model into custom user models admin
How can i add extended Profile model fields (fields which are not available in custom user model fields) into custom users admin users.admin? what i am trying to do is that i want too see Profile model fields like photo, date_of_birth, country, phone etc.. inside the Personal Info(see in image) & i can make changes in it from here. profile model from django.db import models from django.dispatch import receiver from django.urls import reverse from django.db.models.signals import post_save from django.contrib.auth import get_user_model # or from users.models import User User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) phone = models.IntegerField(null=True, blank=True) country = models.CharField(max_length=150, null=True, blank=True) city = models.CharField(max_length=150, null=True, blank=True) bio = models.TextField(max_length=150, null=True, blank=True) def __str__(self): return str(self.user.email) def get_absolute_url(self): return reverse('profiles:profile-detail', kwargs={'pk':self.pk}) def post_save_user_model_receiver(sender, instance, created, *args, **kwargs ): # when a user is created(custom user model)like signup or through admin it will create those user's profile too if created: try: Profile.objects.create(user=instance) # it create those user's profile except: pass post_save.connect(post_save_user_model_receiver, sender=User) users.admin from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth import get_user_model # or from .models import User from .forms import … -
Waiting for result of celery task in 2 places get stuck
I'm using Django, Celery and Redis to execute tasks. # tasks.py @shared_task def my_task(): time.sleep(5) # Do stuff return True I call this task in 2 differents places in the application : # test1.py task = my_task.delay() result = task.get() print(result) # Shows True after 5 seconds # test2.py task = AsyncResult(my_task_id) print(task.status) # Shows pending print(task) # Shows the right id result = task.get() # Get stuck here print(result) # This line never appears in console Of course, script in test1.py is called before test2.py. And I'm sure that id is correct. I don't have any messages in celery's log or in Django. It just get stuck. I already tried solutions described here : Retrieve task result by id in Celery -
Django: problem with french date format with datepicker
I use JQuery datepicker but have an error with date (Enter a valid date). My web browser (Firefox) is in French. I want date to be displayed in french format dd/mm/aaaa but initial values (timezone.now() is yyyy-mm-dd because of settings.py if I am right. In a precedent project, it works so I don't know why it doesn't works here. My JS script should do the job Settings.py LANGUAGE_CODE = 'en-us' forms.py self.fields["ran_dem_dat"] = forms.DateField( label = "Date of demand", initial = timezone.now(), required = False, ) self.fields['ran_dem_dat'].widget.attrs.update({ 'autocomplete': 'off' }) JS $(function(){ if(window.navigator.language.slice(0, 2) == 'fr'){ $("#id_ran_dem_dat").datepicker( { dateFormat: 'dd/mm/yy', } ); } else { $("#id_ran_dem_dat").datepicker( { dateFormat: 'yy-mm-dd', } ); } }); -
AWS CodeDeploy Error "The revision size is too large. Its maximum size is 51200B"
I am trying to deploy a Django web app on AWS. I use Jenkins for CI and CodeDeploy plugin to deploy my builds to AWS CodeDeploy. Jenkins works fine and I see "FINISHED:SUCCESS" after the build is finished. But when I navigate to my AWS CodeDeploy console I see an error message: "The revision size is too large. Its maximum size is 51200B." I have added the appspec.yml file to the root directory of my project, but it did not help. appspec.yml version: 0.0 os: linux files: - source: / destination: /home/ubuntu/wamsport/ permissions: - object: /home/ubuntu/wamsport pattern: "**" owner: ubuntu group: ubuntu -
Django: Combine multiple instances of a model (add multiple items to a car/set)
I have a parts model and I want to create a product that consists of multiple parts - but I want to do it on one HTML page: class Part(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price per part", decimal_places=2, max_digits=6) class PartRelation(models.Model): basis = models.ForeignKey(Part, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") class Product(models.Model): name = models.CharField('Name', max_length=120) parts = models.ManyToManyField(PartRelation) I created a simple form: class PartForm(ModelForm): required_css_class = "required" class Meta: model = PartRelation fields = "__all__" and a simple view: def add_part(request): submitted = False if request.method == "POST": form = PartForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/add_part/?submitted=True") else: form = PartForm() if "submitted" in request.GET: submitted = True return render(request, "gap/add_part.html", {"form": form, "submitted": submitted}) and a simple HTML page: {% block content %} {% if submitted %} <p class="success">Part was saved successfully.</p> {% else %} <form action="" method="post" novalidate> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} So I want to give the product a name and then assign multiple items to it. By clicking + a new line with the dropdown should appear and a new quantity can be entered. Bonus Question: How … -
NoReverseMatch at /password-reset-complete/ for Password Reset in Django
I have error "Reverse for 'login' not found. 'login' is not a valid view function or pattern name." But 'login' by it self works fine. I get reset link to email, after that I set up new password and on the last step I get this strange error. There is no success_url for PasswordResetCompleteView, so I can't change it ether. Error: NoReverseMatch at /password-reset-complete/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/password-reset-complete/ Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Exception Location: /Users/m/PycharmProjects/online_store_fp/venv/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /Users/m/PycharmProjects/online_store_fp/venv/bin/python Python Version: 3.7.3 Python Path: ['/Users/m/PycharmProjects/online_store_fp/online_store_fp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/m/PycharmProjects/online_store_fp/venv/lib/python3.7/site-packages', '/Users/m/PycharmProjects/online_store_fp/venv/lib/python3.7/site-packages/setuptools-40.8.0-py3.7.egg', '/Users/m/PycharmProjects/online_store_fp/venv/lib/python3.7/site-packages/pip-19.0.3-py3.7.egg'] urls.py from django.contrib import admin from django.urls import path, include, reverse_lazy from django.conf import settings from django.conf.urls.static import static from accounts import views as user_views from django.contrib.auth import views as auth_views urlpatterns = [ path('', include('accounts.urls')), path('products/', include('products.urls')), path('admin/', admin.site.urls), path('signup/', user_views.signup, name='signup'), path('user/', user_views.user, name='user'), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name="logout"), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html', email_template_name='accounts/password_reset_email.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( … -
Django Wagtail TableBlock not displaying correctly
I'm new to django and programming and I've been trying to use Wagtail for my website. I am currently stuck with the 'TableBlock' I managed to set up the model and the block correctly but when the html is rendered, i'm not getting a table but rather a dictionary. here is my code: {% for block in page.table %} {% if block.block_type == 'table_horaire' %} {% include_block block %} {% else %} <p>This is not working</p> {% endif %} {% endfor %} And this is what I get on the Html {'data': [['Jour', 'Matin', 'Après-midi', None], ['Lundi', '9.00-12.00', '14.00-17.00', None], ['Mardi', '9.00-12.00', '14.00-17.00', None], ['Mercredi', '9.00-12.00', 'Fermé', None], ['Jeudi', '9.00-12.00', '14.00-17.00', None], ['Vendredi', '9.00-12.00', '14.00-17.00', None]], 'cell': [], 'first_row_is_table_header': True, 'first_col_is_header': False, 'table_caption': 'Horaires'} here is my model class HomePage(Page): body = RichTextField(blank=True) table = StreamField( [ ('table_horaire', blocks.TableHoraire()) ], null=True, blank = True, ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), StreamFieldPanel('table') ] and here is my block from wagtail.core import blocks from wagtail.contrib.table_block.blocks import TableBlock new_table_options = { 'minSpareRows': 0, 'startRows': 6, 'startCols': 4, 'colHeaders': False, 'rowHeaders': False, 'contextMenu': True, 'editor': 'text', 'stretchH': 'all', 'height': 216, 'language': 'en', 'renderer': 'text', 'autoColumnSize': False, } class TableHoraire(blocks.StructBlock): """ Home Page … -
Django use automatic search field filtering from another viewset
I have 2 different viewsets StoreViewSet and ShowcaseViewSet. In my StoreViewSet, I have: search_fields = ['name_search', 'address__address1_search', 'address__postcode', 'address__city_search', 'address__country'] When I GET on my StoreViewSet I can pass search parameter like this: /api/x?search=mysearch And it automatically filter on the search fields, this is great. Now I made a custom method in ShowcaseViewSet that call: stores = Store.Objects.all() Here I need a way to call the automatic StoreViewSet filtering and pass him the "request" with the search parameter. This custom method need to remain in the ShowcaseViewSet to maintain a correct rest url. What can I do here to solve my problem ? -
django ajax syntax error missing missing ] after element list2 book [ opened at line 11, column 0
hello guys i am trying to make self generate table using ajax and i got this error when the script trying to append the table every 10 second can anyone help me? this is my script in static/js/book.js $(document).ready(function () { console.log("loaded"); var updateTable = $.ajax({ method: "GET", url: "get_more_table", success: function(data) { console.log(data) $("#_appendHere").append(data) } }); setInterval(updateTable,10000); }); my view def record_table(request): dest = Destination.objects.all() return render(request,"destination.html",{'dest':dest}) def get_more_table(request): dest = Destination.objects.all() return render(request,"get_more_table.html",{'dest':dest}) destination.html <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>name</th> <th>desc</th> <th>status</th> <th>price</th> </tr> {% for i in dest %} <td>{{ i.name|upper }}</td> <td>{{ i.desc|capfirst }}</td> <td>{{ i.status|capfirst }}</td> <td>{{ i.price | capfirst}}</td> </tr> {% endfor %} </table> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script> <script src="{% static 'js/book.js' %}"></script> get_more_table.html {% for i in dest %} <td>{{ i.name|upper }}</td> <td>{{ i.desc|capfirst }}</td> <td>{{ i.status|capfirst }}</td> <td>{{ i.price | capfirst}}</td> </tr> {% endfor %} </table> my error: SyntaxError: missing ] after element list2 book.js:11:8note: [ opened at line 11, column 0 -
DJANGO ! make verification_code available only for 1 hour
So basicaly when a user register , i put the is_active=False i generate a verification_code and i send it within an email , but i want that verification_code to be used within 1Hour otherwise verification_code is set to null to my database email=email, age=age, gender=gender, phone_number=phone_number, city=city, is_active=False occupation=occupation,) user_obj.set_password(password) user_obj.save() activation_link = 'http://127.0.0.1:4200/' + random_string(200) subject = 'Confirm email' from_email = EMAIL_HOST_USER to = [email,] html_message = render_to_string('forget_password.html', {'activation_link': activation_link}) text_message = strip_tags(html_message) msg = EmailMultiAlternatives(subject, text_message, to=to, from_email=from_email) msg.attach_alternative(html_message, "text/html") msg.send() return Response("Mail sended", status=status.HTTP_200_OK)``` -
connect() to unix:/var/uwsgi/salesproject.sock failed (111: Connection refused)
Okay guys, so this is the error I'm stuck on for days.I am trying to get my django+nginx+uwsgi work properly but it's been 3 days and it's still not working, I tried a lot,rebuilded by server,tried python2 and 3 and blah blah blah but the error I hook on is the one above. Here's my uwsgi file [uwsgi] project = salesproject base = /home/ubaid logto = /var/log/uwsgi/error.log chdir = %(base)/%(project) chmod-socket= 777 plugins = python3 wsgi-file = %(project)/wsgi.py master = true processes = 2 socket = /var/uwsgi/%(project).sock virtualenv = %(base)/%(project)/venv vacuum = true uid = www-data gid =www-data Here's my Nginx conf located in /etc/nginx/sites-available/ server { listen 80; server_name 72.14.184.213; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubaid/salesproject; } location / { include uwsgi_params; uwsgi_pass unix:/var/uwsgi/salesproject.sock; } } Now see how the problem unfolds in steps, First when I go to my website, 1.It gives me an error like this connect() to unix:/home/ubaid/var/uwsgi/salesproject.sock failed (2: No such file or directory) Then I manually make the .sock file by sudo nano .sock so when I run my website,It gives me an error like this connect() to unix:/var/uwsgi/salesproject.sock failed (13: Permission denied) Then to resolve … -
Django ordering search results from get_queryset(self)
I am using django 2.2.10. I have a searchbar which returns search results to the showpage, using get_queryset(self) in searchresultsview(listview) class. I have set paginate_by=10. In the front-end I made links to order the table: ` <th>Title original <a href="?order_by=title_original&direction=asc" class="arrow up"></a> <a href="?order_by=title_original&direction=desc" class="arrow down"></a></th> At the start of the get_queryset(self) function I have the following code: order_by = self.request.GET.get('order_by') direction = self.request.GET.get('direction') if order_by is not None and order_by != "" and direction is not None and direction != "": ordering = Lower(order_by) if direction == 'desc': ordering = '-{}'.format(ordering) publications = Publication.objects.filter(is_deleted=False).order_by(ordering) ''' paginator = Paginator(publications, 10) page = self.request.GET.get('page') try: all_publications = paginator.page(page) except PageNotAnInteger: all_publications = paginator.page(1) except EmptyPage: all_publications = paginator.page(paginator.num_pages) ''' return publications The main problem is that the publications variable contain all publications, I want to restrict it to the publications from the previous get_queryset(self) call. Also the showpage is paginated (paginate_by = 10 in template).The ordering for descending does not work I get: invalid order_by arguments: ['-Lower(F(title_original))'] . If I order ascending it logically does not keep my search results. I tried finding a stackoverflow solution but the explanation is minimal. Any help would be appreciated. -
How to migrate the OSTree plugin form Pulp2 to Pulp3?
Does anyone made some experience in migrating OSTree from Pulp2 to Pulp3? I need to get OSTree working under the newer Pulp3. I would be glad if anyone could share his experience and maybe tell me what I need to look for in order to accomplish my task. -
Is it somehow possible to create a popup window rendering a django tables2 table
I have a django tables2 table. I want to show this table in a popup window when the user clicks a button. Is it somehow possible? Something similar can be accomplished with fm modal forms https://github.com/django-fm/django-fm but for rendenring a form not a table. -
Filtering on foreignkey properties doesn't filter out the foreignkey objects
I have Equipment that can be booked (Bookings). But I don't want to show the bookings from the past. queryset = Equipment.objects.filter(bookings__start_date__gte=datetime.now().date()).distinct() But this query still contains all the bookings that have startdates in the past. Any ideas? -
Show submitted form parameters in URL in Django
I have a form in home page and I want to add the submitted form parameters to the home url after getting back the response from the backend. I want it to be shown without any parameters on loading the page first time. How can I do that? home.html <form class="choices_select_form" method="POST" action="{% url 'home' %}"/> {% csrf_token %} <div class="cities_dropdown"> <select name = "city"> {% for citiy in cities %} <option value="{{ citiy.id }}" {% if city.name == citiy.name %} selected="selected" {% endif %}> {{ citiy.name }} </option> {% endfor %} </select> </div> <div class="profession_fields_dropdown"> <select name = "profession_field"> {% for key, value in profession_fields %} <option value="{{ key }}" {% if profession_field == key %} selected="selected" {% endif %}> {{ value }} </option> {% endfor %} </select> </div> <div> <input type="submit" value="Search" /> </div> </form> <div>{{ users }}</div> views.py def home(request): if request.method == 'POST': city_id = request.POST.get('city') city = City.objects.get(pk=city_id) company_field = request.POST.get('company_field') users = User.objects.filter(is_staff=False, userprofile__city=city, userprofile__profession_field=profession_field) else: if request.GET.get('city') and request.GET.get('profession_field'): city_id = request.GET.get('city') city = City.objects.get(pk=city_id) profession_field = request.GET.get('profession_field') users = User.objects.filter(is_staff=False, userprofile__city=city, userprofile__profession_field=profession_field) else: city = City.objects.get(pk=1) profession_field = 'DF' users = User.objects.filter(is_staff=False, userprofile__city=1, userprofile__profession_field=profession_field) cities = City.objects.values('id', 'name') profession_fields = CompanyProfile.PROFESSION_FIELDS paginator … -
Django ListView dynamic context data
Given my models: class Deck(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Flashcard(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) deck = models.ForeignKey(Deck, on_delete=models.CASCADE) question = models.TextField() answer = models.TextField() In my html template, I want to have a table of all the user's decks, each with their number of cards, e.g. like this: Deck1: 15 Deck2: 22 Deck3: 100 In my views I have: def get_context_data(self,**kwargs): context=super(generic.ListView,self).get_context_data(**kwargs) context['number_decks']=Deck.objects.filter(owner=self.request.user).count context['number_cards']=Flashcard.objects.filter(owner=self.request.user,deck__name="Deck1").count number_decks works as expected. number_cards also works when I manually type the name in. But how can I do this without specifying the name, so that in the html template I can just say: {% for deck in deck_list %} <td>{{deck.name}}</td> <td>{{number_cards}}</td> And since I won't know the names of the decks that users will create. I've tried deck__id=deck.id, but I get zeroes. How can I change either my models or views to get what I want? -
Django File Upload form: if request.method=="POST" fails
So I am trying to implement file upload to my website. It is something I have done before but right now in my views the form does not pass the if request.method=="POST" line. Here is my code: settings.py: ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py: urlpatterns=[ ... path('filepost/', views.filepost, name='filepost') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py ... class File(models.Model): user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='files', null=True) file=models.FileField(upload_to='files/') forms.py ... class FileForm(forms.Form): file=forms.FileField(label='') home.html: ... <form action="{%url 'filepost'%}" method="post" enctype="multipart/form-data"> {%csrf_token%} {{fileForm}} <button type="button">Post File</button> </form> views.py: ... def filepost(request): form=FileForm() if request.method=='POST': print(1) form=FileForm(request.POST, request.FILES) if form.is_valid(): file=request.FILES['file'] newupload=File(user=request.user, file=file) newupload.save() return redirect('../') I have the print(1) in the views to check if it gets past the if request.method=="POST" line but it doesn't print 1 so I am guessing that this line is the problem. Any ideas? Thanks!