Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Random - order_by('?')
When you make queryset in Django, argument "?" for order_by returns queryset in random order Model.objects.order_by('?') Documentation warns, that it may be slow. Also many articles tell not use this method for big database. I know question will sound dumb, but what is database limit size in order to user order_by efficiently? How many objects may I have in my database before order_by will get slower? Or this is all up to machine specs? -
Handle multiple parameters from URL in Django
In my app I am trying to make query on multiple parameters from the URL which is something like the following: /allot-graph/?sc=Infac%20India%20Pvt.ltd&type=FLC there are 2 parameters sc and type at times they can be empty as well I was handling the single parameter like the following: class AllotmentbyMonth(APIView): def get(self, request): q = 0 try: q = request.GET['sc'] except: pass if q == 0: print("q", q) dataset = Allotment.objects.all().annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c') else: print("q") client = Client.objects.filter(client_name = q)[0].pk print("client", client) dataset = Allotment.objects.filter(sales_order__owner=client).annotate( month=TruncMonth('dispatch_date')).values( 'month').annotate(c=Sum('flows__alloted_quantity')).values('month', 'c') date = list(dataset) months = list() for i in date: months.append(i['month'].strftime("%B")) chart = {'chart': {'type': 'column', 'height': 400}, 'title': {'text': 'Allotments by Months'}, 'xAxis': {'categories': months}, 'yAxis': {"title": {"text": 'Count'}}, 'series': [{'name': 'Months', 'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]}]} print("chart", chart) return Response(chart) I know it's not the ideal way but this was my workaround. How can I handle the filter type in this as writing too many if-else just doesn't seem right. The filter for type is this : .filter(flows__kit__kit_type = type) -
How to do Django pagination without page reload?
I am displaying questions with options in template page. on click next and previous i am getting questions with options. because of page reload user selected option is loosing. How to solve this problem. I am new to Ajax. I posted my script below. views.py: def render_questions(request): questions = Questions.objects.all() p = Paginator(questions, 1) page = request.GET.get('page', 1) try: page = p.page(page) except EmptyPage: page = p.page(1) return render(request, 'report.html', {'ques': page}) template.html: <div class="row display-content"> <div class="col-lg-8"> <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} {% for question in ques %} <h6>Q &nbsp;&nbsp;{{ question.qs_no }}.&nbsp;&nbsp;<input type="hidden" name="question" value="{{ question.question }}">{{ question.question }}</h6> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_a}}">&nbsp;&nbsp;&nbsp;A)&nbsp;&nbsp;{{ question.option_a }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_b}}">&nbsp;&nbsp;&nbsp;B)&nbsp;&nbsp;{{ question.option_b }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_c}}">&nbsp;&nbsp;&nbsp;C)&nbsp;&nbsp;{{ question.option_c }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_d}}">&nbsp;&nbsp;&nbsp;D)&nbsp;&nbsp;{{ question.option_d }}</label> </div> {% endfor %} <ul class="pagination"> {% if ques.has_previous %} <li><a href="?page={{ques.previous_page_number}}" class="button">Previous</a></li> {% else %} <li class="disabled button">Previous</li> {% endif %} {% if ques.has_next %} <li><a href="?page={{ques.next_page_number}}" class="button">Next</a></li> {% else %} <li class="disabled button">Next</li> {% endif %} <input type="submit" value="Submit" onclick="submitTest()" class="button"> </ul> </form> </div> </div> script: $(document).ready(function(){ $("ul.pagination a").click(function() { $.ajax({ type: "GET", url: $(this).attr('href'), success: … -
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper in Django BaseCommand
I work on learning to create a custom command to rename the project of Django boilerplate. Below snippets lives in appname/management/commands/rename.py extending from BaseCommand. from django.core.management.base import BaseCommand import os class Command(BaseCommand): help = 'Rename project' def add_arguments(self, parser): parser.add_argument('new_project_name', type=str, help='The new project name') def handle(self, *args, **kwargs): new_project_name = kwargs['new_project_name'] files_to_rename = ['demo/settings/base.py', 'demo/wsgi.py', 'manage.py'] folder_to_rename = 'demo' for file in files_to_rename: with open(file, 'r') as file: filedata = file.read() file.close() filedata = filedata.replace('demo', new_project_name) with open(file, 'w') as file: file.write(filedata) os.rename(folder_to_rename, new_project_name) self.stdout.write(self.style.SUCCESS( 'Project has been renamed to %s' % new_project_name)) while running python manage.py rename newprojectname I get the below error: File "D:\GitHub\django-boilerplate\src\core\management\commands\rename.py", line 30, in handle with open(file, 'w') as file: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper For me it sounds like open function looks for a string, albeit I already passed that list of string to it. The file is also closed in read only part through with. How I am getting this error? any help please? Thank you -
django objects filtering according to date
lately I have faced this situation in Django and can not understand clearly why there is difference between these 2 kind of queries is anybody could help me to understand it, thank you >>> date datetime.datetime(2020, 11, 1, 0, 0) >>> Contract.objects.filter(deadline_on__gt=date).count() 220 >>> Contract.objects.filter(deadline_on__month__gt=10, deadline_on__year__gt=2019).count() 30 >>> -
I am trying to do Django authentication with Facebook. I have an extended User model in my application which has a required fullname field
I am using the social_django application. How do I combine first_name and last_name received from Facebook and put them in the fullname attribute. Error : TypeError at /social-auth/complete/facebook/ create_user() missing 1 required positional argument: 'fullname' The error message The attribute in etended model : fullname = models.CharField(max_length=255, verbose_name='Fullname') Requested fields : SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] -
Django Rest Frawork: Where to put logic that modifies database?
I have a Django project using the Rest Framework. In some view I'm trying tu execute some logic every time I call these views, but it works when I have an existing Database. If I have to do a migrate to create a new Database it gives me the error django.db.utils.OperationalError: no such table: bar_reference because I don't have any Database. So I understand it's not the right way to do it, but so how/where should I execute this logic? Here is my view: from rest_framework import viewsets from rest_framework import permissions from rest_framework.permissions import AllowAny from ..models.reference import Reference from ..models.stock import Stock from ..models.bar import Bar from ..serializers.reference import * class MenuViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] references = Reference.objects.all() bars = Bar.objects.all() for reference in references: ref_id = reference.id quantity = 0 for bar in bars: bar_id = bar.id stocks = Stock.objects.filter(ref_id=ref_id, bar=bar_id) for stock in stocks: quantity += stock.stock if quantity == 0: reference.availability = "outofsotck" reference.save() else: reference.availability = "available" reference.save() queryset = Reference.objects.order_by('id') serializer_class = MenuSerializer -
in django each database should have superuser?
i am using MongoDB for database. i am working on Django to create app similar to-do app and try to create two databases. by default Django create some collections and to create super user for each databases -
configuring django with nginx gunicorn on docker
Good day, i am new to docker and i have a django app i will like to dockerize , i have searched for tutorials to help me setup my django app with docker, i followed this article here on testdriven https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/. i get issues making nginx work with my app. here is my code. my apps docker file: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app COPY ./testdocker /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user nginx docker file: FROM nginx:1.19.3-alpine RUN rm /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d RUN mkdir -p /vol/static my docker-compose file: version: '3.7' services: app: build: context: . command: sh -c "gunicorn testdocker.wsgi:application --bind 0.0.0.0:8000" volumes: - static_data:/vol/web expose: - "8000" environment: - SECRET_KEY=MANME1233 - ALLOWED_HOSTS=127.0.0.1, localhost nginx: build: context: ./nginx volumes: - static_data:/vol/static ports: - "8080:80" depends_on: - app volumes: static_data: my nginx conf file: upstream testapp { server app:8000; } server { listen 8080; server_name app; location / { proxy_pass http://testapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static … -
why media queries is not working with django css styling?
Below is the HTML tag <div class="logo"> <img src="{% static 'img/sunil.png' %}" id="logo" alt=""> </div> STYLE.CSS what i have done in css file is below: #logo { height: 60px; width: 120px; } @media only screen and (max-width: 500px) { .logo { height: 20px; width: 60px; } } I tried to change the image size using media queries but it is not working. style.css is connected in main file because when I use #logo and changed height and width then its working but when I try in media queries then it's not working. -
Handling Exceptions in Python Django Crispy Forms
I'm new in Python 3.8.2/Django 3.1.1, and I'm trying to figure out the correct way to add rules to models so they can be called from forms and web services, the issue I have is that some errors are not properly caught and they are generating an 500 Error. This is my initial Model: class TotalPoints(TimeStampedModel): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='TotalPoints_Course', null=False, blank=False, verbose_name='Curso') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='TotalPoints_Kit', null=False, blank=False, verbose_name='Kit') bought = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Comprados') assigned = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Asignados') available = models.PositiveIntegerField(default=0, null=False, blank=False, verbose_name='Disponibles') class Meta: db_table = 'app_totalpoints' constraints = [ models.UniqueConstraint(fields=['course','kit'], name='app_totalpoints.course-kit') ] fields are declared PositiveIntegerField to avoid negative values this is my Form and CreateView class TotalPointsForm(forms.ModelForm): class Meta: model = TotalPoints fields = ['id', 'course', 'kit', 'available', 'bought', 'assigned'] class TotalPointsCreateView(CreateView): model = TotalPoints form_class = TotalPointsForm template_name = 'app/form_base.html' success_url='../list/' and this is my template: {# app/templates/app/form_base.html #} {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head lang="es"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <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="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"> <title>{% block page_title %}{% endblock %}</title> </head> <body> <div class="container-fluid"> <div class="jumbotron"> <h1 class="display-4">{% block form_title %}{% endblock %}</h1> <p class="lead">{% block form_subtitle %}{% … -
Django: How to save pdf file from PdfFileMerger
What wrongs this code? I want to save the file to the field's model 😭😭 obj = Document.object.first() merger = PdfFileMerger() for pdf in [page_1, page_2]: merger.append(pdf) merger.write(f'{str(uuid.uuid4())}.pdf') merger.close() obj.pdf = merger obj.save() -
Django admin list_display of different data types with null
I know I explained the title poorly, look I have a simple chat app where users can send text/audio/video/image and for me to render those messages I have a method that checks the type of the message and renders it accordingly if it was text then i will set safe to False in my template, else I will display what the function will give me which is an HTML code What I really want is: Admin panel giving me message text[:50] if it was text, if it was audio then i can have an audio preview for it, if it was image or video or file then it will give me the url. Is there anyway to do so? here are my files so you can get a better understanding of what I'm saying: models.py: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) text = models.TextField(blank=True, null=True) video = models.FileField(upload_to="chat/room/vid", blank=True, null=True) image = models.FileField(upload_to="chat/room/img", blank=True, null=True) file = models.FileField(upload_to="chat/room/file", blank=True, null=True) audio = models.FileField(upload_to="chat/room/aud", blank=True, null=True) is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) def content(self): if self.text: return self.text elif self.video: return f""" <video width="320" height="240" controls> <source src="{self.video.url}" type="video/mp4"> <source src="{self.video.url}" type="video/mov"> <source src="{self.video.url}" type="video/wmv"> <source src="{self.video.url}" … -
SendGrid Mail send is not working in my django rest-api view
I tried to add the send mail using sendgrid in my django & react project, but it is not working. My code in backend api view is like following: def send_invitation(request): if request.method == 'POST': TO_EMAILS = [('my email@gmail.com', 'My fullname'), ] FROM_EMAIL = 'my another email' TEMPLATE_ID = 'send-grid template id' message = Mail( from_email=FROM_EMAIL, to_emails=TO_EMAILS) message.dynamic_template_data = { 'subject': 'SendGrid Development', 'place': 'New York City', 'event': 'Twilio Signal' } # message.add_filter('templates', 'enable', '1') message.template_id = TEMPLATE_ID try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) code, body, headers = response.status_code, response.body, response.headers print(f"Response code: {code}") print(f"Response headers: {headers}") print(f"Response body: {body}") print("Dynamic Messages Sent!") return Response({'message': 'Your Invitation is sent successfully!'}) except Exception as e: print("Error {0}".format(e)) return Response({'error': 'Your Invitation is failed to send!'}) I already add the SENDGRID_API_KEY in the .env file of my django backend, and installed the sendgrid using pipenv. The error is like this; Error HTTP Error 403: Forbidden Please let me know if the description is not enough. -
How to serve static_files in django?
Basically, I am practising an E-commerce project of Django. There are two ways of adding images. ( 1 ) - First is that someone adds the photos manually but I want users to add a photo of the product automatically via static files. models.py: from django.db import models # Create your models here. class Mobile(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Samsung') def __unicode__(self): return 'This is a mobile' def get_price(self): return self.price class MobileImage(models.Model): device = models.ForeignKey(Mobile, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images/') def __unicode__(self): return self.device class Laptop(models.Model): brand = models.CharField(max_length=30) price = models.IntegerField(default=1) color = models.CharField(max_length=30) screen_size = models.IntegerField(default=5) os = models.CharField(max_length=30, default='Dell') def __str__(self): return self.brand my views.py: def mobile(request): mobiles = Mobile.objects.all() context = { 'mobiles': mobiles } return render(request, 'device/mobile.html', context) def laptop(request): laptops = Laptop.objects.all() context = { 'laptops': laptops } return render(request, 'device/laptop.html', context) my mobile.html: {% extends 'device/base.html' %} {% load static %} {% block body %} <h1>Mobile!</h1> <!-- Table --> <table class=""> <tr> <h3>Phones:</h3> <th>ID</th> <th>Model</th> <th>Price</th> <th>Color</th> <th>Screen Size</th> <th>OS</th> <th>Image</th> </tr> <body> {% for mobile in mobiles %} <tr> <td>{{ forloop.id }}</td> <td>{{ mobile.brand }}</td> <td>${{ mobile.price }}</td> <td>{{ mobile.color }}</td> … -
Django Insert data or update
if the user inserted data with the same day his inserted his account the record will updated, and if the user insert data tomorrow or following day it will insert. I just want that only 1 data will insert everyday this is my views.py insert_1tab, created = TrCustomerEmployeeSupplierSubmittedRecords( fmCustomerID=company, fmCustomerLocationID = location, firstname=firstname, lastname=lastname, middleInitial=middlename, bodyTemperature=temperature, fmCustomerSectionID = sections, employee_number=employeno, contactNumber=cnumber, address=tirahan, ) if not created: insert_1tab.save() this is my models.py class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): fmCustomerID = models.ForeignKey('FmCustomer', null=True, blank=True, verbose_name="Customer") fmCustomerLocationID = models.ForeignKey('FmCustomerLocation',null=True, blank=True, verbose_name="CustomerLocation") dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) firstname = models.CharField(max_length=500, blank=True) middleInitial = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) bodyTemperature = models.FloatField() fmCustomerSectionID = models.ForeignKey('FmCustomerSection', null=True, blank=True, verbose_name="CustomerSection") employee_number = models.CharField(max_length=500, blank=True, null=True) contactNumber = models.CharField(max_length=500, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) email = models.CharField(max_length=500, blank=True, null=True) -
Django url error ( Redirecting to another url)
I have been learning django and i am having a problem with the url patterns. i have the project urls.py as follows: urlpatterns = [ path('', include('app.urls')), path('accounts/', include('accounts.urls')), path('data/',include('data.urls')), path('admin/', admin.site.urls), ] and i have "accounts app" urls.py as follows: urlpatterns = [ path("register", views.register, name="register") ] views.py of accounts app: def register(request): return render(request,'register.html', {'title' : 'User Registration | Django'}) Basically my data app contains country, state and district models. i have "data app" urls.py as follows: urlpatterns = [ path("country", views.country, name="country"), path("state" , views.state, name="state"), path("district", views.district, name="district") ] views.py of data app: def country(request): if request.method == "GET": if request.is_ajax(): obj_country_list = Country.objects.values("id" , "country") return HttpResponse(json.dumps(list(obj_country_list))) My error was when trying to access the "data/country url" inside the "register.html" page & the javascript function for fetching the is as follows: function Country(){ $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: "data/country", //data: "{}", dataType: "json", success: function (Result) { $.each(Result.d, function (key, value) { $("#ddlcountry").append($("<option></option>").val(value.id).html(value.country)); }); }, error: function (Result) { alert("Error in invoking the function"); } }); } I tried to inspect the page & the url it was trying was accounts/data/country. When tried to change the url inside the header while inspecting the … -
Calling URL in Django and get output in Django screen
I am a beginner to Django and flask I want to invoke a URL from my flask and print the output in Django screen views.py def hello(request): your_name = request.GET.get('your_name') if not your_name: your_name =0 respons = requests.get('http://127.0.0.1:5000/' + str(your_name)).json( return render(request, 'hello/index.html', {'msg': respons['msg']}) index.html <form action ="/hello/" method="get"> <label for ="your_nname">Your number: </label> <input id="your_name" type="text" name="your_name" value="0"> <input type ="submit" value="OK">. in flask I want to create a get method with hello & 'name' I am getting error in my code -
How to add comments with ajax in django website?
How can I add comments in my Django website without refreshing the page? Here are my codes: VIEW.PY @login_required def comments(request, post_id): """Comment on post.""" post = get_object_or_404(Post, id=post_id) user = request.user comments = Comment.objects.filter(post=post).order_by('-date')#comment if request.method == 'POST':#Comments Form form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.user = user comment.save() messages.success(request, 'Comment has been added successfully.') return HttpResponseRedirect(reverse('core:comments',args=[post_id])) else: form = CommentForm() template = loader.get_template('post/comments.html') context = {'post':post,'form':form,'comments':comments,} return HttpResponse(template.render(context, request)) COMMENTS.HTMl Form section: <div class='commentsection' > <strong> <form action="{% url 'core:comments' post.id %}" method='post' id=comment-form > {% csrf_token %} {% bootstrap_form form %} </form> <br/> <br/> </strong> </div> Comments section: {% for comment in comments %} <div class="card mb-3" style="width: 30rem;"> <div class="row no-gutters"> <small> <a style="color: black;" href="{% url 'core:user_profile' comment.user %}"><img src="{{comment.user.profile.profile_pic.url}}" width=50 height=50 class="profile-image img-circle " style="object-fit: cover; float: auto; "><strong style="font-size: 18px;" > @{{comment.user}} </strong></a> </small> <small><span class="glyphicon glyphicon-time"></span> {{ comment.get_date }}</small> </div> <div class="card-body" style="width:100%; padding-left:20%; margin-top:-8%; word-break: break-all; color:black; " > <h5 class="card-text"> {{ comment.comment }}</h5> <small ><a href="{% url 'core:replies' comment.id %}"> Replies </a> [{{comment.total_replies}}] </small </div> </div> </div> <br/><br/> {% empty %} <center> No commnets </center> {% endfor %} My problems: 1] Add comments without refreshing … -
Write BaseSerializer to prevent Stored XSS in Djano
How can we prevent stored xss in Django API's, basically every Text/Char Field should be cleaned. Can we write a Base Serializer using DRF to prevent the attack. Does Django really need to use XSS safe mechanism or it does not effect anything as Django uses ORM for queries? We can use validate_<field_name> method in serializer but that is not a generic solution. Other than bleach can we have a built-in solution -
Can I dynamically place items in two-column template in Django?
The title might not be so clear, so let me elaborate more. I have a two-column template, and want to load some number of items in them. It would look like this: {{item1}} | {{item2}} {{item3}} | {{item4}} {{item5}} | {{item6}} {{item7}} | {{item8}} ... And this is the farthest I've got in my template : {% for a in answers %} <div class="row justify-content-center"> <div class="col-6 text-center"> <div class="row justify-content-center"> <div class="col"> <div class="answers">{{a.title}}</div> </div> </div> </div> <div class="col-6 text-center"> <div class="row justify-content-center"> <div class="col"> <div class="answers">{{a.title}}</div> </div> </div> </div> </div> {% endfor %} Apparently, it doesn't load item as I want to. How do I make this possible? Any help is very much appreciated! :) +Some other codes for further info: views.py def qandaSquare(request, pk): answers = Answer.objects.filter(authuser=request.user.id, question_number=pk) context = { 'answers' : answers, } return render(request, 'main/square.html', context) -
Overriding Django model's id
I have a user model and multiple user types that are related to the user model with a one to one relationship, a goer and a host. Whenever someone creates a goer or a host, an underlying user model is created and saved in the postgresql table. Currently, the goers' and the hosts' id are auto incrementing to the number of goers and hosts. Is there anyway I can override the goers' and hosts' id such that it matches the id of the underlying user that is created? -
Django: Dynamic Annotation and Filtering
I think this should not be complicated but i can't get it right. How can i conditionally count the number of brands in a specific category within a queryset? views.py def get_brands(request): all_brands = brand.objects.values('brand_name','brand_category').\ annotate(brand_proportion=Count('brand_name')/Count('brand_name', filter=Q(brand_category="brand_category"))#I'm stuck here return JsonResponse(list(all_brands), safe=False) I am not sure to filter the brand category and count the number of brands in that category. For example: brand_category 'A' might have: Brand 1,Brand 1 ,Brand 1,Brand 2,Brand 2 Here, the proportion of Brand 1 in category A would be 3/5 = 0.6 or 60% I can calculate the 3 using Count('brand_name') within the queryset, but how can i calculate the 5? brand_category 'B' might have: Brand 1,Brand 2,Brand 3,Brand 4,Brand 5 Here, the proportion of Brand 1 in category B would be 1/5 = 0.2 or 20% Please help.Thanks. -
I want members +1
I am currently trying to create a many to many field that will allow a user to create an organization with a name and a description. I would like to show how the name of the different users in the org as well as the creator. Is there a way for me to automatically count the creator of the org as a member without rewriting too much of my code? ATM even if the user is the admin of the org the member count remains 0. -
NoReverseMatch error when using reverse function
I am trying to redirect from one view to another and I get the following error: NoReverseMatch at /challenges/1/answer/ Reverse for 'results' with arguments '(1,'test')' not found. 1 pattern(s) tried: ['challenges\/(?P<challenge_id>[0-9]+)\/results\/$'] I have the following code in models.py: def answer(request, challenge_id): challenge = ... result = "test" return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result))) def results(request, challenge_id, result): My understanding is that 'reverse' in an HttpResponseRedirect would redirect to results if I pass the 'result' in args? Thanks in advance!