Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelform widget attributes replaced or disregarded
I've been scratching my head over this for the last little while. I have been able to change the modelfield's field queryset and widget attributes, well somewhat! class InvoiceItemForm(ModelForm): UOM = forms.ChoiceField (choices = site_defaults.UOM) class meta: model = InvoiceItem fields = ['name', 'costcode', 'rate', 'quantity',] labels = {'name': 'Item', 'rate': 'Cost Per Unit', 'quantity': 'Base Quantity'} widgets = {'UOM': forms.Select(choices = site_defaults.UOM )} def __init__(self, current_user, current_project, *args, **kwargs): ''' Rendering custom ModelForm ''' super(InvoiceItemForm, self).__init__(*args, **kwargs) the_title = None the_instance = kwargs.get('instance', None) if the_instance: the_costcode = the_instance.costcode if the_costcode: the_title = the_costcode.title self.fields['costcode'].queryset = CostCode.objects.filter(project = current_project, item = 0) self.fields['costcode'].widget = forms.TextInput(attrs={'class': 'site-flex-select-large', 'value': the_title}) When this is rendered, the costcode field takes the right instance. Also, the class is shown as site-flex-select-large, but the title is shown as the instance.id and not the_title which is the instance.title (a text field is displayed with value of 192 instead of the title of the invoice item). Why is Django ignoring some changes and accepting some other changes to the field? I'm not sure if it is a relevant detail or not, but the modelform is used in an inlineformset: expenses_forms = self.InvoiceItem_InlineFormSet(instance = the_invoice, prefix='expenses', form_kwargs={'current_user': user, … -
Reverse for 'patient_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['patients/update/(?P<pk>[0-9]+)$']?
I made a view where users can edit the patients information and as I'm using a custom user model I had to make a custom update/delete view.The views are working when i enter them manually by the url but when i put a link reference to them by an anchor tag i get an error that it can't access the pk,I tried following many answers here and vids on YT but the error is still there Views.py def PatientUpdateView(request,pk=None): patient = get_object_or_404(models.Patient, pk=pk) form = forms.PatientForm(request.POST or None ,instance=patient) if form.is_valid() : patient = form.save(commit=False) patient.save() messages.success(request,"patient updated!") context = { 'patient': patient, 'form': form } return render(request,'patients/patient_edit_form_success.html',context) else: context = { 'patient' : patient, 'form': form, } return render(request, 'patients/patient_edit_form.html', context) and here's how i call it in an anchor tag <a class="btn btn-info btn-sm" href="{% url 'patients:patient_update' patient.pk %}">Open</a> I tried pk = patient.pk pk = pk and many other ways of calling it. -
How do you use downloaded templates in Django
I have found these really cool templates online and I would like to use them for building my website. Is there any way of not copying the links for bootstrapping but for me to use the templates downloaded and tweak them? I have looked online and all they suggested was bootstrapping. -
Django - How to serialize inheritance
I walked through the documentation at https://django-model-utils.readthedocs.io/en/latest/managers.html to learn more about the InheritanceManager.I won't add the models.py because it is the same as in the documentation. So, here is my views.py: class PlaceList(generics.ListAPIView): serializer_class = PlaceSerializer def get_queryset(self): return Place.objects.select_subclasses() As you can see, the line return Place.objects.select_subclasses() returns all the Bar, Restaurant or Place instance stored in the database. My serializers.py looks like the following: from rest_framework import serializers from genericRelations.models import Place, Restaurant, Bar class PlaceSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id', 'location') class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = ('id', 'location', 'restaurant_name') class BarSerializer(serializers.ModelSerializer): class Meta: model = Bar fields = ('id', 'location', 'bar_name') I do not know how to modify the PlaceSerializer so that it also serializes/deserializes the subclasses of Place. E.g. something like 'if a Bar instance is encountered, then use the BarSerializer' and 'if a Restaurant instance is encountered, then use the RestaurantSerializer'. Note: When the URL is .../places/ then PlaceList is performed which results in this output: { "places": [ { "id": 1, "location": "Köln" }, { "id": 2, "location": "Köln" }, { "id": 3, "location": "Köln" }, { "id": 4, "location": "Köln" }, { "id": 5, "location": "Köln" … -
How to connect REST API built using Django Rest Framework with Flutter app
I am building an application to register details of user for which I have used Django rest framework for backend and Flutter for frontend. I am having no idea on connecting these two. Please help me. -
How do I validate a field based on it's initial value in forms.py?
I have a custom self.clean method in forms.py which contains a check on whether the POSTed date values overlap with existing records. In the case where the user edits their record, but does not change the dates, this validation stops the record update. How can I change the validation with If statement or otherwise dependant on if the user has modified the start_date or end_date fields? I've tried looking at things like self.get_initial() and self.has_changed() which seem to only be applicable in the view function? I'd rather validate in forms.py. If I could filter out the record currently being edited from my "overlap" validations, that may be the neatest solution. forms.py: class EditBookingForm(ModelForm): class Meta: model = Bookings #user not included as that is handled in views fields = ['start_date', 'end_date', 'type', 'approved', 'members', 'guests'] ... def clean(self): form_data = self.cleaned_data #check if dates overlap by more than one day (ie. can start/end on the same day) overlap_in = Bookings.objects.filter(start_date__lt=form_data['start_date'], end_date__gt=form_data['end_date']).count() overlap_st = Bookings.objects.filter(start_date__lt=form_data['start_date'], end_date__gt=form_data['start_date']).count() overlap_end = Bookings.objects.filter(start_date__lt=form_data['end_date'], end_date__gt=form_data['end_date']).count() overlap_same = Bookings.objects.filter(start_date=form_data['start_date'], end_date=form_data['end_date']).count() overlap_over = Bookings.objects.filter(end_date__gt=form_data['start_date'], start_date__lt=form_data['end_date']).count() overlap = overlap_end + overlap_in + overlap_same + overlap_st + overlap_over if overlap > 0: self._errors["start_date"] = ["Your dates overlap with an existing … -
display user profile images of chats
All is working good except of the fact that, i am trying to display user profile images of user who sent a chat message in a chat room . chatSocket.onmessage=function(e){ var tag_img=document.createElement('img'); var get_user=document.querySelector('#user').value var tagname=document.createElement('li'); var data =JSON.parse(e.data); // get the image and display document.querySelector('.img_tag').src=data.message.sender_img This is my consumer.py messaage_json={ 'user':me.username, 'message':message_object.message, 'sender':message_object.sender.username, 'sender_img':str(message_object.sender.profilepicture), 'created':str(message_object.created) } data_array=await self.get_data() #coverting data to string myResponse={ "message":messaage_json, } #broad cast the message event to be send # in the layaer await self.channel_layer.group_send( self.room_group_name,{ # call the chat_message method "type":"chat_message", #covert string data to json objects "text":json.dumps(myResponse), } ) It prints out the user profile image path in the media file, but cannot display the image using javascript. Note i am using django . -
I have a field: forms.CheckboxSelectMultiple(). How can I access it's options in JS?
I'm setting up a form, which has a field = forms.CheckboxSelectMultiple() The field is a ManyToMany field of a model. It'll display the options that the model has to relate to the other fields. models.py class Tag(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class Entry(models.Model): # ...other fields tags = models.ManyToManyField(Tag, related_name='entries', blank=True) #other fields... And the form: class NewEntryForm(forms.ModelForm): # ...other code 'tags': forms.CheckboxSelectMultiple(attrs={ 'class': 'form_new_entry_tags', 'id': '' }), I want to access the text of the options (the options would be all the tags available), in JS, so as to display it on another place when the checkbox is checked. The text is not the input's value, as one might think it'd be. It is html that comes directly from the django form, which seems to not have a selector. I'm trying to do this: let display_when_checked = document.querySelector("#display") let checkbox = document.querySelector("#checkbox") checkbox.addEventListener('change', function() { if (this.checked) { display_when_checked.innerHTML = checkbox_value } } But I can't access checkbox_value. And the HTML is: <ul> <li> <label> <input type="checkbox" value="1" class="form_new_entry_tags"> "text of the option" <--- I want to access this. </label> </li> </ul> When I hover with the dev tools in the browser, the selector for … -
Request attributes
I have a page, and there are 3 types of button(apple,banana, orange), by clicking the first button, a form comes up to get information. The first button should send information to the apple Model, the banana button should send information to the banana Model and so orange! here is my models.py: from django.db import models class Apple(models.Model): first_name = models.CharField(max_length=100) class Banana(models.Model): first_name = models.CharField(max_length=100) class Orange(models.Model): first_name = models.CharField(max_length=100) my forms.py: from django import forms class Fruit(forms.Form): first_name = forms.CharField(max_length=100) my views.py: def fruitForm(request): form = Fruit() if request.method == 'POST' & request.id == 'apple': form = Fruit(request.POST) if form.is_valid(): Apple.objects.create(**form.cleaned_data) elif request.method =='POST' & request.id =='orange': form = Fruit(request.POST) if form.is_valid(): Orange.objects.create(**form.cleaned_data) elif request.method =='POST' & request.id =='banana': form = Fruit(request.POST) if form.is_valid(): Banana.objects.create(**form.cleaned_data) return render(request, 'main/home.html', {'form':form}) my home.html: <button class='btn btn-primary' data-target='#orange'> Add </button> <form action=# method="POST" id = "orange"> {% csrf_token %} {{ form.as_p }} </form> well, when I try go to main page (where the buttons are), I got this error: 'WSGIRequest' object has no attribute 'id' request doesn't have the id attribute, right? So, How can I get specific data to save in relative model? -
AttributeError: module 'asyncio' has no attribute '_get_running_loop'
I am using channels to implement WebSockets. I am trying to send data through websocket from post_save django signal. Below is my code. signals.py @receiver(post_save, sender=CheckIn) def send_data_on_save(sender, instance, **kwargs): channel_layer = get_channel_layer() stats = get_stats() async_to_sync(channel_layer.group_send)( 'dashboard', { 'type': 'send_data', 'message': stats } ) analytics = get_analytics() async_to_sync(channel_layer.group_send)( 'analytic', { 'type': 'send_data', 'message': analytics } ) consumers.py class DashboardConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'dashboard' # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'send_data', 'message': message } ) # Receive message from room group def send_data(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) this same piece of code is working on my local machine(windows) but when i am trying to run this code on server(ubuntu 16.04) i am getting bellow error: Traceback Exception inside application: module 'asyncio' has no attribute '_get_running_loop' File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step result = coro.throw(exc) File "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/user1/demowebapps/env/lib/python3.5/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, … -
The delete view doesn't erase the correspondent object
I'm developing the backend of my personal blog and I've create a view that delete a single tag of the post. views.py from django.shortcuts import get_object_or_404, redirect, render from django.utils.text import slugify from .forms import BlogTagForm from .models import BlogTag def deleteBlogTag(request, slug_tag): if request.method == 'POST': tag = BlogTag.objects.get(slug_tag=slug_tag) tag.delete() return redirect('tag_list') models.py from django.db import models from django.urls import reverse class BlogTag(models.Model): tag_name = models.CharField( 'Tag', max_length=50, help_text="Every key concept must be not longer then 50 characters", unique=True, ) slug_tag = models.SlugField( 'Slug', unique=True, help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents", ) def __str__(self): return self.tag_name def get_absolute_url(self): return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag}) class Meta: ordering = ['tag_name'] urls.py path("tags/", views.listTagAdmin, name='tag_list_admin'), path("create-tag/", views.createBlogTag, name='create_tag'), path("update-tag/<str:slug_tag>/", views.updateBlogTag, name='update_tag'), path("delete-tag/<str:slug_tag>/", views.deleteBlogTag, name='delete_tag'), tag_list.html <table class="table table-striped"> <thead class="bg-secondary text-white"> <tr> <th colspan="3"><h1 class="text-center"><strong>Tag List</strong></h1></th> </tr> <tr> <th colspan="1">Tag</th> <th colspan="1">Related Posts</th> <th class="text-center" colspan="1">Actions</th> </tr> </thead> <tbody> {% for tag in tag_list %} <tr> <td colspan="1">{{ tag.tag_name }}</td> <td colspan="1"><a href="{{ tag.get_absolute_url }}">{{ tag.tag_blogpost.count }}</a></td> <td colspan="1"> <div class="row justify-content-md-center"> <a class="btn btn-success btn-sm mx-1" href="{% url 'update_tag' slug_tag=tag.slug_tag %}">Update</a> <button class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal" data-target="#deleteModal">Delete</button> <div class="modal fade" … -
Django E.408, E.409 and E.410 errors on runserver
I am installing a new Django project using virtualenv, all in the normal way. My version of Python is 3.7.3, and django is 2.2.3. If I do python manage.py runserver, I get the following errors: ?: (admin.E408)'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. Here is my settings.py, and you can see that those middleware are there. """ Django settings for fcc_new project. Generated by 'django-admin startproject' using Django 1.9.4. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = MY KEY goes here # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django model CreateView does not render form fields in HTML
I am trying to setup a class based 'CreateView' for a model in my django site, but when the create html page renders, the model fields are not rendered. Only the submit button shows up on the web page. However, when debugging, I overrided the 'form_invalid' method in the class view, and the form object had the required HTML for all fields stored in the object. If I take this HTML and manually add it to the HTML of the create page in the browser I can fill out the fields and post the data to the database. At this point I have not found an obvious answer as to why the form fields are not rendered so any help on this would be greatly appreciated. environment used: python 3.7.3, django 2.2.3 models.py: class Alert(models.Model): RAIN = 'Rain' SNOW = 'Snow' COLD = 'Cold' HEAT = 'Heat' WEATHER_CHOICES = [ (RAIN, 'Rain'), (SNOW, 'Snow'), (COLD, 'Cold'), (HEAT, 'Heat'), ] DAILY = 'Daily' WEEKLY = 'Weekly' INTERVAL_CHOICES = [ (DAILY, 'Daily'), (WEEKLY, 'Weekly'), ] weather_type = models.CharField(max_length=15, choices=WEATHER_CHOICES, default=RAIN) interval = models.CharField(max_length=10, choices=INTERVAL_CHOICES, default=DAILY) search_length = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) active = models.BooleanField(default=False) views.py: class CreateAlertView(LoginRequiredMixin, CreateView): template_name = 'users/alert_form.html' … -
Error while entering the login form details based on signup form
I am trying to enter the details in login form.But it is not authenticating the username and password with the existing usernames and passwords present in form data. Here is my code views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth import authenticate, login, logout from . forms import signup_form,loginform,profileform from . models import registration_form def index(request): return render(request,'loginapp/index.html') def display_form(request): rform = signup_form(request.POST) if rform.is_valid(): rform.save() return HttpResponseRedirect('/profile/') else: return render(request,'loginapp/first.html',{'rform': rform}) def login_form(request): if request.method == 'POST': Username = request.POST.get('Username') Password = request.POST.get('Password') registration_form= authenticate(Username=Username,Password=Password) print("Username") if registration_form is None: if registration_form.is_active: login(request,registration_form) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used Username: {} and Password: {}".format(Username,Password)) return HttpResponse("Invalid login details given") return HttpResponseRedirect('/profile/') else: return render(request, 'loginapp/login.html', {}) def profile_form(request): return render(request,'loginapp/profile.html') -
How do I use BeautifulSoup to search for elements that occur before another element?
I'm using BeautifulSoup 4 with Python 3.7. I have the following HTML ... <tr> <td class="info"><div class="title">...</div></td> </tr> <tr class="ls"> <td colspan="3">Less similar results</td> </tr> <tr> <td class="info"><div class="title">...</div></td> </tr> I would like to extract the DIVs with class="title", however, I only want to find the ones that occur before the element in the table whose TD text = "Less similar results". Right now I have this elts = soup.find("td", class_="info").find_all("div", class_="title") But this returns all DIVs with that class, even ones that have occurred after the element I want to screen for. How do I refine my search to only include results before that particualr TD? -
Static file collections - Logo navbar does not show up
I am trying to have an image (logo) on the navbar. My project is called "mysite-project" (where manage-pyis), it contains the app "mysite". In order to upload my static file I did the following: 1) mysite-project/mysite/settings.py I added: STATIC_ROOT = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static/') ] 2) Created folders static and added my logo.png in: mysite-project/static/mysite-project/logo.png 3) mysite-project/templates/base.html {% load staticfiles %} <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="{% static 'mysite/logo.png' %}" height=30 width=30 class="d-inline-block alighn-top" /> Code of Conduct </a> </nav> HOWEVER the image does not show up. I think I have some issues in the settings.py for the folders but I cannot find where -
What is different between django foreigin key in string and without string?
I am not getting why people write foreign key in two way and what is the purpose of this? are they both same or any different? I notice some people write like: author = models.ForeignKey(Author, on_delete=models.CASCADE) and some people write it like: author = models.ForeignKey('Author', on_delete=models.CASCADE) What is different between these? is there any special purpose of writing like this or they both are same? -
Creating a React-Django full stack web app. How to proceed?
I am building a webpage which uses django-rest-framework and react as a frontend. The main aim is to get some data from the frontend or react component, using rest api, then working on that data with python code to make a csv file of the data that i want to display on my next component of react. How should i proceed? I am a beginner in both django and react. Very confused how to take data from react form and then use it in django python code. Very confused how to use csv file in django and manipulate it. Please help. Suggest me some tutorials or something to go forward. -
Unable to use double braces to resolve variables
I am unable to use double braces to resolve variables. Here's my js code. var app = angular.module('toDo',[]); app.controller('toDoController', function($scope, $http) { $http.get('/todo/api/').then(function(response) { $scope.todoList = response.data; }); }); HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>To Do List</title> {% load static %} <link rel="stylesheet" href="{% static 'css/todo.css' %}"> </head> <body ng-app="toDo" ng-controller="toDoController"> <h1>Todo List</h1> <form ng-submit="add()"> <input type="text" ng-model="todoInput" placeholder="Add a new todo task..."> <button type="submit">Add Task</button> </form> <br> <div ng-repeat="todo in todoList"> <input type="checkbox" ng-model="todo.done"><a ng-href="/todo/api/{{todo.id}}" ng-bind="todo.task"></a> </div> <p> <button class="delete" ng-click="delete()">Delete</button> <button class="update" ng-click="update()">Update</button> </p> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js"></script> <script src="{% static 'js/todo.js' %}"></script> </body> </html> tasks which displayed in screen should redirect me to the url "/todo/api/". But values given in the braces not resolving it's ID. Currently the hyperlink redirecting always to the url "/todo/api/". Kindly let me know if I am doing anything wrong or help me to fix this issue. -
Google Re-captcha with Django 2 built-in LoginView
I'm working with a project using Python(3.7) and Django(2) in which I have to implement Google's Recaptcha. For authentication I'm using the built LoginView from Django,contrib.auth.views, How can I validate the captcha by utilising this auth view? Here's what I have tried so far: From urls.py: path('login/', LoginView.as_view(extra_context={'key': settings.RECAPTCHA_PUBLIC_KEY}), name='login'), From login.html: <form action="{% url 'login' %}" method="post" class="p-3"> {% csrf_token %} <div class="form-group"> <label for="recipient-name" class="col-form-label">Username</label> <input type="text" class="form-control" placeholder=" " name="username" id="recipient-name" required=""> </div> <div class="form-group"> <label for="password" class="col-form-label">Password</label> <input type="password" class="form-control" placeholder=" " name="password" id="password" required=""> </div> <div class="form-group"> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{{ key }}"> {{ key }}</div> </div> <div class="right-w3l"> <input type="submit" class="form-control" value="Login"> </div> </form> -
Integrating Vue.js with Django
Vue.js has some modules that can help me to build my web app using Django. Is there any way to to integrate Vue.js with Django (Python)? -
how to print the context added template returned by the view
Just in curiosity to know , i want to get the printed html along with context that is returned by my view .(I want get it printed on server side only). eg def my_view(request): template='product/compare-in-box.html' context={"data": instance,} # print(render(request , template ,context)) the thing i was trying to print but not working as i expect. render(request , template,context) how this can be achieved? -
Django: Get page title from middleware
I have a small middleware I wrote to keep track of user activity: class AccessLogs(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if "/media/" not in request.path: # Add the user and page info into DB try: ActivityLog(user=request.user, pageURL=request.path).save() except Exception as e: print(e) return response Is there any way I can get the title of the page using this method of middleware? I have looked up a LOT of stuff here like templateview, custom response but nothing seems to be working. Is there any class or function that retrieves the visited page's title? Any help would be really appreciated. -
in django app even if migration folders files are deleted this error exists 'relation "blog_no_of_views" does not exist'
i was using sqlite in the beginning but now i tried switching to postgresql and tried executing makemigrations command, now i am getting below error (youngmindsenv) E:\young_minds\heroku\youngminds>python manage.py makemigrations Traceback (most recent call last): File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends \utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "blog_no_of_views" does not exist LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core as suggested in answers by others as i don't worry about losing the data, so i deleted the tables and database as well,i have deleted the migration folder files and created init.py inside it and tried makemigrations command but still i am getting the above error, i am so confused from where is it getting that error since there is no files in apps migrations folder it gives error in all of below commands as well ./manage.py clear_cache ./manage.py clean_pyc ./manage.py reset_schema ./manage.py reset_db please help me i am so troubled by this. Thanks in advance! -
Django Rest Framework, Registering viewset with router breaks everything - circular import, "Module" object is not iterable
Currently trying to configure my project to work with a router as I plan on using multiple viewsets, all the components seem to work individually, specifying the path manually produces no errors and works as intended. However once i attempt to register my viewset with the router it all explodes Have compared what I've done to the tutorial on the Django Rest Framework site and everything seems to be done correctly. Have broken it down to the smallest components I am able to comprehend and still not sure. My code: urls.py # endpoint templateResponder = TemplateViewSet.as_view({ 'get': 'gotget', 'post': 'gotpost', }) # define router and add viewsets router = DefaultRouter() router.register(r'template', views.TemplateViewSet) # THIS LINE IS BREAKING EVERYTHING urlpatterns = [ # path('template/', templateResponder, name='templateResponder'), # If i add the viewset manually it works path('', include(router.urls)), path('response', views.request_maker), path('json', views.response_maker), ] my viewset class TemplateViewSet(viewsets.ViewSet): """ The Template ViewSet """ # serializer = TestSerializer # currently not used # need to specify a queryset maybe? @action(detail=False, methods=['GET']) def gotget(self, request): return Response("A GET request has been received!!!", status=status.HTTP_200_OK) @action(detail=True, methods=['POST']) def gotpost(self, request): return Response("A POST request has been received!!!", status=status.HTTP_201_CREATED) I get these errors upon attempting to run. If …