Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i change is_staff to true ( is false by default) using django
is_staff is by default false and I want to change it to true. I have tried 4-5 methods but is giving an error. error: ValidationError at /accounts/login ["'false' value must be either True or False."] please help. -
NoReverseMatch - not a registered namespace
Hello, I am new to Django and I was working at my first project, but I got NoReverseMatch with Exception Value: 'hiring_log_app' is not a registered namespace in base.htlm which follows: href="{% url 'hiring_log_app:index' %}" >Hiring Log href="{% url 'hiring_log_app:topics' %}" >Topics I made sure my namespace was correct and I looked at the other topics already opened without figuring out how to solve the issue. I paste urls.py: from django.contrib import admin from django.conf.urls import include, url urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include ('hiring_log_app.urls', namespace='hiring_log_app')), ------ hiring_log_app/urls.py: """Define URL patterns for hiring_log_app""" from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^topics/$', views.topics, name='topics'), ] ----- views.py: from django.shortcuts import render from .models import Topic def index(request): """The home page for hiring_log_app""" return render(request, 'hiring_log_app/index.htlm') def topics(request): """ list of topics""" topics = Topic.objects.raw( "SELECT text FROM HIRING_LOG_APP_TOPIC;") context = {'topics' : topics} return render(request, 'hiring_log_app/topics.htlm', context) ------- Does anyone know where I am making a mistake? Thnaks a lot in advance, any help would be precious. Thanks again. -
Related resources on a nested URL in Django Rest Framework
I have two models, Foo and Bar. Bar has a foreign key to Foo. I have a ModelViewSet for Foo and I want the route /api/foos/<pk>/bars/ to return all the bars related to the given foo. I know this can be done using actions. For example class FooViewSet(viewsets.ModelViewSet): serializer_class = FooSerializer queryset = Foo.objects.all() @action(detail=True, methods=['GET']) def bars(self, request, pk): queryset = Bar.objects.filter(foo=pk) serializer = BarSerializer(queryset, many=True) return Response(serializer.data) @bars.mapping.post def create_bar(self, request, pk): request.data['foo'] = pk serializer = BarSerializer(request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) However, this feels like a lot of unnecessary boilerplate code. Is this possible to do in viewsets in a more convenient way? If not, what is the normal DRF way of doing it? A solution with a different URL is also acceptable for me as long as it minimizes boilerplate code. -
Django - how to add prefix to Mixin attributes (possible?)
There is too much relations and chains of actions in my project so I decided to eliminate some relations and use Mixins instead to keep things DRY. For example: class AddressMixin(BaseModel): address_zip = models.CharField(max_length=6, null=True, blank=True, verbose_name='PSČ') address_lat = models.DecimalField(max_digits=24, decimal_places=20, null=True, blank=True) address_lng = models.DecimalField(max_digits=24, decimal_places=20, null=True, blank=True) ... class Meta: abstract = True def some_method... There are many models using Address where I use this as a Mixin but sometimes, I need two or three types of addresses in one model. class Client(..): home_address = OneToOneField('addresses.OldAddressModel',...) work_address = OneToOneField('addresses.OldAddressModel',...) Here I can't just use AddressMixin like Client(AddressMixin,Model) since I need two different addresses. I would like to use AddressMixin two times with different prefixes, so in final model, there would be home_address_city and work_address_city. Is it possible to do that? I was thinking about some MixinFactory which takes Mixin and prefix and then it prefix all attributes (and maybe methods too but I can live without prefixed methods...). -
Django static files not loading with no error signs
When I run django server and try to load html files, it's not loading css files. I don't see any errors on terminal or the website itself - just loading animation in the background. After I set up static files in settings.py, I ran collectstatic on terminal which generated a new static file in main file area with all the css/js/fonts files. Thank you in advance! ~filepath ├── static/ │ ├── static/ │ │ └── admin/ │ │ └── css/ │ └── fonts/ │ └── images/ │ └── js/ ├── templates/ │ └── base.html/ │ └── _partials/ │ └── footer.html │ └── navbar.html │ └── pages/ │ └── index.html │ └── about.html ~settings.py STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'tvfb/static') ] ~urls.py (project) urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), ] ~urls.py (app) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] ~views.py def index(request): return render(request, 'pages/index.html') def about(request): return render(request, 'pages/about.html') ~base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,400i,700,700i,900,900i" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" … -
Django inlinefomrset delete
Here is a mystery. I cannot get the inlineformset deletion to work property. I have followed the docs to delete forms in my formset processing: # In my forms.py: def clean(self, *args, **kwargs): ''' Custom clean method to handle deletion ''' super(BaseDevelopmentTypeInlineFormSet, self).clean(*args, **kwargs) if any(self.errors): return # Everything beyond this point is clean cd = self.cleaned_data for form in self.forms: the_can_delete = self.can_delete # can_delete returns True the_should_delete = self._should_delete_form(form) # _should_delete returns False! form_fields = [ field for field in form.fields ] if self.can_delete and self._should_delete_form(form): continue form_cd = form.cleaned_data And, here are the relevant sections of the views.py: if development_type_formset.is_valid(): development_types_cd = development_type_formset.cleaned_data forms_marked_for_deletion = development_type_formset.deleted_forms assert False # forms_marked_for_deletion correctly returns the forms that have been marked for deletion the_kwargs = {'development_project': active_development_project } development_type_formset.save(**the_kwargs) assert False # the_development_types = [] is returned return HttpResponseRedirect(reverse('development:add_details', args = (the_id,))) After submitting, the redirection to another url happens successfully. But, when I go back, I still see the forms that should have been deleted. Originally, I thought the problem is with _should_delete, so I commented the part of the code calling _should_delete out. This made no difference. The redirection happened successfully, but deletion failed again. I have searched … -
How to iterate across HTML elements a specific number of times?
I'm having trouble coming up with working logic for the use case of repeating a set of HTML elements across columns. Simplified HTML as an example: {% for day in days %} <div class="container"> <div class="row"> {%for room in day.rooms%} <div class="col-sm-3"> <section class="box"> <h4>{{room.name}}</h4> {%for session in day.sessions%} {%if session.leftpos == room.leftpos %} {%if session.id%} <a href="session/{{session.id}}-{{session.title|slugify}}/">{{session.timeslot}}<br/><b>{{session.title}}</b><br/></a> {%else%} {{session.timeslot}} - <b>{{session.title}}</b> {%endif%} {%for speaker in session.speakers %}{%if loop.first%}{%else%}, {%endif%}<i><a href="speaker/{{speaker.id}}-{{speaker.name|slugify}}/">{{speaker.name}}</a></i>{%endfor%} {%endif%} {%endfor%} </section> </div> {%endfor%} </div> </div> {%endfor%} As this currently works, it looks for rooms depending on the sortkey, and lines up the talks corresponding with what rooms by going off that sortkey (if session.leftpos == room.leftpos). I have another variable (session.cross_schedule) which applies to talks which span across all 3 rooms, meaning that's the featured session. What I need to determine is how best to repeat the session information (everything within for session in day.sessions) across for room in day.rooms, but only if it's session.cross_schedule. Ideally, these cross-scheduled talks would appear at the proper time in the schedule rather than being separated from the rest. Any ideas or guidance would be much appreciated! -
Implement google autocomplete for address fields whilst using django models for forms
I have used django models to create the forms then loaded in the fields using crispy forms. The current implementation uses a standard text field to take in the address straight from the models. I would like to add the auto complete feature so that no incorrect addresses are entered in. I am unable to access the raw code as crispy forms loads everything in straight from the models so I cannot attach the code required for the autocomplete feature. I have tried to add a block in to manually add in the address however, this can only be added at the top or the bottom of the form. This is a problem as I need to add the address after the user entering the title of the listing. forms.py class ListingDevelopmentForm(forms.Form): title = forms.CharField() slug = forms.SlugField() description = forms.CharField(widget=forms.Textarea) first_line_address = forms.CharField() second_line_address = forms.CharField() postcode = forms.CharField() number_of_properties= forms.IntegerField() site_plan = forms.IntegerField() price = forms.DecimalField() rent = forms.DecimalField() ownership = forms.CharField() tenure = forms.CharField() from.html <form method="post" action='.' enctype='multipart/form-data'> {% csrf_token %} {{ form|crispy }} {% block main1 %} <!-- this is where I have added the block which allows me to manually add in the code … -
Is there a better way to display additional information from the Django model in the Django admin
Is there a better way to make the code less repetitive by moving the "CONN" to where is can still be used but where it only need to be written once. So I can still display the same information in the same fields in django admin. When I move "CONN" somewhere else the function stops working. and an error get displayed. Models.py class Host(models.Model): name = models.CharField(max_length=20) hostname = models.CharField(max_length=20) login = models.CharField(max_length=20) password = models.CharField(max_length=14, blank=True, null=True) conntype = models.CharField(max_length=7, choices=CONN_SELECT) def __str__(self): return self.name def status(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) status = conn.host_up() return status def cpu(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[0] def memory(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[1] def free_memory(self): conn = HostConn(self.hostname, self.login, self.password, self.conntype) return conn.get_host_info()[2] admin.py class HostAdmin(admin.ModelAdmin): list_display = ('name', 'hostname', 'conntype', 'status', 'cpu', 'memory', 'free_memory', 'options') -
I do a search on the site but gives an error No Programs matches the given query
I do a search on the site but gives an error " No Programs matches the given query." I want to do a search on the site, but after I enter the search query I get an error views.py def post_searchProgramm(request): queryProgramm = request.GET.get('searchProgramm') if queryProgramm: results = Programs.objects.filter(title__icontains=queryProgramm).order_by('-date') total_results = results.count() return render(request, 'programs/programms.html', { 'results': results, 'queryProgramm': queryProgramm, 'total_results': total_results}) else: messages.info(request, 'no results found for {}', format(queryProgramm)) urls.py path('searchProgramm/', views.post_searchProgramm, name='post_searchProgramm'), html template <form action="{% url 'post_searchProgramm' %}" method="get"> <input style=" height:30px; min-width:10px; width:auto; border: 3px solid #242424; border-radius: 15px ; background-color: #8B8B8B;" type="text" name="searchProgramm" value=""> <input style=" margin-left:30px; height: 30px ; min-width:10px; width:auto; border-radius: 30px ; background-color: #414141 ; border: 3px solid #242424;" type="submit" value="Найти"> </form> forms.py class SearchFormProgramm (forms.Form): queryProgramm = forms.CharField() -
How to configure vue for correct integration with django
I would like to write an application using django for Web-API and vue.js for frontend. I find many tutorials how to do it and decided to follow this one https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a Unfortunately I have a problem whith configuration of WebPack. It is written that I have to change my URL to http://0.0.0.0:8080. But when I did it, my application's page become blank. Expected result: I see Vue.js start page when running django server. How can I fix it? -
serializing nested model objects in django
say i have some models in one of my apps in the django project as follows: class BaseModel(Model): # some fields... class FirstNestedLevel(Model): parent_id = ForeignKey(BaseModel) # other fields class SecondNestedLevel(Model): parent_id = ManyToManyField(FirstNestedLevel) # other fields class ThirdNestedLevel(Model): parent_id = ForeignKey(SecondNestedLevel) # other fields It looks fine when there is only 2 level of nested objects to override the create and update methods on each serializer to make them work, but what if we have more levels of nested objects? I usually do this by implementing create and update methods to handle one level down and pass downer objects to their own serializer to do the rest. Is there a better way to implement serializer classes? -
how to apply 2d list in jinja(format) using django
I have this 2d list in python "[['count1', 'product1', 'subtotal1',' 'unit1', 'total1'], ['count2', 'product2', 'subtotal2',' 'unit2', 'total2'], ['count3', 'product3', 'subtotal3',' 'unit3', 'total3']]" i expect this in jinja format please explain in brief thank you obj = '[['count1', 'product1', 'subtotal1',' 'unit1', 'total1'], ['count2', 'product2', 'subtotal2',' 'unit2', 'total2'], ['count3', 'product3', 'subtotal3',' 'unit3', 'total3']]' return obj {% for x in list % }} {{x.count}} {{x.product}} {{x.subtotal}} {{x.unit}} {{x.total}} {% endfor %} -
Python: getting all combinations from dictionary with list values (i.e permutation)
I used django-oscar and I need to auto-create product variants from one parent product, that has multiple color, size, textile options. I have the following ProductAttributeValues rows, which I use to populate the auto-created variants. [ OrderedDict([('value', <QuerySet [<AttributeOption: Black>, <AttributeOption: White>]>, <AttributeOption: Red>]>), ('attribute', <ProductAttribute: dress Color>), ('product_class', 'dress')]), OrderedDict([('value', <QuerySet [<AttributeOption: M>, <AttributeOption: S>]>), ('attribute', <ProductAttribute: dress Size>), ('product_class', 'dress')]), OrderedDict([('value', <QuerySet [<AttributeOption: Cotton>, <AttributeOption: Wool>, <AttributeOption: Silk>, <AttributeOption: Nylon>]>), ('attribute', <ProductAttribute: dress Textile>), ('product_class', 'dress')]), ] I need to get all combination of the product variants like the following: [ { <ProductAttribute: dress Color>: <AttributeOption: Black>}, <ProductAttribute: dress Size>: <AttributeOption: S>, <ProductAttribute: dress Textile>: <AttributeOption: Cotton>, }, { <ProductAttribute: dress Color>: <AttributeOption: Black>}, <ProductAttribute: dress Size>: <AttributeOption: S>, <ProductAttribute: dress Textile>: <AttributeOption: Wool>, }, .... # this list should include all 24 possible combinations 3*2*4 = 24 # ] I tried to use itertools.product to get the results I wanted, but found no luck. Help needed! Thanks. Additional question. Would the following results be a better design? [ [ { "attribute": <ProductAttribute: dress Color>, "value": <AttributeOption: Black> }, { "attribute": <ProductAttribute: dress Size>, "value": <AttributeOption: S> }, { "attribute": <ProductAttribute: dress Textile>, "value": <AttributeOption: Cotton> } ], … -
correct usage of limit_choices_to in django models
Please help me to limit model team choices based on the company. Right now I put test value "1" and it's working correctly (function _limit_function). But how to limit it dynamically based on the selected company? class CustomCompany(models.Model): name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): name = models.CharField( max_length=30, default="None" ) company = models.ForeignKey( CustomCompany, on_delete=models.CASCADE, ) class CustomUser(AbstractUser): def _limit_function(): return {"company__id":1} phone = models.CharField( max_length=20, blank=True ) company = models.ForeignKey( CustomCompany, on_delete=models.CASCADE, default=1 ) team = models.ForeignKey( CustomTeam, on_delete=models.CASCADE, default=1, limit_choices_to = _limit_function() ) So, I need to limit variants of team values, based on the selected company. Please help to understand how to do this. -
TypeError: __str__ returned non-string (type MagicMock)
I'm writing some tests for my Django code and I'm mocking file and file storage. I've found this guide https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html so my mocks look like this # mocks.py image_mock = mock.MagicMock(spec=File, name='FileMock') image_mock.name = 'dummy.jpg' storage_mock = mock.MagicMock(spec=Storage, name='StorageMock') storage_mock.url = mock.MagicMock(name='url') storage_mock.url.return_value = '/tmp/dummy.jpg' any my failing test looks like this: import factory import mock from imagekit.signals import source_saved from .mocks import storage_mock, image_mock from .models import Car @factory.django.mute_signals(source_saved) class CarFactory(factory.django.DjangoModelFactory): class Meta: model = Car image = image_mock def test_case_one(self): with mock.patch('django.core.files.storage.default_storage._wrapped', storage_mock): car = CarFactory.create() And it fails with the following error: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:564: in create return cls._generate(enums.CREATE_STRATEGY, kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:337: in wrapped_generate return generate_method(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:141: in _generate return super(DjangoModelFactory, cls)._generate(strategy, params) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:501: in _generate return step.build() /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/builder.py:279: in build kwargs=kwargs, /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:315: in instantiate return self.factory._create(model, *args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:185: in _create return manager.create(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/manager.py:82: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/query.py:422: in create obj.save(force_insert=True, using=self.db) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:741: in save force_update=force_update, update_fields=update_fields) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:779: in save_base force_update, using, update_fields, /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:870: … -
showing json data in django template?
I have json files generated and saved in a model and I want to show it's content in a template. I tried this but it didn't work : def ResultDetails(request, pk=None): result = get_object_or_404(models.Processed,pk=pk) json_ = result.json_result.path with open(json_) as json_file: detail = json.load(json_file) context = { 'result' : result, 'json' : detail } template = "patients/results.html" return render(request,template,context) and this how I call it in the template : <tr> <th scope="row">{{ json.NumberOfCells }}</th> <td>{{ json.Cells_Density }}</td> <td>{{ json.Cells_Area }}</td> <td>{{ json.Cells_Perimeter }}</td> <td>{{ json.Cells_Polymegethism }}</td> <td>{{ json.Cells_Pleomorphism }}</td> </tr> the table headers appear but the content not btw the json file is just like this : I followed an answer here which was this approach is there a better one or should i take another one ? -
Select2 in Bootstrap with Dependent/Chained autocomplete List. Did not work
I'm trying to create Dependent/Chained Dropdown List (with auto-complete) with Bootstrap4 and Django. I'm trying to use this solution. Everything works fine if the forms are dropdown List. <select id="id_country" name="country" class="form-control" > <option value="" selected="selected">---------</option> <option value="1">Colombia</option> <option value="2">Rusia</option> </select> <select id="id_city" name="city" class="form-control"> <option value="" selected="selected">---------</option> <option value="1" class="1">Bogotá</option> <option value="2" class="2">Moscú</option> <option value="3" class="2">San Petersburgo</option> <option value="4" class="1">Valledupar</option> </select> But when I try to set the autocomplete to the first field, the second field stops working (stops responding). My code (after changes) looks like this: <select id="id_country" name="country" class="form-control" data-toggle="select" title="Country" data-live-search="true" data-live-search-placeholder="Country"> <option value="" selected="selected">---------</option> <option value="1">Colombia</option> <option value="2">Rusia</option> </select> <select id="id_city" name="city" class="form-control"> <option value="" selected="selected">---------</option> <option value="1" class="1">Bogotá</option> <option value="2" class="2">Moscú</option> <option value="3" class="2">San Petersburgo</option> <option value="4" class="1">Valledupar</option> </select> Why the solution stops working after adding additional parameters to the select field. Is it possible to add some simple javascript code in template that will run it again so that the second drop down field react properly again. Any help will be appreciated. -
Django return form with errors
I have created two functions, a edit and update. In the edit view, I return the form, on my template I have a form post to the update function. I am trying to return the form errors back to the page but how can I do that when it hits the update function? I know I could do all in one function and do a if request.method == 'POST but i'd figure to separate them. (Is my solution even the correct way to do in Django?) My goal is to do a return redirect with form, which then form would hold the errors. def locations_edit(request, id): location = Location.objects.filter(rand_id = id, user_id = request.user.id).first() if location is None: print('Error') return redirect('company-locations') context = { 'title': 'Edit Location - ' + location.name, 'pagetitle': 'Editing "' + location.name + '" Location ', 'tab_name': 'locations', 'new_location': 0, 'location': location } return render(request, 'company/locations/add_edit.html', context) def locations_update(request, id): location = Location.objects.filter(rand_id = id, user_id = request.user.id).first() if request.method == "POST" and location is not None: form = AddLocationForm(request.POST, instance=location) if form.is_valid(): form.save() messages.success(request, f'Location {location.name} updated') else: print(form.errors) return HttpResponse('Error') #return redirect('company-locations-edit', id=location.rand_id, *args={'form':form}) else: raise Http404 return redirect('company-locations-edit', id=location.rand_id) -
apache not servce media file django when debug =false
I use Linux VPS to run my application for android API and use apache web server when the debug is true my app work completely, but when debug is false I can't access my media file and get an error this is my apache conf : and this is my setting.py: and this is my media location: where is wrong and how to fix it debug false in my production and serve media file completely -
django queryset to output foreignkey objects to ModelChoiceField
class Location(models.Model): name = models.CharField() class Point(models.Model): name = models.CharField() location = models.ForeignKey('Location') I have a list of locations: Location A Location B Location C Every Point belongs to a location: Point 1 -> Location A Point 2 -> Location B I want to provide a queryset to a forms.ModelChoiceField so that it shows only Locations which have a Point associated in the database (in the example above it should only return Location A and Location B). In SQL language it would be: SELECT location.* FROM location JOIN point ON location.id = punto.location_id I've spent the last two hours reading the Django documentation, but I couldn't find any method to do what I need... any advice? -
Obtain mamytomanyfield value in anchor tag in template - Django
I am new to Django and trying to add program_code value to anchor tag. here are the codes: models.py class Program(models.Model): class Meta: verbose_name_plural = 'Program' program_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) program_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' program = models.ManyToManyField(Program, blank=False) course_code = models.CharField(max_length=10, default='', unique=True, validators=[MinLengthValidator(1)]) course_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) urls.py urlpatterns = [ path('',views.programs,name='programs'), path('<slug:program_code_no>/',views.courses,name='courses'), path('<slug:program_code_no>/<slug:course_code_no>',views.all_items,name='all_items'), ] views.py def programs(request): obj = Program.objects.all() paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/programs/index.html',context=all_details) def courses(request,program_code_no): obj = Courses.objects.filter(program=program_code_no) paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/courses/index.html',context=all_details) def search(request): query = request.GET.get('q') if query: course_search = Courses.objects.filter( Q(course_code__icontains=query) ).distinct() else: return redirect('/') all_details = { 'courses': course_search, } return render(request,'index/search.html',context=all_details) However, I get this error when I try to get http://127.0.0.1:8000/search/?q=c ('c' is a course_code field) search.html {% if courses %} {% for i in courses %} <a href="{% url 'courses:all_items' **i.program.program_code** i.course_code %}{% endfor %} "> <span>{{ i.course_title|title }}</span> </a> {% endfor %} {% endif %} I have to get value of program_code in anchor tag and program_code is from Program model and program is from Courses … -
Get second item of queryset in html file (Django)
How can I get the second item of queryset in html file (Django)? I tried {{ posts[1] }} -
Nested Serializer in Django Rest Framework
I am trying to make a nested serializer but when I run the following code it gives me an empty list. I tried to replicate the solution of this question and my problem is exactly similar The only difference is in that answer serializer.Serializer is used but I am using Model Serializer class hhhSerializer(serializers.Modelserializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(read_only=True) class Meta: model = ItemBatch fields = ('id','name') class dispatchhistorySerializer(serializers.ModelSerializer): truck_name = ReadOnlyField(source='truck_name.name') truck_type = ReadOnlyField(source='truck_type.name') items = hhhSerializer(many=True) class Meta: model = DispatchPlan fields = "__all__" Output: "id": 35, "truck_name": "24 ft mxl 14 Ton", "truck_type": "Container", "items": [ {}, {}, {}, {}, {}, {}, {}, {}, {}, {} ], -
NameError name 'ApplicationcreateView' is not defined
I've created an app where by a user can create a job and the other user can apply to that specific job.My problem is that when another user tries to apply for the job, on submitting the application view i get a NameError at /*/*/ name 'ApplicationcreateView' is not defined this error is due to the form_valid method in the ApplicationcreateView in the last line of views.py may some one please help me out,here is what i've tried in my code . thanks in advance models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True, null=True) career_briefing = models.CharField(max_length=250, null=True) class Attachments(models.Model): application = models.ForeignKey(Application, related_name='attachments', on_delete=models.CASCADE) cv = models.CharField(max_length=150, null=True) forms.py class ApplicationForm(forms.ModelForm): cvs = forms.CharField(max_length=6000, widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('career_briefing', 'job',) views.py class ApplicationCreateView(LoginRequiredMixin, CreateView): model = Application form_class = ApplicationForm message = _("succesfuly applied") template_name = 'jobs/application_form.html' def form_valid(self, form): cvs = form.cleaned_data['cvs'] form.instance.user = self.request.user apply = form.save(commit=False) apply.user = self.request.user apply.save() doc = Attachments(cv=cvs) doc.application = apply doc.save() return super(ApplicationcreateView,self).form_valid(form) My expectations are that after a user fills a form he is directed back to the job details but i just end up …