Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django getting (AttributeError: 'str' object has no attribute 'get') after submitting a form
I am studying django recently, and I met problem, Internal Server Error: /event_edit Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/workspace/CalendarProject/cencal/views.py", line 107, in event_edit if form.is_valid(): File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 381, in full_clean self._clean_fields() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 393, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/usr/local/lib/python3.7/site-packages/django/forms/widgets.py", line 258, in value_from_datadict return data.get(name) AttributeError: 'str' object has no attribute 'get' This error message appeared while doing form.is_valid(), but I can't know what is the problem. There was surely no problem with form field values. If you need any additional informations for this, I am ready to do it. -
Paginator problems on class based views in django
I'm trying to add the pagination functionality on my project that has a plog section. On this project I have different types of page that needs to display some content and to be more efficient I've mad a single model that hold all types of pages. On the page section I want to display just the pages that has the blog_post=True and apply a pagination. I've tried that on my class based view but the paginator is not working. It show me correct number of post per page, is showing the pagination buttons but when I try to acces another page, for example next page it give an error like this, but on the url I know that should display me something like blog/?page=2 but it displays me this "http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E" class BlogListView(generic.ListView, MultipleObjectMixin): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') Models.py class Page(models.Model): class Meta: ordering = ['slug'] blog_post = models.BooleanField(_("Blog Post"), blank=False, default=False) title = models.CharField(_("Title"), blank=True, max_length=100, unique=True) slug = models.SlugField(_("Slug"), unique=True, max_length=100, blank=True, null=False) breadcrumb_title = models.CharField( _("Breadcrumb Title"), blank=True, max_length=100, null=False, default='') text = MarkdownxField(_("Text"), blank=True, null=False) description = models.TextField( _("Meta Description"), blank=True, null=False, default='') keywords = models.TextField( _("Meta Keywords"), … -
Pytest after running all tests raises AttributeError: 'ReprExceptionInfo' object has no attribute 'rsplit'
I use the pytest-django package for testing in the project. When running pytest for my Django project, I run into an exception that shows up after the whole tests have been ran, hence does not show the test results. This happened on OSX. The following is the complete stacktrace of the error. Nothing that leads back to my code whatsoever. Really frustrating. Traceback (most recent call last): File "/Users/oluwanifemi/Desktop/projects/env/bin/pytest", line 8, in <module> sys.exit(console_main()) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main code = main() File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/config/__init__.py", line 164, in main ret = config.hook.pytest_cmdline_main( File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/hooks.py", line 286, in __call__ return self._hookexec(self, self.get_hookimpls(), kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 93, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 84, in <lambda> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 187, in _multicall res = hook_impl.function(*args) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 80, in get_result raise ex[1].with_traceback(ex[2]) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 187, in _multicall res = hook_impl.function(*args) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/main.py", line 306, in pytest_cmdline_main return wrap_session(config, _main) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/main.py", line 257, in wrap_session session.exitstatus = doit(config, session) or 0 File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/hooks.py", line 286, in __call__ return self._hookexec(self, self.get_hookimpls(), kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 93, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 84, in <lambda> self._inner_hookexec = … -
Remove _id automatically appended by Django in case of foreign key
account_number = models.ForeignKey("commuter.Account", on_delete=models.CASCADE, db_column="account_number ") -
Am I unable to use sendinblue with heroku?
I just deployed a tiny website to Heroku and it uses SendInBlue as the SMTP. It's not sending any of the messages. Does Heroku force you to use one of their add-ons and refuse to let you use other types of SMTP servers? -
How do I add more than one dictionary list to a Django return render call?
Hey guys I'm trying to send more than one dictionary list to a certain HTML template from Python. I know how to do it with one list. How would I send more than one? In my example below I am sending the list newquery to the render request so that I can use it in my HTML. But I also want to include another list from my Follows model...what is the correct syntax for this? Here's what I have: def profile(request, username): newquery = Follow.objects.filter(username=username) return render(request, "network/profile.html", { "newqueries": newquery }) Here's what I want: def profile(request, username): newquery = NewPost.objects.filter(username=username) query = Follow.objects.filter(username=username) return render(request, "network/profile.html", { "newqueries": newquery }, { "queries": query }) -
How to use django-user-agents with class ListViews
I am building a blog and I have different templates for mobile and desktop versions, I have successfully implemented the user_agent identification for addressing mobile or desktop template for all of my functions as follow: ''' def about(request): user_agent = get_user_agent(request) if user_agent.is_mobile: return render(request, 'about-mobile.html') elif user_agent.is_pc: return render(request, 'about.html') ''' However, once I have to implement it to the ListView classes I really have no idea how to do that! ''' class homepage(ListView): model = DeathAd template_name = 'homepage.html' ordering = ['-id'] paginate_by = 5 ''' -
uwsgi failed to open python file for deploying
I am trying to set up uwsgi on a linux machine. I created a conda environment and isntalled uwsgi and django using conda. To test the installation I created a test: # test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 and run the following command in the same directory where the test.py is : uwsgi --http :8000 --wsgi-file test.py I get the following error: *** Starting uWSGI 2.0.19.1 (64bit) on [Tue Nov 24 14:30:06 2020] *** compiled with version: 7.5.0 on 15 October 2020 10:51:33 os: Linux-4.4.0-18362-Microsoft #1049-Microsoft Thu Aug 14 12:01:00 PST 2020 nodename: DESKTOP-QPDTTFN machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /home/masih/projects/uw detected binary path: /home/masih/.conda/envs/uwsgi/bin/uwsgi *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 7823 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) TCP_DEFER_ACCEPT setsockopt(): Protocol not available [core/socket.c line 744] TCP_DEFER_ACCEPT setsockopt(): Protocol not available [core/socket.c line 744] uWSGI http bound on :8000 fd 4 spawned uWSGI http 1 (pid: … -
Using cmd line under django server
To make it easier to understand, i will use simple command line as 'ls' How can i use a command line like 'pwd' or 'ls' into a django server ? For example, my django server is running 'python manage.py runserver' And into my code i would like to run a cmd command like 'pwd' and get the output of this command : @login_required def history(request): list_file = print('ls') #i would like to do 'ls' command return render(request, 'history.html') Is it possible ? Thank for your help ! -
Form couldn't save in Django
Please help me. I'm trying to make the company users can assign the status of the applicants and give feedback, but it doesn't save the form. Could someone tell me where i did wrong?? I'm a beginner please help.. forms.py` ** class StatusForm(forms.ModelForm): class Meta: model = ApplicantsJobMap fields = ['applicant', 'status', 'feedback'] models.py class Applicants(models.Model): name = models.CharField(max_length=100) age = models.CharField(max_length=10) gender = models.CharField(max_length=20, default=GENDER_MALE, choices=GENDER_CHOICES) mobile_phone = models.CharField(max_length=20) city = models.CharField(max_length=30) expected_salary = models.IntegerField() will_relocate = models.BooleanField(default=False) for_cv = models.FileField(verbose_name='CV') def __str__(self): return "{} - {}".format(self.name, self.mobile_phone) class ApplicantsJobMap(models.Model): applicant = models.ForeignKey(Applicants, on_delete=models.CASCADE) job = models.ForeignKey('jobs.Job', on_delete=models.CASCADE, related_name='applicants', null=True) status = models.CharField( max_length=20, choices=STATUS_CHOICES, default=STATUS_PENDING ) feedback = models.TextField(blank=True, null=True) def __str__(self): return "{} - {}".format(self.applicant.name, self.job.position_name) views.py def update(request, pk): #applicant_form = inlineformset_factory(Applicants, ApplicantsJobMap, fields=('applicant', 'status', 'feedback')) applicants = Applicants.objects.filter(id=pk).first() formset = StatusForm(initial={'applicant': applicants}) #formset = applicant_form(instance=applicants) if request.method == 'POST': formset = StatusForm(request.POST) if formset.is_valid(): formset.applicant = formset.cleaned_data['applicant'] formset.status = formset.cleaned_data['status'] formset.feedback = formset.cleaned_data['feedback'] formset.save() return redirect('home') context = {'formset': formset} return render(request, 'jobs/status.html', context) html <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> {% csrf_token %} {% for field in formset %} {{field}} <hr> {% endfor %} <input type="submit" name="Submit"> </form> </div> </div> -
Django N+1 problem with serpy.MethodField
I use nplusone to detect N+1 queries. I have a serpy serializer that serializes Order instances. An Order has a cart consisting of OrderComponent instances, as shown below. Code simplified: class Order(models.Model): objects = OrderManager() listings = models.ManyToManyField(to=Listing, through="OrderComponent", related_name="orders") class OrderComponent(models.Model): listing = models.ForeignKey(to=Listing, on_delete=models.PROTECT, related_name="order_components") order = models.ForeignKey(to=Order, on_delete=models.PROTECT, related_name="cart") nb_units = models.PositiveIntegerField() A list of serialized Order instances is gotten through OrderListView: class OrderListView(SimplePaginatedListView): # Custom base class model = Order serializer_class = OrderSerializer deserializer_class = OrderDeserializer def get_queryset(self): return super().get_queryset().select_related( "fulfillment", # Used for order.is_fulfilled() "cancellation", # Used for order.is_cancelled() ).prefetch_related( "cart", # I don't believe the first two are necessary, but added for testing purposes "cart__listing", "cart__listing__product", "cart__listing__service", ) @http_get(required_permissions=ShopRolePermission.MANAGE_ORDERS) def get(self, *args, **kwargs): return super().get(*args, **kwargs) @http_post(required_permissions=ShopRolePermission.MANAGE_ORDERS) def post(self, *args, **kwargs): return super().post(*args, **kwargs) OrderSerializer is defined below. nplusone does not say where an N+1 query was detected, so I have commented out every possible culprit and found the true culprits. I have indicated in comments where they are. class OrderSerializer(BaseSerializer): class SimpleOrderComponentSerializer(BaseSerializer): id = serpy.IntField() listing_id = serpy.IntField() product_name = serpy.MethodField(required=False) # No N+1 service_name = serpy.MethodField(required=False) # No N+1 nb_units = serpy.IntField() def __init__(self, instance=None, many=False, data=None, context=None, **kwargs): # Should this … -
Python Django NoReverseMatch Error When I {% url 'crm_client_detail' client.id %}
I know my question seems fimiliar to others but it's not. I'm stuck on in the error in the below when I visit my homepage. The problem is that {% url 'crm_client_detail' client.id %}. I'm pretty sure that I'm doing right but it's not happening. NoReverseMatch at / Reverse for 'client_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['client/(?P[0-9]+)/$'] Any help is so appreciated models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Client(models.Model): client_name= models.CharField(max_length=100) client_sector= models.CharField(max_length=100) client_phone= models.CharField(max_length=100) client_city= models.CharField(max_length=100) client_district= models.CharField(max_length=100) client_adress= models.TextField() client_type= models.CharField(max_length=100) client_priority= models.CharField(max_length=100) client_first_contacted_date=models.DateTimeField(default=timezone.now) # author = models.ForeignKey(User, on_delete=models.CASCADE) views.py from django.shortcuts import render from .models import Client from django.views.generic import ListView, DetailView def ClientView(request): context = {'client_aranacak': Client.objects.all()} return render(request, 'crm/crm_home.html', context) class ClientListView(ListView): model = Client template_name = 'crm/crm_home.html' context_object_name = 'client_aranacak' ordering = ['-client_first_contacted_date'] class ClientDetailView(DetailView): model = Client urls.py from django.urls import path from . import views from .views import ClientListView, ClientDetailView urlpatterns = [ path('', ClientListView.as_view(), name='crm_client'), path('client/<int:pk>/', ClientDetailView.as_view(), name='client_detail'), ] # {% url 'crm_client_detail' client.id %} crm_home.html {%extends "base.html"%} {%block content%} <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table mr-1"></i> Customers </div> <div class="card-body"> <div class="table-responsive"> <table … -
github action for django project
I am trying the github-action-django and the following is the python-app.YAML file for the project name: Python application on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:11 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - 5432/tcp options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.6 uses: actions/setup-python@v2 with: python-version: 3.6 - name: psycopg2 prerequisites run: sudo apt-get install python-dev libpq-dev - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install -r devreq.txt - name: Run migrations run: python manage.py migrate --settings=mysite.dev - name: Test with pytest run: pytest while running the migration job, workflows throws following error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? the database setting also defined in dev.py which is used as django settings while invoking migrations DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mysite', 'USER': 'naveen', 'HOST': '127.0.0.1', 'PORT': 5432, } } if os.environ.get('GITHUB_WORKFLOW'): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'github_actions', 'USER': 'radorado', 'PASSWORD': 'radorado', 'HOST': '127.0.0.1', 'PORT': '5432', … -
Django channels websocket connecting and disconnecting (Nginx + Daphne + Django + Channels)
I'm having problems to deploy this in a production virtual machine, with Nginx + Gunicorn + Daphne + Django. I had been testing it in a local virtual machine, and it works without a problem, but in production, the sockets is connecting and disconnecting. I attached my nginx config, asgi.py and routing.py. I use the command ````$ daphne -p 8010 project.asgi:application``` enter image description here # Nginx config upstream test_project { server localhost:8001; } upstream test_project_websocket { server localhost:8002; } server { listen 1881; location / { proxy_pass http://test_project; } location /ws/ { proxy_pass http://test_project_websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_redirect off; } proxy_set_header Host $host; } #asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebServer.settings') django.setup() from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter import Andon.routing # app.routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.layers import get_channel_layer application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Andon.routing.websocket_urlpatterns, ), ), }) # routing.py from django.urls import path, re_path from . import consumers from channels.layers import get_channel_layer websocket_urlpatterns = [ re_path(r'ws/andon/$', consumers.AndonConsumer.as_asgi()), ] -
'Profile' object is not iterable . Error is raising when i click on template
views.py @login_required def friends_profile(request): f_profiles = Profile.objects.get(user=request.user) return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} ) urls.py path('friends_profile/', views.friends_profile, name='friends_profile'), template = friends_profile.html {% extends "mains/base.html" %} {% block content %} {% for friends in f_profiles %} {{ friends.full_name }} {% empty %} <li>NO DATA</li> {% endfor %} {% endblock content %} models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField(User, related_name='friends',blank=True) email = models.EmailField(max_length=60,default='') date_added = models.DateTimeField(auto_now_add=True) def get_friends(self): return self.friends.all() def get_friends_no(self): return self.friends.all().count() def __str__(self): return f'{self.user.username}' STATUS_CHOICES = ( ('send', 'send'), ('accepted','accepted'), ) class Relationship(models.Model): sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='receiver') status = models.CharField(max_length=8, choices=STATUS_CHOICES) def __str__(self): return f"{self.sender}-{self.receiver}-{self.status}" 'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ? I will really appreciate your HELP. -
Range Filter not working in django rest does not react at all when filtered
Range Filter not working in django rest does not react at all when filtered View class MDShopListView(generics.ListAPIView): queryset = smartphone.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = ShoppFilter def get(self,request): queryset = self.get_queryset() serializer=MDShopListSerializer(queryset,many=True) return Response(serializer.data) -
Use get_queryset method with tables2
Right now, this code works to render my template as an html table, but I would like to render it as tables2. How to do that, while keeping the "get_queryset" bit in the views.py file is giving me trouble. urls.py path('proforma/<int:pk>/', ProformaDetailView.as_view(), name='proforma-detail') views.py class ProformaDetailView(ListView): template_name = "blog/proforma_detail.html" context_object_name = 'proforma' def get_queryset(self): queryset = Proforma.objects.filter(proforma_id=self.kwargs['pk']) return queryset tables.py | Not currently being used class ProformaDetailTable(tables.Table): class Meta: model = Proforma template_name = "django_tables2/bootstrap.html" fields = ('proforma_id','time_stamp','base_price','lot_cost','permit_cost','hard_cost') -
Probmlems with admin pagel in django
I have a problem with the admin panel on a project that I cloned recently in order to perform some tasks on it. I had install all the packages from requirements.txt, make migrations, created a superuser and I logged in in the admin section and I want to add some new objects in order to test some new functionality that I've added and it's not opening anything. When I click on users for example it just selects the user field and that's wall, doesn't redirect me to the users specific page. I can't add nothing. This is how it looks like when I click on a field. -
Where should i put Django Signals?
Hey I apologize in advance for my English. I use Django Signal in my models.py to delete user images from my media directory. Everything works great but in Django documentation I have found something like this: Where should this code live? Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code. In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, import the signals submodule inside ready(). Soo my questions is where and how I should properly use Django signals and what kind of consequences may be if I still used Singals In my models.py I also have found this topic: Where should signal handlers live in a django project? but it was for django 1.7 and may be a little out dated. -
Django Query to get all parents given only the child's id
Given the Table X: id | parentId | name ===================== 1 | null | A 2 | 1 | B 3 | 2 | C 4 | null | D How could I get all the connected parents until the final parent has a parentId of null. So for example, In my query I would do a pass a single id 3. This query would return row 3, row 2(because it is the parent of 3), and row 1 (because it is the parent of 2), then be done because row 1's parentId is null. Is there a way to do this without having to write in loops in the frontend to query for every parent? -
how to if condition on Foreign Key in Django
this is my model class MainCategories(models.Model): name = models.CharField(null=True,blank=True,max_length=150) def __str__(self): return u'{0}'.format(self.name) class SubCategories(models.Model): main_category = models.ForeignKey(MainCategories,null=True,blank=True,related_name = 'MainCategories', on_delete=models.CASCADE) name = models.CharField(null=True,blank=True,max_length=150) def __str__(self): return u'{0}'.format(self.name) this my view.py def home(request): sub_category = SubCategories.objects.all() print('subbbb', sub_category) c = { 'sub_category' : sub_category } return render(request,'core/home.html', c) this is my base.html <li> <a href="javascript:;">Process Equipment & Project Division<i class="fa fa-angle-right"></i></a> <ul class="sub-menu left"> {% if sub_category.Main_category.Name == "Process Equipment & Project Division" %} {% for sub in sub_category%} <li><a href="header-style-1.html">{{sub.name}}</a></li> {%endfor%} {%endif%} </ul> </li> iam created if condition in "li" tag. but its not working. the if condition is not properly.. -
Remove Group of Permissions in Django
I have list of users where the admin can add/remove group of permissions for them. When I want to add everything works fine but when removing it gives me a success method but nothing is removed. def add_remove_role(role_id, user_id, is_checked): ''' add/remove role for a user @param role_id: id of role to be removed or added @param user_id: id of user that should add or remove for him a role @param is_checked: if true then add role else remove role ''' try: user = User.objects.filter(id=user_id).first() role = Group.objects.get(id=role_id) role.user_set.add(user) if is_checked else role.user_set.remove(user) log.debug('successfully added/removed the role "%s" for user "%s" ' %(role_id, user_id)) return True except Exception as e: log.error('an error has occurred while adding/removing role of id "%s" for user "%s" ' %(role_id, user_id)) return False -
Signature differs from overidden 'save' method, pylint(signature-differs)
Could I get some help understanding what the pylint message Signature differs from overidden 'save' method, pylint(signature-differs) is referring to?: def save(self, *args, **kwargs): """ Override the original save method and update the number of seats available """ reservations = ( Booking.objects.aggregate( num_passengers=Count("passengers") ) ["num_passengers"] or 0 ) self.seats_available = self.destination.max_passengers - reservations super().save(*args, **kwargs) The Django docs says "If you use *args, **kwargs in your method definitions, you are guaranteed that your code will automatically support those (updated method) arguments when they are added." I don't fully comprehend how signatures work but my understanding is that it's to do with making sure parameters match. In this case I don't think I have changed anything from the default save method...so what is causing the issue? -
django data migration - class variable unavailable via get_model()
I'm trying to update some database records via a Django data migration, using the following migration file: from django.apps import apps from django.db import IntegrityError, migrations def exclude_pending_drivers(apps, schema_edition): Driver = apps.get_model("team", "Driver") pending_drivers = Driver.objects.filter(type=Driver.PENDING) for driver in pending_drivers: driver.show_in_app = False Driver.objects.bulk_update(pending_drivers, ['show_in_app']) class Migration(migrations.Migration): dependencies = [ ('team', '0002_add_show_in_app_to_driver'), ] operations = [ migrations.RunPython(exclude_pending_drivers), ] I'm getting an error when I run it: AttributeError: type object 'Driver' has no attribute 'PENDING' PENDING is defined as a class variable in the model: class Driver(models.Model): PENDING = 1 CONFIRMED = 2 show_in_app = models.BooleanField(default=True) # etc I can run the exact migration code above in a manage.py shell without errors, and it also runs fine if I use from team.models import Driver instead of apps.get_model("team", "Driver") (although obviously that's not advised). What gives? It looks like the Driver class, when it's included via apps.get_model(), is different to a straight import, but surely that's not the case?? -
loading querysets of the same table name from different databases
I want to combine data from user tables in 3 different databases via django query. They have roughly the same structure, so I chose to make one unmanaged model to represent them. For testing purposes I checked the output by printing it to the console. The output however, only contains data of db1. I cannot union them, because of an indiscinctable textfield. Q: Is there anything i miss or a better method than firing a raw sql via model.objects.raw() ? Here are some files for a better overview: settings.py - same dbms DATABASES = { 'default': {...}, 'db1': { 'ENGINE': 'sql_server.pyodbc', ...}, 'db2': { 'ENGINE': 'sql_server.pyodbc', ...}, 'db3': { 'ENGINE': 'sql_server.pyodbc', ...} } } models.py - same model for 3 databases class UserProfile(models.Model): id = models.IntegerField(db_column="x", primary_key=True) user_name = models.CharField(db_column="y", max_length=255, null=True, blank=True) ... class Meta: managed = False db_table = 'Users' views.py - tested for all outputs and different order def userprofile(request): d = UserProfile.objects.using('db1').all() e = UserProfile.objects.using('db2').all() f = UserProfile.objects.using('db3').all() for row in f: print(row.id, row.user_name) ... context = {...} return render(request, 'userprofile.html', context)