Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render to specific html div with value from django views?
I am trying to deploy a machine learning model using Django. Here I am trying to do is take input from the HTML form, predicting value using a trained model, and sending that result value to the HTML page. Still here working good. But I want to go to a specific division(div tag) of the HTML page based on division(div tag) id. Please help me, anyone; how can I fix this problem. HTML code File name :- nlpdocs.html <div style='background:pink;height:300px;width:600px;left:150px;position:relative' id="spam_try"> <form action='smsclassifier' method='POST' enctype='multipart/form-data' > {% csrf_token %} <h2 style='left:80px;position:relative'>SMS Spam Classifier</h2> <label>SMS :- </label> <textarea id="smstext" name='smstext' rows="4" cols="50" placeholder="Enter SMS here </textarea> <button type='submit' > Submit</button> </form> </div> <p><h4 style="color: #55CEFF">Input SMS Text :- </h4><h6> {{sms_text}}</h6></p> <p><h4 style="color: #55CEFF">Entered SMS is :- </h4><h6>{{result}}</h6></p> I create urls file within the django app folder. urls.py urlpatterns = [ path('',views.home_view,name='home_view'), path('index.html',views.home_view,name='home_view'), path('nlpdocs.html',views.nlpdocs, name='nlpdocs'), path('smsclassifier', views.sms_spam_classification, name='smsclassifier'), ] views.py @csrf_exempt def sms_spam_classification(request): """ Input :- Text Output :- string Return :- classify input text spam or not """ if request.method == 'POST': sms_text = request.POST.get('smstext') result = predict_new_text(sms_text) result_dict = {'result':result, 'sms_text':sms_text} return render(request, 'nlpdocs.html#spam_try', result_dict) If I send the only nlpdocs.html to render function, that one works but goes to … -
Django - Handle a user vote per set amount of time
I'm working on a Django site that allows users to post to car shows and then vote for entries. Previously you could just vote for your top 3, but now I'm trying to add the ability to re-vote after some configurable amount of time (eg. daily, weekly). The first option lent itself to Django m2m fields nicely. Essentially just added a 'votes' m2m field to each entry and then tracked who voted. With timing involved though I separated it out into a new 'vote' model as shown below. The problem I'm having though is it introduces some pretty complicated queries where anytime I want to get whether a user can vote, I have to check against the timestamps. I was wondering if anyone had a better way to handle this or a clever way of integrating into the model an 'active' indicator in terms of whether the vote has expired based on the timing of the event. class Vote(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="votes", on_delete=models.CASCADE, ) post = models.ForeignKey( Post, related_name='votes', on_delete=models.CASCADE, ) timestamp = models.DateTimeField(auto_now_add=True) An example query: # Returns an active vote of a user/entrant combo that has not been reset by a voting period. def get_active_vote(self, … -
Django: 'int' object is not iterable when different serializers in a Viewset
I have an issue when making a GET request on this endpoint: /api/stock/{bar_id}/. It should return stock information for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. In order to get the relevant information, I intended on calling the BarDetailsSerializer through the Stock Viewset, thinking it might be easier than having to filter the Stock table according to the bar_id value provided in the URL, as it would automatically provide the Stock collection related to that specific Bar ID. Making a GET request on http://localhost:8000/api/bars/1 (as shown below) provides the information I need. However when I'm trying to get this response via the Stock Viewset with this end-point http://localhost:8000/api/stocks/1 I get the following error: TypeError at /api/stocks/1/ 'int' object is not iterable So is what I'm trying to do even possible in the first place, or is there a better way or some best practise to apply here? Thanks for your responses! Here is my Stock Serializer file: from rest_framework import serializers from ..models.model_stock import Stock from .serializers_reference import * from .serializers_bar import * class StockIndexSerializer(serializers.ModelSerializer): """ Serializer … -
FileNotFoundError at /login/ [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg'
when ever i try to log in this error msg came up in heroku. but in my local machine it's having no problem. dont know wgat to do? here is my setting.py FileNotFoundError at /login/ [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg' Request Method: POST Request URL: https://peaceful-chamber-65312.herokuapp.com/login/ Django Version: 3.1 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg' -
Return value for importlib.import_module()
I have a strage problem with importlib.import_module(). I cannot find documentation which return value is expected. It seems that return values sometimes different. I'm using python3.8 with Django 2.2 and there is a function import_string() https://github.com/django/django/blob/stable/2.2.x/django/utils/module_loading.py#L17 def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError as err: raise ImportError("%s doesn't look like a module path" % dotted_path) from err module = import_module(module_path) try: return getattr(module, class_name) except AttributeError as err: raise ImportError('Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) ) from err The line module = import_module(module_path) imports a module, and sometimes this module has attributes, but sometimes it doesn't. So for example if I do print(dir(module)) sometime I see object like this: ['BaseCache', 'CONNECTION_INTERRUPTED', 'ConnectionInterrupted', 'DJANGO_REDIS_SCAN_ITERSIZE', 'RedisCache', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'functools', 'import_string', 'logging', 'omit_exception', 'settings'] But sometimes it looks like this: ['__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] So obviously for second case next line after import fails: return getattr(module, class_name) I wonder why this may happen? I think it's not backend library problem … -
excel to django 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
Why is it i am receiving this kind of error? utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte ? def excel_cities(request): if request.method == 'POST': file_format = request.POST['file-format'] City_resource = CityResource() dataset = Dataset() new_city = request.FILES['importData'] if file_format == 'xls': imported_data = dataset.load(new_city.read().decode('utf-8'), format='xls') result = City_resource.import_data(dataset, dry_run=True) elif file_format == 'xlsx': imported_data = dataset.load(new_city.read().decode('utf-8'), format='xlsx') # Testing data import result = City_resource.import_data(dataset, dry_run=True) this is my html <form method="post" action="/excel_cities/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="importData"> <p>Please select format of file.</p> <select name="file-format" class="form-control my-3"> <option selected>Choose format...</option> <option>xls</option> <option>xlsx</option> </select> <button class="btn btn-primary" type="submit">Import</button> </form> this is the excel i want to import to django this is the documentation i followed https://dev.to/coderasha/how-to-export-import-data-django-package-series-3-39mk -
In django's view.py, I want to change it to a string form rather than a json form
django: view.py class ListPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PalyerListSerializer react: console.log(player) (4) [{…}, {…}, {…}, {…}] 0: {d_code: 4, name: "test4", position: "RW", code: 1} 1: {d_code: 3, name: "test3", position: "ST", code: 2} 2: {d_code: 2, name: "test2", position: "LB", code: 2} 3: {d_code: 1, name: "test1", position: "RB", code: 1} length: 4 __proto__: Array(0) When I use console.log I want it to be output in string format. I can't use JSON.stringify as I can use the map function. I want to convert it to string format in view.py. How can I convert it? -
Improperly configured error when running django-admin check
I'm relatively new to Django and programming, so I have no idea what caused this error or how to fix it. I asked another question related to the same error but got no responses so here's a simpler version. When I run Django-admin check (along with various other commands not including run server) I get the following error. django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have spent hours googling and nothing I find works (I either get this error or a module not found error). What can I do? here's the full traceback: Traceback (most recent call last): File "/Users/linnea/opt/miniconda3/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/commands/check.py", line 69, in handle databases=options['databases'], File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/translation.py", line 60, in check_language_settings_consistent get_supported_language_variant(settings.LANGUAGE_CODE) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 68, in _setup % (desc, … -
Using CookieCutter-Django & Docker, how do I get a 'hello, world' app to run on the development server?
I am using Django 3.1 in VSC and Docker Desktop for Mac 2.3.0.5. I am following the cookiecutter-django documentation here (https://cookiecutter-django.readthedocs.io/en/latest/developing-locally-docker.html) I have been able to build the stack, run the stack, and execute management commands without errors. I built an app in the second level per the manual fix specified here: (https://github.com/pydanny/cookiecutter-django/issues/1725#issuecomment-407493176) It's a simple 'hello, world' app that I want to run on my local development server. When I'm in my root directory and I run the server, I get ~/ccdocker34 $ docker-compose -f local.yml run --rm django python manage.py runserver Starting postgres ... done Creating ccdocker34_django_run ... done PostgreSQL is available Watching for file changes with StatReloader INFO 2020-09-24 01:13:43,008 autoreload 8 140145520564032 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 24, 2020 - 01:13:43 Django version 3.0.10, using settings 'config.settings.local' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when I access http://127.0.0.1:8000/ the error on Chrome reads: This site can’t be reached 127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED I get a similar result when I attempt to access the paths listed in the "users" app, … -
Django getting one to many on same query
I need to display a view with Courses with its dependable Lectures on an accordion in html. A Course has many Lectures. class Course(models.Model): title = models.CharField(max_length=1500) def __str__(self): return self.title class Lecture(models.Model): title = models.CharField(max_length=1500) course = models.ForeignKey(Course, on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.title It seems like all the examples I have found. Get the relationship after doing a filter or getting the first object like this: Course.objects.first().lecture_set.all() This gets all the lectures for the first one. But I need to get all Courses with all lectures. Something like this: Course.objects.all().lecture_set.all() or Course.objects.filter('all').lecture_set.all() This way I could iterate over Courses and then on each Course iterate again with Course.lectures Does anyone know the best practice to achieve this? -
Upload File using Vue axios and Django Python Backend
I have VueJs as my front end where i have upload component and using formdata to create request and axios to make rest api call to backend written in Django Python. My Front upload method looks like: uploadFiles() { if (!this.currentFile) { this.message = "Please select a file!"; return } else { let formData = new FormData(); formData.append("file", this.currentFile); const instance = axios.create({ baseURL: "<URL>", withCredentials: false, }); instance .post("/test/", formData, { headers: { "content-type": "multipart/form-data", }, }) .then((response) => { console.log("Success!") console.log({ response }) }) .catch((error) => { console.log({ error }) }) } }, Now backed micro service is Django Python where I want to use the file. However i am not getting the file here. Code looks like below @api_view(['POST']) def attachment(request): myFile = request.FILES myfile2 = request.data.initial_data i tried above two ways to extract files from request object but no success, however it works if i send request via postman. -
Need guide on creating Scheduling app using Django
I am trying to create an Event / Meeting Scheduling app similar to www.calendly.com but way less complex and I have a question on how to deal with the availability section. Basically There are two users: 1.Organizer and 2.Participant The organizer can create an event AND choose his availability dates to schedule a meeting with participant. For Example, availability dates can be September 24, 27, and October 2, 4 these 4 days. How can I create this feature? What my model.py would look like? Any help would be appreciated -
How to Replace Django Radio Buttons with PayPal Radio Buttons
Helloo, I am trying to replace my Django Radio buttons for the payment options to be Payal Radio options found in the below link https://developer.paypal.com/demo/checkout/#/pattern/radio I have set my payment options in the forms.py and I am stuck and don't know how to proceed The stripe payment method is working perfectly fine I just want to add the PayPal payment option. This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) Here is the checokout template <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return … -
ALTER COLUMN "active" TYPE boolean USING "active"::boolean
I am currently working through "Django 3 By Example" by Antonio Mele. Chapter 3 has me working through creating a blog application. In the chapter it has me change my database from MySQL to PostgreSQL and then migrate the data. When I migrate the data I get this error: **django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to boolean LINE 1: ..." ALTER COLUMN "active" TYPE boolean USING "active"::boolean** I have gone through some PostgreSQL documentation and back through my code but I am unable to complete the migrate due to this error. I have been stuck at this same place for quite some time and can not seem to isolate the correction for the error. Any help is appreciated. -
Django, problem with the comment form below the post
I just can't figure it out for a very long time, I made a conclusion of comments to posts from the admin panel. But I just can't figure out how to make a comment form right under the post for users to comment. Thanks to all! models.py class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) enter code here def __str__(self): return '%s - %s' % (self.post, self.name) form.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('name', 'body') views.py class HomePage(ListView): model = Post template_name = 'main/index.html' context_object_name = 'posts1' class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' -
How to send large post request in flutter
I'm trying to upload my users' contacts to my server (running django-rest-framework) from flutter, but am having a hard time due to the size of the request. The contacts are sent from a screen within a bottom navigation bar, so I would like to request to continue even when the user switches pages (we're using bloc and flutter clean architecture to organize logic). I looked into https://pub.dev/packages/flutter_uploader and multipart uploads but it seems that most are geared towards files rather than json in the post body. The size of the contacts request is partly due to the included avatar images, encoded in base64. I have them as base64 encoded strings because that is easier to parse and deserialize on the server, and I'm not sure how to parse files in django-rest-framework ModelSerializers. Is there any way to upload a large json (List<Map<String, dynamic>>) request to my server so that: The request continues even when the bloc that called the usecase->repository->remotedatasource.dart is recycled when user selects different window in bottom navigation bar. The request contains the images in a way I can process without too much django-rest-framework code and allows me to automatically save the images to s3 as happens automatically … -
issue with public key stripe in Django
Hey I did all good what I could can't find any error or a miss displaced the keys has anybody ever had this issue ? enter image description here -
Filter ForeignKey choices in an Admin Form based on selections in same models ManytoMany Field?
I am making a "matches" model that currently has these fields in them: event = models.ForeignKey(Event, on_delete=models.RESTRICT) match_participants = models.ManyToManyField(Wrestler, on_delete=models.RESTRICT, null=True, blank=True,) match_type = models.CharField(max_length=25, choices=match_choices, default=BLOCK) match_result = models.CharField(max_length=25, choices=result_choices, default=NOT_OC) winner = models.ForeignKey(Wrestler, on_delete=models.RESTRICT, null=True, blank=True, related_name="winner") In my scenario the "winner" can only be one of the foreignkeys chosen in "match_participants", I would really like to filter the winner field to only those chosen foreignkeys. Is this possible? I know you can filter foreign key selections based on entries into other models, but not too sure about same table entry. Here's a UML example of what my database structure currently is: -
Django - Why is my form invalid when a non-required field is not filled?
My form triggers form_invalid when the field "category" is empty. The weird thing is, when the view displays, the "description" field does not have the asterisk indicating it's required, unlike "name" or "enabled", for instance. Also, when I try to send the form with an empty name, it correctly displays a little yellow mark and says "This field is required", but it doesn't say that when the category is empty. So, it seems to correctly recognize that the category is not required, it just says it's invalid after I send the form. My form looks like this: class ProductForm(forms.Form): name = forms.CharField(max_length=80, required=True) category = forms.ModelChoiceField(queryset=None, required=False, label='Categoría') description = forms.CharField(max_length=150, required=False) price = forms.FloatField(required=True) image = forms.ImageField(allow_empty_file=True, required=False) extras = forms.FileField(allow_empty_file=True, required=False) enabled = forms.BooleanField(required=False, initial=True) def __init__(self, user, *args, **kwargs): self.user = user super(ProductForm, self).__init__(*args, **kwargs) self.fields['name'].label = 'Nombre' self.fields['description'].label = 'Descripción' self.fields['price'].label = 'Precio' self.fields['image'].label = 'Imagen' self.fields['extras'].label = 'Extras' categories = Category.objects.filter(store=Profile.objects.get(user=user).store) if categories.count() == 0: self.fields['category'].required = False self.fields['category'].queryset = categories self.fields['enabled'].label = 'Habilitado' It is included to my view in this way: class ProductCreateView(LoginRequiredMixin, CreateView): template_name = 'products/product_form.html' model = Product fields = ["name", "category", "description", "price", "image", "enabled", "extra"] success_url = reverse_lazy("orders:products") And … -
How can i filter a Product by price in DRF
I have a model class Products in which I simple specify product-URL, product-title and product-price as attributes. and make Serializer.py file use ModelSerializer and pass data to Reactjs Now I can't understand that how can i filter products by there price so if I fetch API in react all High price are sorted first or low after according to user need or our option...thanks -
django Pycharm 2020.2.2 not resolving static files when using "pathlib.Path" to address BASE_DIR
I'm using the latest version of Pycharm, 2020.2.2 and django 3.1. In my project, I removed the default settings.py and created a directory named settings, so the whole project root looks like: tsetmc ├── asgi.py ├── celery.py ├── context_processors.py ├── __init__.py ├── settings │ ├── base.py │ ├── __init__.py │ ├── local.py ├── urls.py ├── views.py └── wsgi.py and in the base.py, I defined the static files setting as: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent ... STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'assets/' ] STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' Everything works fine in the browser and the static files are successfully loaded using the {% static %} tag; However, Pycharm can not resolve any of the static files in the templates. I enabled Django Support, set Django project root and settings in the Pycharm settings accordingly and also set the Template Language as Django; but it didn't solve the issue. After some trial-and-error, I found an odd solution; If I use import os and os.path.join() to locate the static paths, instead of from pathlib import Path and /, Pycharm can resolve the static files without any problem. So when … -
How to show files after clicking on certain category on html/django?
I have an html file that outputs a multilevel list. I'm able already able to get the id of that list with an onClick. What I want to do is that once I've clicked on the list element, a table appears with the files from that category. I don't mind if it reloads the page, but it would be better if it's not needed to. This is what my list looks like: <body> <nav id="navigation"> <ul class="parent"> <li class="big-section">Commissions <ul class="child"> <li class="area" id="Pays">Pays</li> <li class="area" id="Quotas">Quotas</li> </ul> </li> <li class="big-section">Store Rank <ul class="child"> <li class="area" id="Store Rank">Store Rank</li> </ul> </li> <li class="big-section">Ranker <ul class="child"> <li class="area" id="Ranker">Ranker</li> </ul> </li> </ul> </div> </body> This is what my table looks like: <table class="documentTable"> <thead> <tr class="headers"> <th>Document</th> <th>Upload Date</th> <th>Summary</th> </tr> <tbody> {% for f in upload %} <tr class="data"> <td> <a href="{{f.file.url}}" download="{{f.file.url}}">{{ f.title }}</a> </td> <td>{{ f.department }}</td> <td> {{ f.date }}</th> <td> {{ f.summary }}</th> </tr> {% endfor %} </tbody> </thead> </table> This is the javascript I'm using to animate the table and get the id of the clicked list item <script> $("li.area").click(function () { console.log($(this).attr('id')); // jQuery's .attr() method, same but more verbose }); $(function () { … -
Javascript Fetch : Error Unexpected token < in JSON at position 0
I am sending a POST request to my Django view. When I run the code in local it works but when I run it on my apache server it gives me a 500 error. Could you help me, please !! This is my code: form.addEventListener('submit', e=>{ e.preventDefault() const baseInput = document.querySelector('#inputbaseform0') if(baseInput.value !== null){ $('#loadMe').modal('show'); let data = {} data['base'] = baseInput.value data['tiempo'] =tiempo.value data['otros'] =otros.value let url = "{% url 'cal' %}"; fetch(url, { method: "POST", credentials: "same-origin", headers: { "X-CSRFToken": document.querySelector('#form0 input').value, "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }).then(function(response){ return response.json(); }).then(function(data){ console.log('ERROR: ', data.error) baseData = parseFloat(data.base).toFixed(2) deducir.value = data.porciento//porciento $('#loadMe').modal('hide'); }).catch(function (e){ console.log('Error', e); $('#loadMe').modal('hide'); }) } }) }) -
Reverse for 'user-post' not found. 'user-post' is not a valid view function or pattern name
i have created a blog app. when i try to create new posts is shows the following error. i have double check everything. Now i really don't know what to do. urls patterns are urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register,name='register'), path('profile/', user_views.profile,name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('', include('Bblog.urls')), ] [here is my code] https://github.com/coderbang1/Blog/tree/master -
Writing .create() & .update() for multi-level nested serializer in Django
I have Models.py class Zorg(models.Model): name = models.CharField(max_length=100) owner_first_name = models.CharField(max_length=20) owner_last_name = models.CharField(max_length=20) zorg_email_id = models.EmailField(max_length=100) owner_email_id = models.EmailField(max_length=100) open_year_of_zorg = models.CharField(max_length=4) website = models.URLField(max_length=100) base_rating = models.IntegerField(default=2) joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.name class Categories(models.Model): zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE, null=True, related_name='categories') category_name = models.CharField(max_length=100) def __str__(self): return self.category_name + ' - ' + str(self.zorg) class Service(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE,null=True, related_name="services") zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE,null=True, related_name="zorg") service_name = models.CharField(max_length=100) time = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=False) def __str__(self): return self.service_name + ' in ' + str(self.category) Here's my serializer.py class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service exclude = ['id', 'category', 'zorg'] class CategorySerializer(serializers.ModelSerializer): services = ServiceSerializer(many=True) class Meta: model = Categories fields = ['category_name', 'services'] class ZorgSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Zorg fields = [ 'id', 'name', 'owner_first_name', 'owner_last_name', 'zorg_email_id', 'owner_email_id', 'open_year_of_zorg', 'website', 'base_rating', 'categories', ] I am trying to write .create function for it but I am unable to write the proper create function for the zorg serializer. GET is working just fine and I am getting expected results but POST and PUT is where I am having trouble with multi level depth. This is how I want to pass …