Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - NoReverseMatch at /project/3/evillio
I'm working on a portfolio project and i face a strange problem when trying to list a project, ( class-based-views-DetailView). More specifically when trying to list a project for example /project/3/evillio i got following error Reverse for 'project-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['project/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$'] but when i add a new project, i'm able to list /project/3/evillio with no problem, however i got the same error on the next project /project/4/urban. urls.py path('project/<int:pk>/<slug:slug>', WorkProjectsDetailView.as_view(), name='project-detail'), views.py class WorkProjectsDetailView(DetailView): model = Project template_name = 'work/project-detail.html' context_object_name = 'single_project' def get_context_data(self, **kwargs): context = super(WorkProjectsDetailView, self).get_context_data(**kwargs) context['next'] = Project.objects.filter(id__gt=self.kwargs['pk']).order_by('pk').first() return context detail-project.html <div class="projects-list gallery"> {% if projects %} {% for project in projects %} <div class="item brand"> <a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" class="effect-ajax" data-dsn-ajax="work" data-dsn-grid="move-up"> <img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="" /> <div class="item-border"></div> <div class="item-info"> <h5 class="cat">{{ project.category }}</h5> <h4>{{ project.title }}</h4> <span><span>View Project</span></span> </div> </a> </div> {% endfor %} {% else %} <div class="col-lg-8"> <p>No Projects Available</p> </div> {% endif %} </div> Any help appreciated. -
Django Try/Except CBVs dealing with query returning None?
I am trying to include some exception handling to handle queries that return None, If none is returned I just want to display a simple JsonResponse message. Working with FBVs, I've done this pretty simply. But when using class based views, my except block is not doing as I expect. class BusinessDetailView(DetailView): model = BusinessDetail def get_object(self, queryset=None): business = self.model.objects.filter(**custom filters here)).values().first() logger.debug(Business: {business}') return business def get(self, request, *args, **kwargs): try: try: business = self.get_object() except BusinessDetail.DoesNotExist: return JsonResponse({'Error': 'Business Does Not Exist.'}) return JsonResponse(company, status=200) except Exception as e: logger.error(f'Error getting business detail with error: {e}') return JsonResponse({'Error': 'Database error, return to previous page'}, status=500) In the get_object method, the logger is returning Business: None as I expect. But in the get method, the BusinessDetail.DoesNotexist is not getting hit. The last Try/Except block is the one getting hit, returning return JsonResponse({'Error': 'DB error, return to previous page'}, status=500). From my understanding, the DoesNotExist exception would catch the query returning None? But in my case this is not occurring. Any help is greatly appreciated! -
Why i get 'NoneType' object has no attribute 'days_count' this error in my code
I want to multiple days_count * room_service but after multiple i see this outpout which is not suitable . Please See the image where Room_Cost is like 800days, 000 whats the solution please help me.. class PatientDischarge(models.Model): assign_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, null=True) appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=False, null=True) medicine_cost = models.IntegerField(null=True, blank=True) other_charge = models.IntegerField(null=True, blank=True) def __str__(self): return self.appointment.patient.name if all([self.appointment, self.appointment.patient, self.appointment.patient.name]) else 0 def days_count(self): return self.release_date - self.appointment.entry_date if all([self.appointment, self.appointment.entry_date]) else 0 def room_bill(self): return self.days_count() * self.appointment.room_service if all([self.appointment, self.appointment.room_service]) else 0 -
Cannot force an update in save() with no primary key
I am working with a custom build user model in Django and there was some message in the terminal at the time of migrate given in the stackoverflow link. However, I have failed to solve that and it didn't hamper to run the project, so I actually ignore it and continue with my code. Now when I try to log-in to the admin panel(http://127.0.0.1:8000/admin/) it shows the following error: Internal Server Error: /admin/login/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\contrib\admin\sites.py", line 407, in login return LoginView.as_view(**defaults)(request) File "G:\Python\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "G:\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "G:\Python\lib\site-packages\django\contrib\auth\views.py", line 63, … -
Security issue with custom build decorator in Django
I am working with a custom build decorator in Django. my decorators.py: from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.decorators import user_passes_test def industry_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='app2:request_login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_Industry, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator Here is_Industry is a bool value, comes from models.py. my views.py: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inserted_text'] = "inserted text from EmployeeDetails of views.py" return context in urls.py: path('industryDetails/<int:pk>/', views.industryDetails.as_view(), name='industryDetails') models.py also included if you need: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) Now my problem is, suppose a user with having primary_key=3, can easily visite another user's data having primary_key=2, by using http://127.0.0.1:8000/industryDetails/2/ (by changing the primary key in this address path). I need to stop this for my project. How can I code this in such a way that, any user can only visit his own details? -
Best approach for developing a stateful computation-heavy application with a rest-api interface using python?
I want to develop an end-to-end machine learning application where data will be in gpu-memory and computations will run on the gpu. A stateless RESTfull service with a database is not desirable since the traffic between gpu-memory and database will destroy the "purpose" of it being fast. The way I see it is that I need a way to "serve" the class (lets call it as experiment class) which has the data and the methods, then call them using rest apis. Right now I am using FastApi and initialize the experiment class in it which I believe is not optimal. My class (as well as the data) lives in FastAPI runtime. Kinda like, import experiment_class import FastApi app = FastAPI() my_experiment = expertiment_class() @app.get("/load_csv") my_experiment.load_csv("some_file_path") // do some more on the data ... There are two problems I am having a hard time with, One of them is the terminology: Is this really a stateful application ? Is there a word to describe what I am doing ? Is this a "Model, View , Controller" design, can it be a simple "Server-Client" or is it something completely different ? Do I need a "Web-server" , a "Web-framework" or a "Web-service" … -
How can I use voice as an input method in Django and create models using it? How can I get the input from the microphone and send it to the backend?
This is somewhat near to a Virtual Assistant. I know I would require JS for this but how do I get the input and send it to the backend? -
DJANGO_SETTINGS_MODULE Visual Studio Code Terminal Error
Based on other posts, I've added a new .env file within my app but this error is still appearing. I've also added the top setting module in my settings.py file but still no luck. Any thoughts on what's causing this? Visual Studio Code Terminal Error: Traceback (most recent call last): File "c:/xxxx/Python/Price Tracking/Django/mysite/polls/models.py", line 7, in <module> class Question(models.Model): File "C:\Python38\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Python38\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Python38\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Python38\lib\site-packages\django\conf\__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. PS C:\Users\xxxx\Python\Price Tracking\Django\mysite> settings import os from pathlib import Path os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django django.setup() from django.core.management import call_command INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'chartjs', ] C:\Users\xxxx\Django\mysite.env file: DJANGO_SETTINGS_MODULE='mysite.settings' -
How OuterRef works in django?
Im not able to understand how really OuterRef in django ORM works. For example: Table.objects.filter(field=OuterRef("pk")) What does this mean? What role does field and pk play here and how it affects the final queryset? Someone please elaborate. Thanks in advance. -
Django E-commerce From Scratch vs Package [closed]
I'm building an e-commerce store for a startup. It's not huge - the shop will be dropping two types of t-shirts and two types of pants per month. I want to use django for back-end. Should I build it from scratch or use something like Django Oscar (or other packages - WRITE RECOMENDATIONS) and customize it? -
Django Rest Framework to return desired results from two models
I have two models (customer, movie) and I would like to return (movie_name, customer_name, id) when I hit the URL (api/customer/1) and when I hit the URL (api/customer/1/movies) just wanted the movie names alone. How can we achieve this ? models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) class Movie(models.Model): movie_name = models.CharField(max_length=200, null=True) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name') class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/customers/$', CustomerSerializer.as_view(), name='customers'), ] Note: At the moment, when I hit the URL (api/customers) it returns the id, name of all the customers. Now, I would like to know, when I hit the URL (api/customer/1) how to list the same information along with movie names and when I hit the URL (api/customer/1/movies) how to just return the movie names alone? -
What is the best way to pass a parameter from views into an anchor tag?
I'm building a dashboard that has a button on a sidebar that allows a user to update their data. Which currently looks like this: <a class="nav-link" href="{% url 'form-update' pk=id %}"> Questionnaire </a> I'm trying to connect that id field to my views.py: def dashboard(request): user = request.user account = 0 id = Form.objects.filter(author=user,account=account) context = { 'id':id } return render(request, 'dashboard/index.html',context) url pattern: path('update/<int:pk>', FormUpdateView.as_view(),name='form-update') I'm not sure the best way to send this data to the href tag? -
Running "tasks" periodically with Django without seperate server
I realize similar questions have been asked however they have all been about a sepficic problem whereas I don't even now how I would go about doing what I need to. That is: From my Django webapp I need to scrape a website periodically while my webapp runs on a server. The first options that I found were "django-background-tasks" (which doesn't seem to work the way I want it to) and 'celery-beat' which recommends getting another server if i understood correctly. I figured just running a seperate thread would work but I can't seem to make that work without it interrupting the server and vice-versa and it's not the "correct" way of doing it. Is there a way to run a task periodically without the need for a seperate server and a request to be made to an app in Django? -
Django: A GET Request gets submitted after a POST
My Web Form has a JQuery generated list, that is submitted via a Post Request This is the Jquery Generated List: $(function(){ $("#addToList").click(function(e){ var text= $("#txtSearch").val(); $("#nameList").append(`<li>${text} <a href="#" class="remove_this btn btn-danger">remove</a></li>`); $("#txtSearch").val(""); }); $(document).on('click', '.remove_this', function() { $(this).parent().remove(); return false; }); The Text Field used to populate the list is an Ajax Text Field nd is populated using the folowing code: $(document).ready(function(){ $("#txtSearch").autocomplete({ source: "/ajax_calls/search/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); The above generated list is submitted using the following Code On the Press of a Submit Button. $("#submit").on('click', function() { var stocks = getStocks(); $.ajax({ type: 'POST', url: '/analyser', data: {'stocks': stocks, 'csrfmiddlewaretoken': '{{csrf_token}}'}, }); }); The HTML for the same is as below: <form id="search" > <input type="text" id="txtSearch" name="txtSearch"> </form> <div id="listCreate"> <button id ="addToList" >Add to list</button> <ol id="nameList"> </ol> </div> <button id ="submit" form="search" >Analyse</button> The View Handler for the above request is: def function(request): print("Request is ", request.method) if request.method == 'POST': //Code To build Context here context = { "x": y, } return render(request, 'pages/analyser.html', context) return render(request, 'pages/analyser.html') The Problem is that there is an additional GET Request that is getting submitted after … -
Django form not submitting data to database
I've dig through old post about this topic but like allways nothing works for me. My problem is that data isn't saved. I've printed out form and it's okey, then I've printed out forms.is_valid which gave me true, forms.save() also returns customer object so I don't know where to look now (this form updates user shipping data) form class customerUpdate(ModelForm): class Meta: model = ShippingAddress fields = ['city', 'country','zip_code','adress','phone',] exclude = ['customer','order','date_added'] widgets ={ 'city' :forms.TextInput(attrs={'class':'updateForm',}), 'country' :forms.TextInput(attrs={'class':'updateForm',}), 'zip_code' :forms.TextInput(attrs={'class':'updateForm',}), 'adress' :forms.TextInput(attrs={'class':'updateForm',}), 'phone' :forms.TextInput(attrs={'class':'updateForm',}), } Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) city = models.TextField(max_length=50, null=True, blank=True) country = models.TextField(max_length=50, null=True, blank=True) zip_code = models.TextField(max_length=15, null=True, blank=True) phone = models.TextField(max_length=9, null=True, blank=True) adress = models.TextField(max_length=100, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.adress) views def userView(request): userData = request.user.customer forms = customerUpdate(instance=userData) if request.method == "POST": forms = customerUpdate(request.POST, instance=userData) if forms.is_valid(): forms.save() context={ 'userData':userData, 'forms':forms } return render(request,'user.html', context) html {% load i18n %} <div class="editUserInfoWrapper"> <form method="POST" action="{% url 'user' %}"class="formUserPanel" > {% csrf_token %} <div class="container"> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="form-group"> {{ forms.city }} </div> </div> <div class="col-sm-12 col-md-6"> <div class="form-group"> {{ forms.country }} </div> </div> … -
Django model override save() method raises error when calling super()
I have the following Django model: class TCDUser(AbstractUser): is_change_password = models.BooleanField(_("Cambiar Password?"), default=True) groups = models.ManyToManyField(Group, default=[], related_name='users', verbose_name=_("Grupos")) class Meta: verbose_name = _("Usuario") verbose_name_plural = _("Usuarios") def __str__(self): return "[{}]{}".format(self.pk, self.username) def save(self): create = True if self.id is None else False if create: self.set_password(self.password) super(CustomModel).save() And this is the serializer: class TCDUserSerializer(CustomModelSerializer): class Meta: model = models.TCDUser fields = ('id','username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'password', 'is_change_password', 'groups') When I send a POST to the regular DRF ModelViewSet, I get this exception: TypeError: Got a `TypeError` when calling `TCDUser.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `TCDUser.objects.create()`. You may need to make the field read-only, or override the TCDUserSerializer.create() method to handle this correctly. If I remove the call super(CustomModel).save(), the exception is no more, but I need to set the password when the user is created. -
How to load static css file inside extended template
I have a base.html file which contains the base of all of the HTML pages. I want to create 404.html page: {% extends 'base.html' %} {% block title %} Page 404 {% endblock title %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static '404_style.css' %}"/> {% block content %} <!-- HTML code here --> {% endblock content %} The tree: ./app/app |-- ./app/app/settings.py |-- ./app/app/static | |-- ./app/app/static/404_style.css | `-- ./app/app/static/style.css |-- ./app/app/templates | |-- ./app/app/templates/404.html | |-- ./app/app/templates/base.html | |-- ./app/app/templates/homepage.html |-- ./app/app/urls.py |-- ./app/app/views.py I don't understand why it does not load 404_style.css. My guess is that it is not inside the head tag (which is in base.html. So I tried to add {% block extra_head_content %}{% endblock %} inside the head tag inside base.html but it does not work. How can I load static css file inside extended template? -
Sort objects by interaction time grouped by users in Django
I have a Django app (I use Postgresql for the database), and I have these models of Customers, Products and Transactions that are connected as follows: class Customer(models.Model): products = models.ManyToManyField(Product, through='Transaction') class Product(models.Model): ... class Transaction(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) transaction_timestamp = models.DateTimeField(auto_now=True) The transaction model tracks the time when a customer interacted with a product. I have a list of user ID-s users. I want to get a list of say 1000 products they last interacted with for every customer in users. Is there any way of doing this faster than iterating all the users? I assume this might be done through Aggregation somehow, but I couldn't find anything that worked in my case. -
How to handle PUT request for a model with an extended user(onetoone field) relationship django rest framework
I have a profile model with a onetoone relationship with the django User model, I created an API endpoint which works fine for get and post request but when I try to do a put request to edit some part of the data, it gives me this error. { "user": [ "This field is required." ] } This is my Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) This is my Serializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id' ,'username', 'first_name', 'last_name', 'email', 'password') extra_kwargs = { "password": {"write_only": True}, } class ProfileSerializer(serializers.ModelSerializer): """ A student serializer to return the student details """ user = UserSerializer() class Meta: model = Profile fields = ('uid', 'user', 'bio', 'location') # read_only_fields = ('user',) def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user instance.bio = validated_data.get('bio', instance.bio) instance.location = validated_data.get('location', instance.location) instance.save() user.username = user_data.get('username', user.username) user.first_name = user_data.get('first_name', user.first_name) user.last_name = user_data.get('last_name', user.last_name) user.save() return instance -
How to install cruds_adminlte correctly?
I'm going round in circles here. I followed the basic installation instructions here, which seemed simple enough: pip install django-cruds-adminlte As I was reading the page from top to bottom (that's English) I then installed the following: pip install django-crispy-forms pip install easy-thumbnails pip install django-image-cropping pip install djangoajax I then started to hit a series of problems: 1: ModuleNotFoundError: No module named 'six' Applied this fix: $ pip install six 2: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Applied this fix: $ pip install --user --editable git+git://github.com/oscarmlage/django-cruds-adminlte/@0.0.17+git.081101d#egg=django-cruds-adminlte 3. django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'cruds_adminlte.templatetags.crud_tags': cannot import name 'six' from 'django.utils' (C:\Python\Python39\lib\site-packages\django\utils\__init__.py) Applied this fix: pip install six change templatestags/crud_tags.py line 11, from 'from django.utils import six' to 'import six' 4: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'crispy_forms.templatetags.crispy_forms_field': No module named 'django.utils.lru_cache' and, having re-read the documentation to learn that dependencies have to be installed first, decided to uninstall and start again: pip uninstall django-cruds-adminlte pip uninstall django-crispy-forms pip uninstall easy-thumbnails pip uninstall django-image-cropping pip uninstall djangoajax pip uninstall django-select2 This left me with the … -
How to set daily Update limit on Django model
I'm new to Django. I have created one Django App where users can update their Shift Timing(Morning/Evening/General) and based on this Shift Timing I am taking real-time data from Django Model and running Linux script which will be evaluating user shift timing and allowed timing to use the application. I have used Django import and export which allow the user to upload multiple users' data by using a .xls file from the front-end. Now here I want to apply some limit for example suppose my model is having 5000 records so I want that only 50% of its records should be allowed to modified whether it is added through .xls file or by clicking on update single records(I am doing this because I don't want that more than 50% of users should update Shift Timing). Is there any easiest way to implement this requirement? I have checked https://pypi.org/project/django-limits/ (django-limits 0.0.6)but did not understood from step 3. I am adding my models.py class CTS(models.Model): AConnectID = models.CharField(max_length=100,) Shift_timing = models.CharField(max_length=64, choices=SHIFT_CHOICES, default='9.00-6.00') EmailID = models.EmailField(max_length=64, unique=True, ) Vendor_Company = models.CharField(max_length=64, ) Project_name = models.CharField(max_length=25, default="") SerialNumber = models.CharField(max_length=19, default="") Reason = models.TextField(max_length=180) last_updated_time = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def … -
IntegrityError UNIQUE on blog_post.slog despite creating unique slug function
I am new to django and somewhat new to python too. I am trying to create a simple blog application and as we all know you want to have unique slugs for your blog links. However I cannot seem to rid myself of this UNIQUE error. Problem description When I create a blog post I create a slug from the title. Then I see if that slug matches any others in the database. If it does, I add a little string to the end. Nevertheless, the database keeps throwing an IntegrityError. What I've tried I have been using import pdb; pdb.stack_trace() to try to trace the issue. It seems to me to happen after setting self.object.slug and then doing self.object.save(). Somehow the unique slug is may not be be being passed to save.(). But I'm not sure how to debug beyond this point. I'd appreciate help in the debugging process. The confusing thing is that I'm working from a (functioning) django blog app. I cannot find the difference between my code and that one, and I've tried changing the methods.py and views.py to match that of the other blog, and yet that app produces unique slugs and throws no errors, … -
Django / Visual Studio Class has no Object Errro
I am receiving the following error in my Visual Studio code. There are no errors in my models.py file that this views.py file draws from, but when I debug in views.py in visual studio I get this error. Based on other posts, I've pip installed pylint but that has not resolved the issue. Any suggestions on how to resolve this? view.py from .models import Question, Owner, Stakeholder class StakeholdersView(generic.ListView): template_name = 'polls/stakeholders.html' context_object_name = 'stakeholder_list' def get_queryset(self): return Stakeholder.objects.order_by('id') Class 'Stakeholder' has no 'objects' member -
#djangoMigrationerror #manage.pyError
Currently I'm using Django 3.1.4 and when I migrate or make migrations, it was able to do the migration, but it also show this following message (please note that mysite is the name of app that I making on project): No changes detected in app 'mysite' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable` python manage.py makemigrations mysite No changes detected in app 'mysite' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PARMANAND\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, … -
Django AppRegistryNotReady Exception after import from django.contrib.auth.models
Here is my folder structure: . ├── app ├── project ├── scripts └── tests ├── fuctional -> test_views.py └── unit Here is my test_script.py from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from rest_framework.test import APIClient from mrx.views import LoginView, LogoutView When I launch python -m unittest tests/fuctional/test_views.py I get this error: Traceback (most recent call last): File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/__main__.py", line 18, in <module> main(module=None) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 147, in parseArgs self.createTests() File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 158, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "/home/edx/PycharmProjects/mrx_3/tests/fuctional/test_views.py", line 3, in <module> from django.contrib.auth.models import User File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 136, in …