Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django date picker for filters
I have date range filter that allows me to filter objects. I want to add a date picker for start and end date, I have done that in my forms.py but that widget doesn't work for filters. How can I add a date picker for filters? filters.py import django_filters from django_filters import DateFilter class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name="date_created", lookup_expr='gte') end_date = DateFilter(field_name="date_created", lookup_expr='lte') class Meta: model = Order fields = ['status'] ``` ``` HTML <form class="form-inline" method="get" action=""> {{myFilter.form}} </form> -
Django - complex Query, matching 2+ alike fields in a model instance?
I was recently assigned a task for this week that has been giving me a tough time. given the Database model here... class Company(models.Model): employee = models.ManyToManyField(Account, blank=True) name = models.CharField(max_length=256, null=True, blank=True) street = models.CharField(max_length=256, null=True, blank=True) city = models.CharField(max_length=256, null=True, blank=True) state = models.CharField(max_length=256, null=True, blank=True) country = models.CharField(max_length=256, null=True, blank=True) primary_email = models.EmailField(max_length=200, null=True, blank=True) website = models.URLField(max_length=256, null=True, blank=True) and the view here... def check_company(request): if request.method == 'GET': company = request.GET.get('company') check_comp = Company.objects.filter(name=company.title()).count() if check_comp > 1: res = 'false' else: res = 'true' return HttpResponse(res) right now, the check_company function checks whether the companies name is already in the database, and if it is, it alerts the user that the company is already in the database. Now, I am trying to change this in a way that checks whether the company name, AND any OTHER field (website, primary_email, street, city) are already in the Company database together. So, (name + wesbsite) or (name + primary_email), or (name + street) or (name + city) Any help is greatly appreciated! -
How can I pass an iterable queryset to a form field?
I'm having trouble understanding why my QuerySet is non-iterable I'm attempting to use the users data when formatting a form. I'm returning a QuerySet with courses the user has not yet taken and then passing it as the choices for the multiplechoicefield method. When I attempt this I receive a error saying: "TypeError: cannot unpack non-iterable Courses object" Here is my code: forms.py from django import forms from .models import UserProfile, Courses class CourseForm(forms.Form): def __init__(self, *args, **kwargs): self.user=kwargs.pop('user', None) super(CourseForm, self).__init__(*args, **kwargs) student_profile = UserProfile.objects.filter(user_id=self.user) crs_taken = Courses.objects.filter(userprofiles=student_profile[0]) crs_not_taken = Courses.objects.exclude(title=crs_taken[0]) self.fields['crs_not_taken'] = forms.MultipleChoiceField(choices=crs_not_taken) models.py from django.db import models from django.contrib.auth import get_user_model # Create your models here. class Courses(models.Model): subject = models.CharField(max_length=50) title = models.CharField(max_length=50) professor = models.CharField(max_length=50) section = models.PositiveSmallIntegerField() crn = models.PositiveSmallIntegerField() userprofiles = models.ManyToManyField('UserProfile', through='Attends') def __str__(self): return self.title class UserProfile(models.Model): usermodel = get_user_model() user = models.OneToOneField(usermodel, on_delete=models.CASCADE) course = models.ManyToManyField('Courses', through='Attends') def __str__(self): return "%s's profile" % self.user #Juction table class Attends(models.Model): userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) courses = models.ForeignKey(Courses, on_delete=models.CASCADE) views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from .models import UserProfile, Courses from django.http import HttpResponseRedirect from .forms import CourseForm from django import forms # Create your … -
Django custom validation leads to view returning None
I am making an auctions app, and need to check that the bid amount entered on the form is equal to or greater than the starting bid (if there has been 0 bids), or that it's greater than the current bid. I used custom validation using clean(): class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=11, decimal_places=2) def clean(self): # if there has been one or more bids if self.listing.current_bid and self.listing.current_bid.amount >= self.amount: raise ValidationError({'amount': _('Amount must be greater than current bid')}) # else if there has been 0 bids elif self.listing.starting_bid > self.amount: raise ValidationError({'amount': _('Amount must be great than or equal to starting bid')}) In views.py: def listing_page(request, listing_id): listing_selected = Listing.objects.get(pk=listing_id) if request.method == "POST": # Since I don't want the user to have to fill out a field specifying what listing page # they're on, and since I don't have access to that information in the model class # definition, I did that here: request.POST._mutable = True form = BidForm(request.POST) form.data['listing'] = listing_selected if form.is_valid(): # ...process clean data... return HttpResponseRedirect(reverse('auctions:listing_page', args=(listing_id,))) Now when I submit the form with a value that is being checked by this custom validation, I get "ValueError: The view auctions.views.listing_page … -
How to connect django to elasticsearch with logsatsh?
I'm trying to send django data to elasticsearch by using logstash. I use tcp for logstash input type and here is my django settings.py file. INSTALLED_APPS = [ 'django_elasticsearch_dsl', ... ] ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' } } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': 'velname)s %(message)s' }, }, 'handlers': { 'logstash': { 'level': 'INFO', 'class': 'logstash.TCPLogstashHandler', 'host': 'localhost', 'port': 5959, # Default value: 5959 'version': 1, 'message_type': 'django', 'fqdn': False, 'tags': ['django.request'], }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['console'], 'propogate': True, }, } } And this is my simple logstash conf file. input { tcp { port => 5959 codec => json } } output { elasticsearch { hosts => ["localhost:9200"] user => "****" password => "****" } } I already checked there is index in elasticsearch like this. But I couldn't find any matching index pattern in kibana. I'm trying like logstash-*, but there is no index which matches it. Although I know that there is no docs in the index right now, but I think it should match pattern anyway. Another … -
Swagger Django [No operations defined in spec]
I have been trying to integrate Swagger with Django Application and encounter this error: No operations defined in spec! My project structure is App views.py urls.py .. App2 settings.py urls.py .. I am using drf_yasg for my purpose. I have included all details in settings.py and in App2 I have this in urls.py: from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Testing", default_version='v1', description="Doc Integration", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="abc@abc.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatters=[path("admin/", admin.site.urls), path("", include("app.urls")), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),] My class views such as (class Att(generic.TemplateView) and methods are declared in views.py under App. I tried methods such as @swagger_auto_schema, @api_view, to display app class and functions in the documentation. But it just returns No operations defined in spec!. I tried using routers to register the view as well but did not work, even django-rest-swagger fails. Any help is appreciated. Thanks! -
uploading arabic files in django not working returning codes
i have a view in my django project that should be able to read the content of an uploaded .txt file from the input type="file", but the thing is that with arabic content it doesn't print the actual text, but a series of codes "\xd9\x88\xd9\x82\xd8\xa7\xd9\x84" and i couldn't find any solution for this since the file is perfectly viewable on my pc and my website it the one exporting that file in "utf-8". any help here ? Uploaded_File = request.FILES["Doc"] for chunk in Uploaded_File.chunks(chunk_size=None): print(chunk) -
EmailMessage issues timeout on ubuntu development server
i have just uploaded my django project to a ubuntu server at Linode.com. I wanted to test out my site by running a development server via the ubuntu server at linode. I can access the website just fine from the development server. My problem is that i have a contact form at the bottom of my website. The contact form is made within HTML, and then i am accessing the different inputs from my views.py file. It all worked just as fine when i started a development server on my localmachine (My PC). Now that i have uploaded the django-project i can no longer use the contact form, and it gives me a timeout error, when i am submitting the message. I have tried to search on the internet on how i can possibly fix the problem but i cant seem to find the solution so i am hoping that i can get some help from here. My mail server is at PrivateEmail.com, which i bought through NameCheap. Here is how i am sending the email message def index(request): if request.method == 'POST': contacters_name = request.POST['contacters_name'] contacters_subject = request.POST['contacters_subject'] contacters_message = request.POST['contacters_message'] contacters_email = request.POST['contacters_email'] email = EmailMessage( contacters_subject + … -
Django channels background worker not picking up messages
I'm trying to implement a background worker that will eventually read a log file and sent it back over websocket to client. Currently the message isn't delivered to the worker. #consumer channel_layer = get_channel_layer() class LogFileConsumer(AsyncConsumer): async def read_file(self, message): print(message) await asyncio.sleep(2) class LogConsumer(AsyncWebsocketConsumer): # group_send code, not shown, is routed back fine to the client browser async def connect(self): await self.accept() await channel_layer.send('read-file',{ 'type': 'read.file', 'id':'start', }) #routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( log_reader.routing.websocket_urlpatterns ) ), 'channel': ChannelNameRouter({ 'read-file': LogFileConsumer, }), }) I then run the worker like so: $ python manage.py runworker read-file Running worker for channels ['read-file'] I'd expect to see a message printed back on the console, but nothing is returned. The rest of the code, receiving message from browser over websocket, and sending back to client using group_send works fine. I'm sure there is a silly mistake somewhere, just can't spot it. Thanks -
Django: django.db.utils.IntegrityError: UNIQUE constraint failed:
I am creating a blog post using django! However, for some weird reason, I'm keep getting this error... File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site- packages\django\core\management\commands\migrate.py", line 233, in handle fake_initial=fake_initial, File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site- packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site- packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\backends\base\schema.py", line 567, in alter_field old_db_params, new_db_params, strict) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site- packages\django\db\backends\sqlite3\schema.py", line 360, in _alter_field self._remake_table(model, alter_field=(old_field, new_field)) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site- packages\django\db\backends\sqlite3\schema.py", line 287, in _remake_table self.quote_name(model._meta.db_table), File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute cursor.execute(sql, params) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\kimmc\anaconda3\envs\SearchWeb\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, … -
django-filter filter and count objects
I am using django-filter to filter down a queryset based on a foreignkey model’s fields, and i want to count the number of objects for each field in the filtered queryset... models.py class MyModel(models.Model): . . field1 = models.ForeignKey(Model1) field2 = models.ForeignKey(Model2) field3 = models.ForeignKey(Model3) field4 = models.ManyToManyField(Model4) . . filters.py class MyFilter(django_filters.FilterSet): field1 = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset = Model1.objects.all()) field2 = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset = Model2.objects.all()) field3 = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Model3.objects.all()) field4 = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset= Model4.objects.all()) class Meta: model = MyModel fields = ['field1','field2','field3','field4'] views.py def MyView(request): filtered_data = MyFilter(request.Get, queryset = MyModel.objects.all()) filtered_queryset_data = filtered_data.qs . . want to make a count based on the filered data queryset. Field1 ✓ checkbox1 (count) ✓ checkbox2 (count) ✓ checkbox3 (count) ✓ checkbox4 (count) Field2 ✓ checkbox1 (count) ✓ checkbox2 (count) ✓ checkbox3 (count) ✓ checkbox4 (count) What is the best way to make it? Any help would be greatly appreciated. Thank you -
deploying django to google cloud engine Server Error (500)
I've been trying to deploy my django project with gcp, but I keep getting series of errors. the project runs locally but doesn't run even after gcloud app deploy ran successfully. if i try visiting the site i get server error (500) settings.py if os.getenv('GAE_APPLICATION', None): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '/cloudsql/connection name', 'USER': ' user', 'PASSWORD': 'project_password', 'NAME': 'instance name', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfolio', 'USER': 'postgres', 'PASSWORD': 'local db password', 'HOST': 'localhost', 'PORT': 5432, } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] STATIC_URL = 'https://storage.googleapis.com/newinstance_buc/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/') PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') # STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' app.yaml env: flex entrypoint: gunicorn -b :$PORT mysite.wsgi env_variables: SECRET_KEY: secret_key beta_settings: cloud_sql_instances: connection_name=tcp:5432 runtime_config: python_version: 3 automatic_scaling: min_num_instances: 1 max_num_instances: 2 the following are the error reports in error log error reporting File "/layers/google.python.pip/pip/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/gunicorn/app/wsgiapp.py", … -
AbstractUser model with custom field shows myapp.class.None
I have the following model: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): follows = models.ManyToManyField("self", symmetrical=False, blank=True, null=True) pass class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() likes = models.PositiveIntegerField() dislikes = models.PositiveIntegerField() user = models.ForeignKey(User , on_delete=models.CASCADE) and the following views.py file: from django.shortcuts import render from .models import * def index(request): actualUser = User.objects.all() for i in actualUser: print(i.id) print(i.follows) return render(request, "network/index.html") but it prints this: 1 network.User.None 2 network.User.None Need help cant reach the custom field follows -
Python class variables not behaving as expected in Django app
I've created a REST API view in Django to keep track of who is currently typing in a client chat program, so I can notify the other user in the chat channel by means of an animated icon. On the client side, every 2 seconds this view will receive a POST call -- a sort of "ping" -- for as long as the user is typing. If the user stops typing for longer than 2 seconds, those pings stop coming in. On the server side, as you can see in this view, I keep a list of current_typists, indexed by the chat's channel_id and the typist_id. This list holds 5-second timers, one per typist. Anytime a ping comes in, the timer is extended. If there hasn't been a ping in 5-seconds, the timer will run out and the other typist can be notified that typing has stopped. I store current_typists as a class variable, as well as typing_lock, which ensures that asynchronous accesses to those timers won't collide. @authentication_classes((TokenAuthentication,)) class ChatUserIsTypingView(APIView): current_typists = {} typing_lock = Lock() # Notify the other user silently whether typist_id is typing or not def notify_typing_status(self, typist_id, other_id, typing): do_the_notification_here() # When a timer has … -
How do you get Django to redirect to another page instead of the login when implementing a permission?
I have a permission that works on a view: @permission_required('app.admin_foo') def fooView(request, id=None): ... But the default behaviour is to redirect to a login. How can I get Django to redirect to another view when the permission is denied? E.g. return redirect(reverse('bar')) -
Trying to direct a user to the next page when clicking the next button
I have a app which is letting users fill in a few question, click a button to fill in a form with their contactinfo and redirecting them to a thank you page after submitting the form. At first I had the error: Reverse for 'contact' with arguments '('',)' not found. * So I set a get method with reverse_lazy. Now the error is gone but when I click the buttons it directs me back to the same page. Read the docs but cannot find out what is going wrong. urls.py urlpatterns = [ path('<slug:bedrijfslug>/check', CheckView.as_view(), name='check'), path('<slug:bedrijfslug>/contact/', ContactView.as_view(), name='contact'), ] views.py class CheckView(DetailView): template_name = 'register/check.html' model = Bedrijf slug_url_kwarg = 'bedrijfslug' context_object_name = 'bedrijf' def get(self, request, *args, **kwars): contact_url = reverse_lazy('ContactView') return render(request, 'register/check.html', {'contact_url': contact_url}) class ContactView(FormView): template_name = 'register/contact.html' form_class = BezoekerForm success_url = '/thankyou/' -
error while loading shared libraries: libgvc.so.6 (deploy django app on heroku)
I have a problem with a heroku deployment because I have an application with multiple buildpacks that use python, r, scikitlearn and grahpviz buildpacks. The application deployed corretly, but when I try to see trees that are made by graphviz I have this problem: "Program terminated with status: 127. stderr follows: /app/.heroku-buildpack-graphviz/usr/bin/dot: error while loading shared libraries: libgvc.so.6: cannot open shared object file: No such file or directory" I know that all graphviz dependeces are installed correctly but in this directory "/app/.heroku-buildpack-graphviz/usr/lib" I tried to move it but does not work. Also I use heroku-16 because I read that graphviz buildpack not work in heroku-18. Could anybody help me? -
Inserting Foreign keys using cur.execute() in Django
I'm new to programming and trying to beat it for a couple of days now with no luck yet. models.py: class Country(models.Model) : country = models.CharField(max_length=64, null = True) class City(models.Model) : city = models.CharField(max_length=64, null = True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) When I try this I get "Error binding parameter 1 - probably unsupported type." from app.models import Country, City cur.execute('''INSERT OR IGNORE INTO country (country) VALUES ( ? )''', (country,)) cur.execute('''INSERT OR IGNORE INTO city (city, country_id) VALUES ( ?, ? )''', (city, Country,)) Other than that everything works fine. I only can't insert foreign keys. I tried a lot of different things, but there's always some kind of errors. When I insert data from console it works fine. I tried same pattern but got unsupported type error or database locked error. c = Country(country='Russia') c.save() ct = City(city = 'Saint Petersburg', country = c) ct.save() -
Django prevent image upload containing possible XSS code
I am creating a site that users can upload images. I am using django-storages to forward these images to S3 bucket, but I recently read the security docs on Django's site: https://docs.djangoproject.com/en/3.0/topics/security/#user-uploaded-content Django’s media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an HTML file can be uploaded as an image if that file contains a valid PNG header followed by malicious HTML. This file will pass verification of the library that Django uses for ImageField image processing (Pillow). When this file is subsequently displayed to a user, it may be displayed as HTML depending on the type and configuration of your web server. It tells me about this vulnerability but it does not provide me an efective way of protecting against these vulnerabilities. Which is the top 3rd most vulnerable attack in websites. Consider serving static files from a cloud service or CDN to avoid some of these issues. I am using S3 to serve my media files, it does say to avoid some of the vulnarabilities described in the section, but is does not say which. My question: Is uploading and serving images to and from … -
i have misconception about this loop in python
i have a list of items and based on it, i would like to print some pieces of information so,a for loop over two items for example, if one on these two items found in somewhere i would like to share them the same print statement, else this, i would like to print a shared statement also, see example please: book = 'long text' a = ['im eating', 'im drinking'] for item in a: if item in book: print('something once')#just one item found to Be satisfied then break the code break else: print('the opposite somthing once')#if the two-items not found print one sentence exprime this once help plz -
How to programically redirect calls to files in my Static folder?
I have rating stars images in my Static folder: static MyApp 1.0-stars.svg 1.5-stars.svg 2.0-stars.svg 2.5-stars.svg ... I will prepend the rating pulled from the model before the image file when calling the image. But some ratings may be 1.6 or 1.7, which I would want to redirect to the appropriate rounded-to-0.5 star rating image (1.5-stars.svg in the former case of 1.6 and 1.7 stars). Is there a way to do this programmatically in Django, if so where exactly (in urls.py, in views.py, in models.py)? Or should I use JS to do the math before calling the correct image file? -
Permissions to GET and POST
I'm new to Django, so maybe the issue is easy to solve. I have App News and APP users. As I have to allow GET for everyone, however POST is only for the token. -
Pass QuerySet in Django url
I'm looking to pass a list as the queryset parameter to a Django ListView. I know you can do this by overwriting the get_queryset method but ideally I would like to avoid this. The reason is, I am referring from another view and already have the queryset I need so I don't want to run the same query twice. Currently I am linking to my view as follows: <a href="{url 'lab_work:project_list_ongoing' %}?projects={{active}}">{{active|length}</a> active is the prepopulated list I want to use as the queryset. My view looks as follows: class ProjectListOngoing(ListView): template_name = "<name of my template>" model = Project context_object_name = "projects" paginate_by def dispatch(self, request, *args, **kwargs): self.projects = request.GET.get('projects', []) return super().dispatch(request, *args, **kwargs) def get_queryset(self): return self.projects This does seem to populate the correct queryset however the primary keys are blank for some reason. I have the following in my template: {% for project in projects %} <li><a href="{% url 'lab_work:project_detail' pk=project.pk %}"></a></li> {% endfor %} And I get the following error: Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['project/(?P<pk>\\d+)/$'] -
ERROR Invalid option specification - AWS Elasticbeanstalk - Django
I am trying to set up my Django project using the AWS CLI service but I get the following error ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting. I work on Windows and follow these instructions: https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/. This is from 2017 and I have already made some adjustments, as the AWS services is constantly being updated But now something seems to be wrong in the python.config file. Maybe the name of the command has been changed. I couldn't find much about that anyway. This is what my python.config file looks like: container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "Whisky.settings" PYTHONPATH: "$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "Whisky/wsgi.py" StaticFiles: "/static/=www/static/" packages: yum: postgresql95-devel: [] I hope you can help me -
Removing one-to-many related models using Django
I have the below models defined in Django and am looking for a way to delete all the cookies associated with a site. models.py class Site(models.Model): created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT) class Cookie(models.Model): name = models.TextField() value = models.TextField(blank=True, null=True) host = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='cookies') I tried the following but got an error: site_object.cookies.delete() AttributeError: 'RelatedManager' object has no attribute 'delete'