Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement Graphql Proxy in python
I'm trying to build a simple Graphql proxy service that receives graphql requests and forwards them to a remote server and I can return the response to the main server. I am using Django for the main project and the remote server is also using Django graphene to return. -
Constant deletion routine can harm the performance of the database or application?
I created a view that does some checks between models as these models are updated/added. When this check finds an inconsistency it creates a record and a specific model of record of inconsistencies. My question is about the strategy I used in this view. view def farm_check(farm_id): farm = get_object_or_404(Farm, pk=farm_id) to_delete = FarmProblem.objects.filter(farm=farm) for delete in to_delete: delete.delete() check_city = Registration.objects.filter(farm=farm).filter(~Q(city=farm.city)) check_uf = Registration.objects.filter(farm=farm).filter(~Q(uf=farm.uf)) check_car = Registration.objects.filter(farm=farm,car__isnull=True) check_ccir = Registration.objects.filter(farm=farm,ccir__isnull=True) check_nirf = Registration.objects.filter(farm=farm,nirf__isnull=True) check_area = Registration.objects.filter(farm=farm,area__isnull=True) list_area_pk = map(lambda x: x.pk,check_area) check_app = Registration.objects.filter(farm=farm,app__isnull=True).exclude(pk__in=list_area_pk) for check in check_city: problem = 'Cidade inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='City',specific=check.number,item=problem) item.save() for check in check_uf: problem = 'UF inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='UF',specific=check.number,item=problem) item.save() for check in check_car: problem = 'CAR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CAR',specific=check.number,item=problem) item.save() for check in check_ccir: problem = 'CCIR inconsistente' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='CCIR',specific=check.number,item=problem) item.save() for check in check_nirf: problem = 'Sem número de NIRF' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='NIRF',specific=check.number,item=problem) item.save() for check in check_area: problem = 'Área indeterminada' item_test = FarmProblem.objects.filter(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) if not item_test: item = FarmProblem(client=farm.client,farm=farm,context='Area',specific=check.number,item=problem) item.save() for check in check_app: problem … -
Add Custom bootstap template to Django CMS Project
I hope you are well. The reason i'm writing to you is because ive been utilizing the Django cms bootstrap carousel plug in. Im all set however i am struggling to figure out how to add me newly added custom template to my application. Im wondering if there is something i need to add to my settings.py file like CAROUSEL_TEMPLATES = [ ' ' ] I would be very grateful if you could point me in the right direction? -
Django view function isnt working correctly
so the basic goal of my project is to allow teachers and admin to login to the system and take attendance for the students. my new issue is that i have a view function that is suppose to check to see if students student is already added to the respective class and if they are it will exclude them from the drop down menu and display the students who aren't in the class but it not doing that instead it is showing me a blank drop down menu. the way i have it set up is that the admin clicks the add student button then it will convert a .html page to modal which brings up the list of students to select from. When i add the form responsible for saving the student to the class in the Django admin it work perfect but i cant seem to get it to work in the user section Ui. I am new to Django and this is my first project so any help is really appreciated Views #check to see if students already exist in class and display those who aint to be added @login_required def manage_class_student(request, classPK=None): if classPK is None: … -
Creating a subForm within a Form to populate an Abstract Form
I have been trying to figure this out by banging my head and scouring the forums and Google. Hope someone has had experience with this. I am trying to create some text mining subform within PostForm Class that calls a script.So an user enters a DOI or PMID and searches the PUBMED database.I am successful with the script pulls data from a server, but would like to figure out the user then continues to fill the rest of the data. So together with the Called data and the User entry save as post. Here I am using the Django-Machina Blog as the platform. So a User would enter a DOI or PMID, returns a query, that a user can then enter information in contents. [Form][1] AbstractModel: class AbstractPost(DatedModel): """ Represents a forum post. A forum post is always linked to a topic. """ topic = models.ForeignKey( 'forum_conversation.Topic', related_name='posts', on_delete=models.CASCADE, verbose_name=_('Topic'), ) poster = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='posts', blank=True, null=True, on_delete=models.CASCADE, verbose_name=_('Poster'), ) anonymous_key = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Anonymous user forum key'), ) # Each post can have its own subject. The subject of the thread corresponds to the # one associated with the first post subject = models.CharField(verbose_name=_('Subject'), max_length=255) doi … -
Django Generating Custom ID
Okay so, I have seen numerous "answers" to this question, most notably, this one. from django.db.models import Max id = models.CharField(primary_key=True, editable= False, max_length=10) def save(self, **kwargs): if not self.id: max= Custom.objects.aggregate(id_max=Max('id'))['id_max'] self.id= "{}{:05d}".format('IT-', max if max is not None else 1) super().save(*kwargs) Now, thanks to this, I really just apply the code to my model, and it should work. Well, it doesn't. It wants to, but it can't, let me explain: on the backend of the django application I tried adding a new row, but when saving it, it throws an OperationalError, (1366, "Incorrect integer value: 'IT-00002' for column id), (my prefix being 'IT-'). Now, from what I can gather, the prefix is being included yes, but the column isn´t changing from integer. I have saved, migrated all changes and it isn´t working. I have even tried changing the data type in phpmyadmin, but because it also has the 'AUTO_INCREMENT' property, it can't be changed to anything other than an integer. How can I change this? -
TypeError: cannot unpack non-iterable function object while using get() in Django
I have a model called WatchList with a object called listing which corresponds to the Listings model. I want to make a page where all the listings that a user has added to his watchlist appear. I am trying to filter through the WatchList objects through the user and get access to the listing object, so I can get all the objects from that particular listing (there may be more than one). views.py def watchlist(request): watchlists = WatchList.objects.filter(user=request.user) watchlist_listing = watchlists.get(listing) listings = Listings.objects.all().filter(watchlist_listing) return render(request, "auctions/watchlist.html",{ "listings": listings }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") error message TypeError: cannot unpack non-iterable function object This error is caused by this line watchlist_listing = watchlists.get(listing) . But if I change the code to watchlist_listing = watchlists.get('listing') this error too many values to unpack (expected 2) occurs. How do I fix this and get access … -
Why does Django related_name isn't working
I am working in my Django (DRF) app. I have these models class CustomUser(AbstractBaseUser, PermissionsMixin): ... class SupportChat(models.Model): support = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="support_chat" ) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name="chat" ) I want to get chats of the users in views.py @api_view(['GET']) def get_my_chats(request): res = {} admins = CustomUser.objects.filter(user_type='Admin') res["admins"] = CustomUserSerializer(admins, many=True).data #my_request_chats = SupportChat.objects.filter(user=request.user) my_request_chats = request.user.chat if my_request_chats is not None: res["my_request_chats"] = SupportChatSerializer(my_request_chats, many=True).data res["my_request_chats"] = None my_response_chats = SupportChat.objects.filter(support=request.user) if my_response_chats is not None: res["my_response_chats"] = SupportChatSerializer(my_response_chats, many=True).data res["my_response_chats"] = None return Response(res) Problem -- Can't get chats of the user (my_request_chats is NULL) Received response like this { "admins": [ // valid data ], "my_request_chats": null, "my_response_chats": null } I checked that request.user have chats (in admin panel) -
Django resize chart in table
I have a basic chart created with chart.js which is later displayed in table. I have a problem to manipulate his height/width to fit it correctly to table in django template. Chart is displayed in for loop in table and code looks like: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> <table class="table table-bordered"> <thead>Details </thead> <tbody> {% for key, value in game_details.items %} <tr> <th>Game</th> <th>Played</th> <th>Won</th> <th>Lost</th> <th>Pending</th> </tr> <tr> <td>Game </td> <td>{{ value.all }}</td> <td>{{ value.win }}</td> <td>{{ value.lost }}</td> <td>{{ value.pending }}</td> </tr> <tr> <td colspan="5" style="max-height: 10px"> <canvas id="myChart{{ key }}" width="200" height="200"></canvas> <script> const ctx{{ key }} = document.getElementById('myChart{{ key }}').getContext('2d'); const myChart{{ key }} = new Chart(ctx{{ key }}, { type: 'doughnut', data: { labels: ['W', 'L', "P"], datasets: [{ label: '# of Votes', data: [{{ value.win }}, {{ value.lost }}, {{ value.pending }}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(153, 102, 255, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(153, 102, 255, 1)', ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </td> </tr> {% endfor %} </tbody> </table> and it looks like that: Changing the width or height … -
NameError: name 'Any' is not defined in Django
When I use the autocomplete suggestion in VSCode to make a get_context_data() function: def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: return super().get_context_data(**kwargs) I get a NameError: NameError: name 'Any' is not defined I am new to using type hints in Python - do I need to import something for type Any? -
how to get all field on modelform on django
I have a model called Product class Product(models.Model): id name nation Number price i want to filter using all of the above attributes, which will be passed in query_params at this moment i am using DjangoFilterBackends with filter_fields but to support all attributes i have to mention all the attributes in filter_fields like below in views filter_fields = ['id', 'name', 'nation', 'Number', 'price'] its working fine, but in actual model the fields are alot, which is causing code quality degradation. is there any way to include all fields in filter_fields ?? i tried filter_fiels = ['__all__'], but its not working. -
how to show options in select with forms.ModelChoiceField - Django
I have this problem: I need to show in a select the data of a model, I have been working with form template to customize it, but when it comes to a select I don't know how to show the options in template it only shows 'rol' in the options. My model: class Rol(TimeStampedModel): name = models.CharField(verbose_name=_('Name'), max_length=100) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.IntegerField(verbose_name=_('Sort Order'), default=0) My forms: class ProfileForm(forms.ModelForm): rol = forms.ModelChoiceField(queryset=Rol.objects.all().order_by('sort_order'), to_field_name='name') class Meta: model = User fields = ['email', 'first_name', 'last_name','rut', 'phone', 'gender', 'rol'] exclude = ('username',) def __init__(self, user=None, *args, **kwargs): self.user = user super(ProfileForm, self).__init__(*args, **kwargs) My HTML: <tr> <td class="table-text typo-grey"><label class="float-left">Rol</label></td> <td class="rol centered"> <div class="ui input"> <select type="mail" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}" maxlength="100"> {% for rol in form.rol %} <option value="{{ form.rol.html_name|default:'' }}"=>{{form.rol.html_name}}</option> {% endfor %} </select> </div> </td> </tr> If u any advice or something, please coment, thanks. -
Django - multi-table inheritance - convert Parent to Child
I have models that look like this: class Property(Model): ... class Meta: # not abstract class Flat(Property): ... class House(Property): ... Is it possible to convert already existing Property to House or Flat? I know that House or Flat additional fields are in different tables so this should be doable by creating such a row and making some relation. How can I do that? -
Django import export get() returned more than one
I have a small Django application with cities_light, smart_selects, and import_export. I am able to properly export from the admin site into csv files using resources and ForeignKeyWidget from import_export. However, there is something wrong with my import and I'm not sure how to fix it. When trying to import through the admin site from the same exported csv file, I get jobs.models.City.MultipleObjectsReturned: get() returned more than one City -- it returned 2!. This question is similar to this one but I still do not understand what is wrong. Would greatly appreciate if the responses contain links to the documentation that explain what I am doing wrong, since I've gone through ReadTheDocs but have been unsuccessful at finding my mistake. Thanks. models.py class Country(AbstractCountry): pass connect_default_signals(Country) class Region(AbstractRegion): def __str__(self): return self.name country = models.ForeignKey(Country, on_delete=models.PROTECT) connect_default_signals(Region) class SubRegion(AbstractSubRegion): pass connect_default_signals(SubRegion) class City(AbstractCity): def __str__(self): return self.name region = models.ForeignKey(Region, on_delete=models.PROTECT) connect_default_signals(City) class JobPost(models.Model): title = models.CharField(max_length=100) company = models.CharField(max_length=100) urlCompany = models.URLField(blank=True) urlApplication = models.URLField(blank=True) contactEmail = models.EmailField(max_length=100, blank=True) jobType = models.CharField(max_length=100, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) region = ChainedForeignKey( Region, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, sort=True, blank=True ) city = ChainedForeignKey( City, chained_field="region", chained_model_field="region", show_all=False, auto_choose=True, sort=True, blank=True … -
how to get data from foreign key to save in database in django
I have two models that are related with many to many relationship. I need the data of the second model to be stored in the database when creating the object from the first model so that later if the values of the second model change, it will not affect the values we entered in the first model. How should I act? # models.py class First(models.Model): percent = models.IntegerField() two = models.ManyToManyField(Two, blank=True) class Two(models.Model): title = models.CharField(max_length=50, null=True) amount = models.PositiveIntegerField(null=True) # forms.py class FirstAddForm(forms.ModelForm): class Meta: model = First def save(self, commit=True): instance = super(FirstAddForm, self).save(commit=False) instance.percent = self.cleaned_data['percent'] / 100 . # How should I act? # . if commit: instance.save() self.save_m2m() return instance # views.py def FishDetailView(request, pk=None): first = First.objects.all() . . for i in First: two= Two.objects.filter(first__id=i.id) . . context = { 'first': first 'two': two, } -
Django DELETE Endpoint gives permission denied, but every other endpoint works fine
I tried to search around including how HTTP DELETE and POST are called. But can't seem to understand why DELETE endpoint doesn't work. The POST endpoint has the exact same Permissions and Serializer, but when I try to DELETE via Postman, it says permission denied. Doesn't make any sense. #this one works fine class PhoneNumberCreateApi(generics.CreateAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer #this one does not class PhoneNumberDeleteApi(generics.DestroyAPIView): permission_classes = [custompermission.IsStaff] queryset = Phone.objects.all() serializer_class = PhoneNumberSerializer Any insight is appreciated. Never seen this error before. -
Django: Reverse for 'download_excel/309' not found. 'download_excel/309' is not a valid view function or pattern name
I am currently working on designing a Django app that would allow a person to download an excel with data from a page. I am trying to connect a hyperlink to a view function but it keeps returning the reverse match. I am able to go directly to the url and it downloads the excel but when I can't load the index.html file because of the error. Am I naming the hyperlink wrong? urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('Excel/<int:study>', views.Excel, name='Excel'), path('download_excel/<int:study>', views.download_excel, name='download_excel'), ] index.html <html> <title>Download File</title> </head> <body> <enter> <h1>Download File using Django</h1> <a href="{% url 'polls:download_excel/309' %}">Download State Impulsivity Excel</a> </enter> </body> </html> views.py def download_excel(request, study): with BytesIO() as b: writer = pd.ExcelWriter(b, engine='xlsxwriter') Retrieve(study) df = pd.DataFrame(data) df.to_excel(writer, sheet_name='Sheet1') writer.save() Names(study) filename = str(name) + "_" + str(current_time) + ".xlsx" response = HttpResponse( b.getvalue(), content_type=mimetypes.guess_type(filename) ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
Django Apscheduler
I'm looking to use Django Apscheduler or Django Celery to allow a user to input a cron expression and add it to the jobs list to be run at the user specified time. I also would like the user to be able to edit the cron expression if needed down the road. From django apscheduler docs I'm aware updates and creates aren't registered till the server is restarted and I'm okay with the server being restarted nightly to import the new jobs. -
Object of type bytes is not JSON serializable when trying to return jwt_token
Really confused because this functionality was working a few days ago and I made no substantial changes to my code. I am getting this traceback: Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response File "C:\Users\15512\anaconda3\lib\site-packages\django\core\serializers\json.py", line 105, in default return super().default(o) File "C:\Users\15512\anaconda3\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable To summarize, I am sending a name to the Twilio library with the expectation of receiving a JWT_token. The API endpoint would then return a dict with a key: title and jwt_token This is what my view for the end point looks like: class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() full_data = {'token': jwt_token} # print(type(jwt_token)) return JsonResponse(json.dumps(full_data), content_type="application/json", safe=False) I've also tried to have this in the return statement: JsonResponse({"token": jwt_token}) -
Django Rest Framework Ordering Filter by an element in nested list
I am using OrderingFilterBackend from django_elasticsearch_dsl_drf to order the results for the api call, i can order by fields and nested fields fine. Now i would like to order by a field in the first element in a nested list. So for each item in the list returned from the api get request the data structure looks like: { id: 1, events: [ { id:2, name: "test_1" }, { id:3, name: "test_2" } ] } I want to order by my_list[0].name. My serializers.py: class EventSerializers(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(read_only=True) class Meta: model = models.Event fields = ( 'id', 'name', 'created', 'updated' ) class OrganisationSerializer(WritableNestedModelSerializer): events = EventSerializers(many=True, required=False) class Meta: model = models.Organisation fields = ( 'id', 'events', 'created', 'updated' ) My views.py: class OrganisationViewSet(SearchWriteNestedViewSet): model = models.Organisation serializer_class = OrganisationSerializer queryset = models.Organisation.objects.all() document = OrganisationDocument filter_backends = [ OrderingFilterBackend ] ordering_fields = { 'id': None, "events": { 'field': 'events.name', 'path': 'events', } } I believe where i have gone astray is somewhere here ordering_fields = { 'id': None, "events": { 'field': 'events.name', 'path': 'events', } } i have tried 'field': 'events.0.name', 'field': 'events.[0].name' and 'field': 'events[0]name', I have searched for the answer but i cannot find … -
How we can use Drf SerializerMethodField with django-filters backend
Getting an error likes this. I am not able to understand that how to create a logic here please create some logic(for me it interesting). Here is the error: FieldError at /api/website/member/ Cannot resolve keyword 'is_you' into field. Choices are: about, address, age, avatar, blocked_author, blocked_person, blog, blogcategory, blogtag, bookmark_author, bookmark_person, children, city, country, created_at, date_joined, education, email, employement, ethnicity, eye_color, faq, favourite_author, favourite_person, first_name, gender, groups, hair_color, height, hidden_author, hidden_person, id, income, interests, is_active, is_online, is_online_show, is_staff, is_superuser, language, last_login, last_name, logentry, looking, password, phone, postal, province, relationship, religion, skin_color, smoke, sports, star, status, updated_at, user_permissions, username, verified, weight Here is the error: User model (Models.py) class User(AbstractUser): username = models.CharField('username', max_length=150, unique=True) email = models.EmailField('email address', unique=True, max_length=255) first_name = models.CharField(max_length=250, null=True, blank=True) last_name = models.CharField(max_length=250, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) about = models.CharField(max_length=1000, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) province = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) postal = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=500, null=True, blank=True) gender = models.CharField(max_length=500, null=True, blank=True) age = models.CharField(max_length=500, null=True, blank=True) is_online = models.BooleanField(null=True, blank=True) is_online_show = models.BooleanField(null=True, blank=True) looking = models.CharField(max_length=100, null=True, blank=True) employement = models.CharField(max_length=50, null=True, blank=True) education = models.CharField(max_length=500, null=True, blank=True) religion = … -
How to get userid in Django classviews?
I have this class that changes user password: class PasswordsChangeView(PasswordChangeView): from_class = PasswordChangingForm success_url = reverse_lazy( "base:password/passwordsuccess", ) And I would like to insert User Avatar Img Path in context. This Img is inside a UserComplement model. When I create function views, it works doing: @login_required def password_success(request): try: obg = UserComplement.objects.get(pk=request.user.id) context = { "img_avatar": obg.avatar_image, } return render(request, "registration/passwordsuccess.html", context) except UserComplement.DoesNotExist: return render(request, "registration/passwordsuccess.html") The problem is that I cannot get the userID in classviews to pass it through the context on success_url. -
Django List Sending To API
We are currently in the process of making a new online store program for our students. The current framework we are using is DJANGO. On one of our views which is called completed checkout, it sends an email to the student's counselor to approve the following purchase. That email we are sending via 3rd party is called Postmark. The reason we decided to go with the third party as opposed to Django is to monitor the tracking of the emails and not have to deal with SMTP issues. The API is a REST API and requires JSON, dictionary, or list to be sent to populate the template. I'm going to show you the postmark template in HTML. The following lines within the template are what the API pushes data to. <td width="60%" class="align-left purchase_item">{{product__name}}</td> <td width="40%" class="align-right purchase_item">{{product__point_price}}</td> Template <table class="purchase_content" width="100%" cellpadding="0" cellspacing="0"> <tr> <th class="purchase_heading"> <p class="align-left">Description</p> </th> <th class="purchase_heading"> <p class="align-right">Amount</p> </th> </tr> {{#each receipt_details}} <tr> <td width="60%" class="align-left purchase_item">{{product__name}}</td> <td width="40%" class="align-right purchase_item">{{product__point_price}}</td> </tr> {{/each}} <tr> <td width="80%" class="purchase_footer" valign="middle"> <p class="purchase_total purchase_total--label">Total Points</p> </td> <td width="20%" class="purchase_footer" valign="middle"> <p class="purchase_total">{{points}}</p> </td> </tr> </table> Now below here is the Completed Checkout View. The issue we are … -
Django error no reverse match with arguments '('',)'
I feel kinda bad using my first post as a cry for help but hey, im certainly not the first lulz, anyway, im teaching myself python/django and im really stuck atm and ive been slogging through problems myself lately and wasting a lot of time doing it and this one has me stuck. Im getting the error: NoReverseMatch at /messages/newreply/1/ Reverse for 'newreply' with arguments '('',)' not found. 1 pattern(s) tried: ['messages/newreply/(?P<post_id>[0-9]+)/\Z'] This is my url file; app_name = 'board' urlpatterns = [ path('', views.index, name='index'), path('<int:post_id>/', views.postdetail, name='detail'), path('newmsg/', views.newmsg, name='newmsg'), path('newreply/<int:post_id>/', views.newreply, name='newreply') view def newreply(request, post_id): post = Post.objects.get(id=post_id) if request.method != "POST": form = ReplyForm() else: form = ReplyForm(data=request.POST) if form.is_valid(): newreply= form.save(commit=False) newreply.post = post newreply.save() return redirect('board:index') context = {'form':form} return render(request, 'board/newreply.html', context) template; {% extends 'pages/base.html' %} {% block content %} <p>Add your reply here</p> <form action="{% url 'board:newreply' post.id %}"method ='post'> {% csrf_token %} {{ form.as_p }} <button name = "submit">Add post</button> </form> {% endblock content %} Ive tried so many things now im not even sure where i began anymore so id really appreciate any help, especially knowing why its actually happening as ive read through a few posts with … -
Need help in displaying items from ManyToMany relation in Django template
I am struggling with displaying items from manytomany field in my html file. models.py class Ingredients(models.Model): name = models.CharField('Nazwa', max_length = 100) ingredient_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE) class ShoppingList(models.Model): name = models.CharField('Nazwa', max_length = 100) status = models.BooleanField(default = False) last_updated = models.DateTimeField('Ostatnia aktualizacja', auto_now=True) publish = models.DateTimeField('Stworzono', default=timezone.now) ingredient_list = models.ManyToManyField(Ingredients, related_name='shopping_list') slug = models.SlugField(unique=True, blank=True, max_length=254) views.py class HomePageView(TemplateView): template_name = "homepage.html" queryset= ShoppingList.objects.all() def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) shopping_list = ShoppingList.objects.all() context['shopping_list'] = shopping_list return context homepage.html {% for list in shopping_list.ingredient_list.all %} <div class="tab-pane fade {% if forloop.first %}show active{% else %}{% endif %}" id="list-{{list.id}}" role="tabpanel" aria-labelledby="list-{{list.id}}-tab">{{list.name}}</div> {% endfor %}