Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sharing an image to LinkedIn using Django 2.2
To share an image on LinkedIn you need to follow the instructions at https://docs.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context What I don't understand is how to make this curl request "curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'". Using Django's requests library. So Basically what I need help with is converting the curl request above into a regular HTTP call such as get, post, put, etc. To Whom it may concern, Jordan -
Django session_key get new value for each request
I create session like this: request.session['user_id'] = 111 if not req.session.session_key: req.session.save() Then in another view, I print: print(request.session.get('user_id')) print(request.session.session_key) session data (user_id) showing correctly, and session_key looks like: eyJ1c2VyX2lkIjoiMTAwIiwidXNlcl9uaWNrIjoibmljazEifT:1khfFA:rwQnzaXk4HQ9XdKPuL1fhRPuLbl8w-TUNR3RMPsNQQr though, for every request, (page refresh) session_key prints different value (BTW part before first ":" stays same). Question: is this behaviour normal? does not session_key must to be same, while session is "alive" ? -
add fields in Django auth Group
I edit the django admin form to show users list with the permission to create group of users to to som actions I want to add a new field without creation a new modal is it possible? forms.py class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['users'].initial = self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): instance = super(GroupAdminForm, self).save() self.save_m2m() return instance admin.py admin.site.unregister(Group) class GroupAdmin(admin.ModelAdmin): form = GroupAdminForm filter_horizontal = ['permissions'] admin.site.register(Group, GroupAdmin) the filed I want to add I have triyed thois but it is not working: models.py class MyGroup(Group): notes = models.TextField(blank=True) def __unicode__(self): return self.name when I add this model I have edit the model in the GroupAdminForm to use this model but no sucess ? -
How to filter foreign key on datatables with server side processing?
How do i filter Foreign keys on a datatable with server side processing? I'm using a datatable to display 3.500 entries from my sql server within Django/Ajax/Rest-Framework. The table is working as intended when searching columns within the given table, but: Foreign key filtering appears not to be working. error i get when searching: raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'bib_tipo_nome' into field. Choices are: autor, cadastro_id, datacriado, emailautor, referencia, tema, tema_id, tipo, tipo_id Is there a solution for this? Do i need client-sided processing? -
Unable to download zip file from server with %20 in it's name but when I copy the link from html it works fine
I am trying to figure out the exact issue but with little success. I have rendered a template containing the link for a file in media directory of my server. The filename has a space in it in the media directory and in the database this space has been replaced with %20 in the filename. I am fetching the filename from the database and passing it to the HTML template with the media url. When I check the rendered html, it has %20 and if I copy the link from the HTML and try to download the file, it is getting downloaded. e.g. The file in the HTML looks like : http://abc.domain.com/media/Demo%20Report.xlsx The file in the media directory is "Demo Report.xlsx" -
DJANGO Static Image deletion
I am experiencing an issue with images saved in the static/images directory in Django. My website was rendering images appropriately, by referencing the name of the image e.g., Image_1. However, once I've tried to delete this image and include a new one in the static/images directory with the same name, Image_1, the website keeps rendering the old image. New images added in the same directory with new names are rendered without issues. Since then I have specified all STATIC_ROOT, MEDIA and MEDIA_ROOT routes in settings.py, I have run manage.py collectstatic and I have checked the images stored in these directories. The "old" version of Image_1 is not there anymore, but the new one is, and the website still renders the "old" version of it. Does anybody have an explanation for this, and how to fix it? Thanks in advance! -
ModuleNotFoundError: No module named 'django_countries'
I have a docker django project and I want to use django-countries. This is my requirements.txt .... django-countries django-cities This is the INSTALLED_APPS in settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_countries', ... (others) ] When I run docker-up, I receive the below error: docker_name | Traceback (most recent call last): docker_name | File "/app/manage.py", line 22, in <module> docker_name | main() docker_name | File "/app/manage.py", line 18, in main docker_name | execute_from_command_line(sys.argv) docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line docker_name | utility.execute() docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute docker_name | django.setup() docker_name | File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup docker_name | apps.populate(settings.INSTALLED_APPS) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate docker_name | app_config = AppConfig.create(entry) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 90, in create docker_name | module = import_module(entry) docker_name | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module docker_name | return _bootstrap._gcd_import(name[level:], package, level) docker_name | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import docker_name | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load docker_name | File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked docker_name | ModuleNotFoundError: No module named 'django_countries' Any ideas? -
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.