Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Delete attachment in django
I have some points with unique identifiers. Each point has a file attached to it. How do I delete files at a specific point? https://github.com/testdrivenio/django-ajax-xhr/blob/jquery/static/main.js#L19-L41 -
Redis django connects to localhost redis, even when I change URL and PORT
return { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': f'redis://{self.REDIS_URL}:{self.REDIS_PORT}', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } this is my redis code to put in CACHES, still even after specifying different redis_url and port, connects to localhost 127.0.0.1:6379 I want to connect to a different IP url and PORT. I tried different 'BACKENDS' and CLIENT_CLASS and pools, playing around with different CACHES types. I can connect to my url-port redis using this: return redis.StrictRedis(host=self.REDIS_URL, port=self.REDIS_PORT, db=0, decode_responses=True, encoding="utf-8") but not when I want to setup CACHES. -
Are Django models "db_tablespace" equivalent to Postgres Schemas?
I just stumbled with the Django docs reference to db_tablespace option in Meta(), and I'm unsure: Are "tablespaces" (as defined in Django) somewhat equivalent to "schemas" (as defined and used in Postgres)? For example: Would the following models: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Meta(): db_table = 'person' db_tablespace = 'people' class Book(models.Model): author = models.ForeignKey(Person) title = models.CharField(max_length=100) class Meta(): db_table = 'book' db_tablespace = 'books' ... be mapped to Postgres schemas / tables people.person and books.book? -
How to print leaflet map in pdf using django-wkhtmltopdf?
I have a django app I am trying to print a leaflet map in pdf using django-wkhtmltopdf, but the map is not rendering correctly. I even try to give more time to the 'javascript-delay' parameter but is giving me the same result. Here is the image of the map: from wkhtmltopdf.views import PDFTemplateResponse class MyPDFView(View): template='agrimensuras/project_pdf.html' # the template def get(self, request, pk): project = get_object_or_404(Project, id = int(pk)) data = {"project": project} response = PDFTemplateResponse(request=request, template=self.template, filename="hello.pdf", context= data, show_content_in_browser=False, cmd_options={'margin-top': 10, "zoom":1, "viewport-size" :"1366 x 513", 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True}, ) return response In the template (I am just showing the relevant pieces of code): <!--Importing leaflet--> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script> <!--Defining the div--> <div id="map" ></div> <!--Defining the map--> <script type="text/javascript"> var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { minZoom: 5, maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); var marker = L.marker([51.5, -0.09]).addTo(map); var circle = L.circle([51.508, -0.11], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: 500 }).addTo(map); var polygon = L.polygon([ [51.509, -0.08], [51.503, -0.06], [51.51, -0.047] ]).addTo(map); </script> -
Django, Celery, and Celery beat via Copilot. Use Sidecars or multiple services?
I am able to easily deploy a Django application via Copilot. But now I need a Celery worker and beat. Sidecars sounds like what I want. Basically, define two new sidecars: one for a Celery worker and another for a Celery beat. But then I came across Developing an application based on multiple microservices using AWS Copilot and AWS Fargate. This takes the approach of deploying the other docker containers as their own services. It's not exactly clear to me which approach is best for my needs. Sidecars seems simpler and more straight forward. The only thing unclear to me on how to establish with it is the image (required) parameter. Why a URL? Why not a reference to the Dockerfile to build the worker and another one for the beat? -
Can't upgrade Jawsdb plan
I have an app hosted on heroku with a shared database tenant and now i want to upgrade to a single tenent. I love jawsdb but it just wouldn't let me upgrade it saying that it is limited to customers with an established payment history. I have already paid a month for their services but still get this error when upgrading from Leopard Shared to Whitetip plan. Pls help -
django main.app_table__old Error deleting item
I am facing this problem and I tried many solutions but no one works for me or it is not convinient of my case. First I use Django==2.0 (can't change to version due to problems). I have I model table named table and my app is appwhen developing it happend that I can't delete any element in that table (the other works fine). and I get this problem. OperationalError at /fieldsdetails/25/delete/ no such table: main.app_table__old I tried to delete all migrations history so the db.sqlite3 and run: python manage.py makemigrations python manage.py migrate Then I tried to delete the table as python manage.py dbshell SELECT * FROM sqlite_master WHERE type='table'; then I found a table named app_table__old and deleting it using this: DROP TABLE app_table__old .exit but nothing works? is there any solution I don't want to upgrade Django version or lose data. -
What is the second argument to ForeignKey in the django stubs typehints?
order = models.ForeignKey["ExtensionOrder", **WhatGoesHere**]( "subscriptions.ExtensionOrder", null=False, on_delete=models.PROTECT ) The stub is here: class ForeignKey(ForeignObject[_ST, _GT]): _pyi_private_set_type: Union[Any, Combinable] _pyi_private_get_type: Any ... # class access @overload # type: ignore def __get__(self, instance: None, owner) -> ForwardManyToOneDescriptor: ... # Model instance access @overload def __get__(self, instance: Model, owner) -> **_GT**: ... # non-Model instances @overload def __get__(self: _F, instance, owner) -> _F: ... Pylance is griping about it, but I'm not sure what _GT should be -
Serving react build folder in django, page not found on reload
I'm writing a chat application in Django and using React as the front end, I'm serving the react at root path 'localhost:8000/' and there are some path in the react app too such as 'chat/:user', I can access this as long as I go from the root path, if I enter the path manually or try reloading the page it gives the error 'Page not found'. This is my urls.py file from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('', TemplateView.as_view(template_name='index.html'), name='chat'), path('api-auth/', include('rest_framework.urls'), name='api-auth'), path('api/', include('api.urls')), ] and this is my App.js function App(props) { const [user, setUser] = useState('none'); useEffect(() => { fetch('http://localhost:8000/api/user-data') .then((response) => response.json()) .then((data) => { setUser(data.username); }); }, []) //console.log(window.location.href); return ( <BrowserRouter> <Routes> <Route path='/' element={<Layout user={user} socket={props.socket} />}> <Route index element={<Home user={user} socket={props.socket} />} /> <Route path='chat/:chattingUser' element={<ChatPage user={user} socket={props.socket} />} /> <Route path='search/:queryText' element={<SearchPage user={user} socket={props.socket} />} /> </Route> </Routes> </BrowserRouter> ); } I was at the route /chat/ and I changed some things in the code so had to reload the page, then this error came, why is it looking at django urls when i reload and how … -
Why is django-autocomplete-light single-select badly styled and broken when multi-select is working?
I have a screen in Django with a single-select autocomplete and multi-select autocomplete to the same model object (but different model fields). The multi-select is working perfectly, the single-select is functional, but poorly styled and also slightly broken (takes an extra click to get into the box to type). Help? EDIT: If I remove the multi-select box from the form, the single-select is still poorly styled and broken. So, while the multi-select shows something can work, it is likely otherwise unrelated. More detail: Django 4.1.5 django-autocomplete-light 3.9.4 django-bootstrap5 22.2 generated HTML multi-select (working): <span class="select2-selection select2-selection--multiple form-select" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1" aria-disabled="false"><ul class="select2-selection__rendered"><li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" placeholder="Type here" style="width: 288px;"></li></ul></span> .select2-container .select2-selection--multiple: min-height: 32px single-select (broken): <span class="select2-selection select2-selection--single form-select" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-id_primary_diagnosis-container"><span class="select2-selection__rendered" id="select2-id_primary_diagnosis-container" role="textbox" aria-readonly="true"><span class="select2-selection__placeholder">Type here</span></span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span> "display:inline prevents height:28px from having an effect" In forms.py: class MyobjForm(forms.Form): # NOTE: can't use ModelForm for various reasons not shown single_select = forms.ModelChoiceField( label='single select', queryset=Myobj.objects.all(), widget=autocomplete.ModelSelect2( url="myobj-autocomplete", attrs={ "data-placeholder": "Type here", # Only autocomplete after 1 character has been typed "data-minimum-input-length": 1, }, ), ) multi_select = forms.ModelMultipleChoiceField( label='multi select', queryset=Myobj.objects.all(), required=False, widget=autocomplete.ModelSelect2Multiple( url="myobj-autocomplete", attrs={ … -
cannot import name 'Categories' from partially inisialized module 'categories.models' (most likly due to a circular import)
I try to create 2 database categories and sous_categories in Django. in these 2 database a categories can have many sous_categories and sous_categories has only one categories. When i test my code i got the 'cannot import name 'Categories' from partially initialized module 'categories.models' (most likely due to a circular import)'. I think the error occurs to a circular dependency and the most solution i see int the web is: it can be resolved by moving the imported classes to a third file and importing them from this file. But i don't know how to do it with my code. here part of my categories model: class Categories(models.Model): nom_categorie = models.CharField(max_length=200) marchand = models.ManyToManyField(Marchands) sous_categorie = models.ManyToManyField(Sous_Categories) slug = models.SlugField(default='') images = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(null=True)``` ` and my sous_categories model: ``from django.db import models from django.template.defaultfilters import slugify from categories.models import Categories class Sous_Categories(models.Model): nom_souscategorie = models.CharField(max_length=200) categorie = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, blank=True) slug = models.SlugField(default='') images = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(null=True)`` -
Django localhost default port already in use with postgres
I am receiving a error when running postgres, pgadmin and django. Port is already in use. I know how to use the sudo command to kill the server, however I am not being shown my databases in postgres. It just shows running when I start the server. When I create a new port database shows but doesn't migration the data. Also when I run migrations to django I get error, table already exist and or table doesn't exist. This happens everytime as if there is a duplicate database and it's not connected to the one showing in pgadmin. I tried dropping and deleting tables in pgadmin, and still get table exist. How do i fix this? How do I show all databases connected and delete the one that overrides my default port and have postgres show database servers in the app. Thank you in advance. Long post but I'm stressing and cant find a solution. Deleting tables in pgadmin, change port number, open postgres first than start pgadmin. -
Django save_m2m() in a separate, delayed transaction
I'm facing a vexing issue in which two adjacent lines of code seem to be committed separately to the database- with one of them hanging out for a full day or more before getting committed. if form.is_valid(): instance = form.save(commit=False) if form.cleaned_data['assigned_to_mtm'].count() <= 0: instance.status = "Unassigned" elif instance.status == 'Unassigned': instance.status = "Assigned" instance.save() form.save_m2m() With the above, I am finding the assigned_to_mtm reflected right away in the database. The status, however, isn't. Instead, when a separate save (even happening the next day) updates the status to something else, then this saved status comes in right afterward with the same timestamp, reverting its value to what it should have been at the time the mtm was saved. I'm astonished that I can't get these two to just happen in a single transaction (I tried the @transaction.non_atomic_requests decorator and doing it myself- that didn't help), let alone that the instance.save() hangs out uncommitted for so long, then gets committed only when the status is updated again separately. I might not even care, if the order of saves was at least preserved, but confoundingly, my earlier save is always committed after the next save. What am I doing wrong here? Can … -
how can show profile User in html django
i create user auth and make model profile user with signals to create profile like User but i want show user profile in template ---- model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) music = models.CharField(max_length=50) skils = models.CharField(max_length=50) search = models.CharField(max_length=50) posts = models.CharField(max_length=50) boi = models.TextField() img = models.ImageField(upload_to="profile-img") def __str__(self): #return self.user or 'User' return str(self.id) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) ---- path path('profile/<int:id>', views.profile, name="profile") ----- views def profile(request, id): ff = profile.objects.get(id=id) context = {'ff' : ff} return render(request, 'profile.html', context) views not work i dont know the problem in html... {% url 'profile' profile.id %} how can show profile User in html django -
djangochannelsrestframework problem with elastickbeanstalk and @model_observer
I have a consumers in which there is tracking of model changes using @model_observer. I subscribe to the event via @action and track its changes, everything works perfectly locally, the model has changed, I immediately received a change. But as soon as I try to put it on aws elastic beanstalk, I can subscribe/unsubscribe, but I don't get changes about events, although I see that the session is not broken. I thought that the problem was in queues or sessions, but I checked this together with technical support, they told me that everything was working correctly and the connection was made correctly. Maybe you know at least in which direction I should look and dig? Just in case, I summarize: everything works correctly locally, when uploading to the server, only subscribe to the event / unsubscribe from the event works, but for some reason the changes do not work my consumer.py with @model_observer my django.conf my Procfile: web: gunicorn --bind :8000 --workers 3 --threads 2 settings.wsgi:application websocket: daphne -b 0.0.0.0 -p 5000 settings.asgi:application I watched redis, I watched DB, cleaned up sessions -
client.post is not passing the FK
Hope someone can help me out here, I am trying to test a post method on an API, but the post method is not working as expected. When I pass the payload to the post method, the points and de code fields are loaded but the shopper and card fields, which are both Foreing Keys, are not loaded and a null value is passed, as they are required fields I ended up getting an error. I did check, and the values for self.shopper.pk and self.card.pk are correct. MYCARDS_URL = reverse('mycards:mycards-list') def test_create_mycards(self): """Test creating a mycards""" payload = { 'shopper': self.shopper.pk, 'card': self.card.pk, 'points': 0, 'code': "code", } res = APIClient().post(MYCARDS_URL, payload) I did check to see if was something related to my serializer, but it is all good as you can see: class MycardsSerializer(serializers.ModelSerializer): """Serializer for cards.""" class Meta: model = MyCards fields = ['id', 'shopper', 'card', 'updated', 'created'] read_only_fields = ['id', 'created'] class MycardsDetailSerializer(MycardsSerializer): """Serializer for card detail view.""" class Meta(MycardsSerializer.Meta): fields = MycardsSerializer.Meta.fields + [ 'points', 'code'] Here is also my viewset which seems to be ok: class MycardsViewSet(viewsets.ModelViewSet): """View for manage card APIs.""" serializer_class = serializers.MycardsDetailSerializer queryset = MyCards.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Django - can't delete rows when migrating backwards
I have a problem. I implemented a migration to create another option on my model (add the preview textchoice) and implemented a RunPython method to create rows on a table that matches my requirements. This works. The part that doesn't work is the reverse code. I simply query and filter the instances that I want to delete and try to delete them. In doing so, I get this weird error: Unapplying applications.0012_alter_mediatype_name...Traceback (most recent call last): File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 39, in <module> cli.main() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 430, in main run() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 284, in run_file runpy.run_path(target, run_name="__main__") File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 321, in run_path return _run_module_code(code, init_globals, run_name, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 135, in _run_module_code _run_code(code, mod_globals, init_globals, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 124, in _run_code exec(code, run_globals) File "/code/ews/manage.py", line 22, in <module> main() File "/code/ews/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File … -
Django media files 404 not found
I am creating my application where I need to upload an image, I created an input tag in html, but through this tag the files are not transmitted in the right way, but through the admin panel the images are loaded as neededenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description here I tried almost all the options that I found -
Error 403 when I try to access an uploaded image in Django with Nginx
When I upload some images together with a total size of about 10MB, I get a 'PermissionError: [Errno 1] Operation not permitted' error when I try to see them. How can I set my media folder to securely accept uploads and downloads from my users? I have a server configured with Django, Nginx and Gunicorn, so I tried to increase the client_max_body_size value in Nginx configuration file but no results. -
Django: Reverse for 'thread' with arguments '(1,)' not found. 1 pattern(s) tried: ['(?P<forum_id>[0-9]+)/(?P<thread_id>[0-9]+)/\\Z']
`I have tried to use two primary key at urls.py path but when I am using that and in template I cannot access that second primary key. Like: forum/1/2 2 cannot be accessed. it show error.` **urls.py **path('<int:forum_id>/<int:thread_id>/', views.thread, name='thread'), views.py `def forum(request,forum_id): forums = get_object_or_404(ForumModel, id=forum_id) threads = ThreadModel.objects.filter(forum=forums) context={'forums':forums,'threads':threads} return render(request,'forumdetail.html',context) def thread(request, thread_id): thread = get_object_or_404(ThreadModel, id=thread_id) posts = PostModel.objects.filter(thread=thread) context={'thread':thread,'posts':posts} return render(request,'threaddetail.html',context) ` template \ {% for thready in threads %} {{ thready.title }} {% endfor %} `` -
How to pass context object from a template to a view in django?
In search results page,a list of experts with their name and some other details are displayed.The name and the details are accessed from a context object "expert" that has been passed to search results page.Beside each search result I also generated a "save" button .When the user clicks on the save button,I need to save the individual expert data to a database.How do I send this "expert" context object from the search results page to a view so that I can then save it to the database? Here is the search result page: Here is part of the code of the for the search results: You can see I tried to create a hidden form with a button to send the context object to a view but it's not working.How do I create the button so that when the user clicks "save" button the url sends the context "expert" to a view? I tried to create a hidden form with a button to send the context object to a view but it's not working -
How can i pass a json param in get method (drf)?
class getAlarmlogsFilterByDistincts(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): column_name = request.data['column_name'] #just an idea, dont works distincts_list = request.data['distincts_list'] #just an idea, dont works column_values = [Alarmlog.objects.filter(**{column_name: x}) for x in distincts_list ] serialized_response = AlarmlogSerializer(column_values) return Response(serialized_response.data, status=status.HTTP_200_OK) My view is more or less like this. I need to receive a string in column_name and a list in distincts_list (maybe in json format). What i tried: class AlarmlogsFilterByDistinctsSerializer(serializers.Serializer): distincts_list = serializers.ListField() column_name = serializers.CharField() class getAlarmlogsFilterByDistincts(CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = AlarmlogsFilterByDistinctsSerializer def post(self, request, *args, **kwargs): column_values = columnFilter(request.data['column_name'], request.data['distincts_list']) response_serialized = serializers.serialize('json', column_values) print(response_serialized) return Response(response_serialized, status=status.HTTP_200_OK) i've tried to use post method, but my response come out as a string: "[{\"model\": \"alarms.alarmlog\", \"pk\": 26, \"fields\": {\"created_at\": \"2023-01-12T17:06:19.016Z\", \"updated_at\": \"2023-01-12T17:06:19.016Z\", \"name\": \"string43\", \"description\": \"string\", \"severity\": \"low\", \"type\": \"string\", \"period\": \"string\", \"value\": \"string\", \"reference\": \"string\", \"source\": 2147483647, \"third_party_id\": \"string\", \"device\": \"string\", \"extra_content\": {}, \"occurred_at\": \"2023-01-12T16:29:39.055Z\", \"equipment\": 7}}, {\"model\": \"alarms.alarmlog\", \"pk\": 27,... ps. sorry my english -
Celery, RabbitMQ removes worker from consumers list while it is performing tasks
I have started my celery worker, which uses RabbitMQ as broker, like this: celery -A my_app worker -l info -P gevent -c 100 --prefetch-multiplier=1 -Q my_app Then I have task which looks quite like this: @shared_task(queue='my_app', default_retry_delay=10, max_retries=1, time_limit=8 * 60) def example_task(): # getting queryset with some filtering my_models = MyModel.objects.filter(...) for my_model in my_models.iterator(): my_model.execute_something() Sometimes this task can be fininshed less than a minute and sometimes, during highload, it requires more than 5 minutes to finish. The main problem is that RabbitMQ constantly removes my worker from consumers list. It looks really random. Because of that I need to restart worker again. Workers also starts throwing these errors: SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2396) Sometimes these errors: consumer: Cannot connect to amqps://my_app:**@example.com:5671/prod: SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'). Couldn't ack 2057, reason:"RecoverableConnectionError(None, 'connection already closed', None, '')" I have tried to add --without-heartbeat but it does nothing. How to solve this problems? Sometimes my tasks takes more than 30 minutes to finish, and I can't constantly monitor if workers were kicked out from rabbitmq. -
How to redirect to another view with arguments and 'cannot unpack non-iterable Listing object' django
Essentially what I am trying to do is allow a user to delete their own comments and simply refresh the page with all the data with that page loaded in from my 'view' view. However, I'm not sure about the best way to go about this as my view function has multiple variables in its context that I cannot access from my 'delete_comment' view. Also I keep running into an error when I try to access a given listing through a foreign key relationship and I get the error 'cannot unpack non-iterable Listing object' even though there is a listing associated with each comment. Here is everything associated with what I am trying to accomplish. views.py def view(request, listing_title): listing = Listing.objects.get(title=listing_title) # If someone is logged in user = request.user if user.id != None: try: watchlist = PersonalWatchList.objects.get(user=request.user) watchlist_listings = watchlist.listings.all() except: watchlist = None watchlist_listings = None return render(request, "auctions/listing.html", { "listing": listing, "watchlist": watchlist, "watchlist_listings": watchlist_listings, "comments": Comment.objects.filter(item=listing).order_by('-date_created') }) else: return render(request, "auctions/listing.html", { "listing": listing, "comments": Comment.objects.filter(item=listing).order_by('-date_created') }) def delete_comment(request, comment_id): comment_details = Comment.objects.get(id=comment_id) # item is None? Supposed to be of type 'Listing' auction = comment_details.item listing = Listing.objects.get(auction) listing_title = listing.title Comment.objects.get(id=comment_id).delete() # Need … -
Django DB delete filtered Objects
I'm trying to delete a user's all related messages. All messages sent by all users are located in a Message Model. So, to delete a specific user's messages only, I have to filter this Message.Model and sort it by user. def clear(request): user_msg = request.user relative_message = Message.objects.filter(user=user_msg) Message.objects.filter(id=relative_message).delete() My code is not working and gives me a Value Error: The QuerySet value for an exact lookup must be limited to one result using slicing.