Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable swagger in django projectt
I have set up drf-yasg swagger and now I'm wondering what's the best way to disable swagger, because they should not be exposed after going live. -
Modify instance before it's saved on import
I'm setting up an import process for a model which has a ForeignKey relationship, and I've got an extra field on the model where I'd like to store the provided value if it's an invalid ID of the related table. The ID's in question here are UUIDs, so there's a good chance that someone along the line will provide some invalid data. class Result(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) passport = models.ForeignKey( to='results.Passport', null=True, blank=True, on_delete=models.SET_NULL ) invalid_passport = models.CharField( max_length=255, blank=True, null=True, help_text=_("An invalid passport number") ) The import file will contain a passport column for the UUID of the related object, but I'd like to save the provided value to invalid_passport if it doesn't match any Passport instances. My resource looks like this; class ResultResource(resources.ModelResource): """ Integrate django-import-export with the Result model """ passport = fields.Field( column_name='passport', attribute='passport', widget=ForeignKeyWidget(Passport, 'id') ) class Meta: instance_loader_class = CachedInstanceLoader model = Result fields = ( 'id', 'passport', 'invalid_passport' ) def init_instance(self, row=None): """ Initializes a new Django model. """ instance = self._meta.model() if not instance.passport: instance.invalid_passport = row['passport'] return instance def before_save_instance(self, instance, using_transactions, dry_run): """ Sets the verified flags where there is a passport match. """ if instance.passport: … -
How to cache object in django template and update if it was changed?
I have a simple Django app with a single view for displaying the product list: from time import sleep <other imports> class ProductListView(ListView): model = Product paginate_by = 50 allow_empty = True def get(self, *args, **kwargs): sleep(2) return super().get(*args, **kwargs) And the template: <div class="container"> {% for product in page_obj %} <div class="col-3 my-2"> <product details> </div> {% endfor %} </div> I use sleep(2) to emulate the slow uploading of a huge amount of objects from the database. Now I need to implement the next workflow: template from this view should be cached. So the first page upload should take >2 sec, the next one <2sec, uploaded from the cache. change Product item in the database (via admin page for example) page on refresh is loaded from cache, but product info should be updated to the newest I'm, researching the Django caching mechanism, but I'm not sure which one should I try. So is it possible in Django to implement this workflow? -
One To Many Connection
So I have two models Field and Sensor which have a OneToMany connection. Im creating a page where I have all the fields and whenever i click on one i get its respective sensors. I've made 4 test sensors (3 of them are on Field1, 1 on Field2) but its printing first one to first field and 2nd one to 2nd field maybe because of the pk parameter. Any clue how to fix that ? class Field(models.Model): friendly_name = models.CharField(max_length=24, blank=True) soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True) cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) sensor_name = models.CharField(max_length=200, blank=True) longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) View : def detail(request, field_id): try: sensor = models.TreeSensor.objects.get(pk=field_id) except models.TreeSensor.DoesNotExist: raise Http404("No sensors for this field") return render(request, 'dashboard/detail.html', {'sensor': sensor}) html: <h1> {{ field.friendly_name}}</h1> {% for sensor in field.treesensor_set.all %} {{treesensor.sensor_name}} {%endfor%} -
How to instantiate model with init function in modelforms?
I have a program that uploads a csv of data in order to map values in the csv to other values. In order to do this, the user must select which columns in the csv they need to create the mapping, so that no extraneous information is on the mapping page. To do this I created a dynamic Django by overriding the init function in my ModelForm. The problem is that even though I'm able to dynamically show the column values, when the user tries to select the values and save them to the model, it fails, because the Model choices don't align with the dynamic checkbox values. So I've overridden the Model's init function to populate the model's choices. My problem is I'm not sure how to instantiate the model in the ModelForm to call the init function. model class ColumnMapping(models.Model): CHOICES =[('row_1', 'A'), ('row_2', 'B'), ('row_3', 'C')] company = models.ForeignKey(RawData, on_delete=models.CASCADE) columnNames = MultiSelectField(max_length=100, choices=CHOICES) def __init__(self, *args, **kwargs): self.choices = kwargs.pop('choices') super(ColumnMapping, self).__init__(*args, **kwargs) self._meta.get_field.choices = self.choices form - I think something needs to happen here in the Meta class, but since the model = ColumnMapping line doesn't instantiate the model (I don't think), I don't think … -
Module not found when trying to import files into Custom Django commands
Background I'm new to Django and trying to set up a Django database with react front end for a trading card game database. I'm using a custom command in Django to pull cards from MTG's API and then using a serializer to save the data I'm pulling. Problem When I try to run the custom command it fails because my program can't seem to find my serializer module. I have tried to specify the path with sys, but it doesn't seem to work and I believe all my modules have an __ init __.py so they can be recognized as modules. I'm definitely willing to admit I did these things incorrectly, however. The exact error: ModuleNotFoundError: No Module named 'MTG_hoard.api' Here is a snapshot of my project directory... Here is how I'm importing the serializer... Additional information I'm basing my project on another github project FearChar/project-4-django-app. This is how I'm importing my apps in settings.py -
Why Django formset saves only 1st form?
I have issue with formset- When I try to save all of my form from formset only first one is saved, but in request.POST I can see all of forms. What am I doing incorectly? thank you in advance! models.py: class Activity(models.IntegerChoices): LOADING = 1, 'Loading' UNLOADING = 2, 'Unloading' LOADING_UNLOADING = 3, 'Loading/Unloading' ANOTHER = 4, 'Another' class Road(models.Model): def __str__(self): return self.company_name company_name = models.CharField(max_length=100) point_address = models.CharField(max_length=200) activity = models.PositiveSmallIntegerField(default=Activity.LOADING, choices=Activity.choices) activity_time = models.DateTimeField() forms.py: class NewRoadForm(forms.ModelForm): class Meta: model = Road fields = "__all__" views.py def new_road(request, extra=2): NewRoadFormSet = modelformset_factory(Road, form=NewRoadForm, extra=extra) formset = NewRoadFormSet(queryset=Road.objects.none()) if request.method == "POST": formset = NewRoadFormSet(request.POST) print(request.POST) #<< here I see data from all forms if formset.is_valid(): for f in formset.cleaned_data: if f: print(f) ##<< here I see only from 1st form return HttpResponseRedirect(reverse("orders:new_road")) else: print(formset.errors) return render(request, 'orders/add_road.html', {'formset':formset, 'extra':extra}) template.html: {% extends 'orders/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} <input type="hidden" name="form-TOTAL_FORMS" value="{{ extra }}" id="id_form-TOTAL_FORMS"> <input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"> <input type="hidden" name="form-MIN_NUM_FORMS" value="2" id="id_form-MIN_NUM_FORMS"> <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"> {{ formset.menagement_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} <input type="submit" value="save"> … -
generate zip folder and add to storage django
Hi guys I need to generate a zip file from a bunch of images and add it as a file to the database This is the code to generate the file def create_zip_folder(asin): print('creating zip folder for asin: ' + asin) asin_object = Asin.objects.get(asin=asin) # create folder output_dir = f"/tmp/{asin}" if not os.path.exists(output_dir): os.makedirs(output_dir) # download images for img in asin_object.asin_images.all(): urllib.request.urlretrieve(img.url, f"{output_dir}/{img.id}.jpg") # zip all files in output_dir zip_file = shutil.make_archive(asin, 'zip', output_dir) asin_object.zip_file = zip_file asin_object.has_zip = True asin_object.save() # delete folder shutil.rmtree(output_dir) return True This all works and I can see the files generated in my editor but when I try to access it in the template asin.zip_file.url I get this error SuspiciousOperation at /history/ Attempted access to '/workspace/B08MFR2DRS.zip' denied. Why is this happening? I thought the file is to be uploaded to the file storage through the model but apparently it's in a restricted folder, this happens both in development (with local file storage) and in production (with s3 bucket as file storage) -
TemplateDoesNotExist at /blogapp/reset_password/ path_to/reset_password_email.html
i am trying to reset password but i got this error TemplateDoesNotExist at /blogapp/reset_password/ path_to/reset_password_email.html urls.py from django.urls import path from . import views from .views import signupview from django.contrib.auth import views as auth_views from django.urls import reverse_lazy app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<int:pk>/',views.authorview,name='author'), path('blogdata/<str:pk>/',views.blog,name='blogdata'), path('profile/<str:pk>/',views.profile,name='profile'), path('change-password/', auth_views.PasswordChangeView.as_view(template_name='blogapp/change-password.html',success_url=reverse_lazy('blogapp:password_change_done'))), path('password_change/done/',auth_views.PasswordChangeDoneView.as_view(template_name='blogapp/password_change_done.html'),name='password_change_done'), path('reset_password/',auth_views.PasswordResetView.as_view(template_name='blogapp/reset_password.html', success_url=reverse_lazy('blogapp:password_reset_done'), email_template_name='path_to/reset_password_email.html'),name='reset_password'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(template_name='blogapp/reset_password_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view( template_name='blogapp/reset_password_form.html', success_url=reverse_lazy('blogapp:password_reset_complete')),name='password_reset_confirm'), path('reset_password_complete/',auth_views.PasswordResetCompleteView.as_view(),name='Password_reset_complete'), ] -
filter search result based on checkbox Django
Trying to filter products based on brands, with the use of checkboxes. models class Product(models.Model): """ Containing the products, each product belong to a category and each product have a feedback system """ category = models.ForeignKey(Category, related_name='products', on_delete=CASCADE) name = models.CharField(max_length=55) brand = models.CharField(max_length=55) price = models.FloatField() featured = models.BooleanField(default=False) image = ResizedImageField(size=[460,460], quality=100, upload_to='products', default='None', blank=True, null=True) slug = models.SlugField(max_length=400, unique=True, blank=True) description = models.TextField(default='product', blank=True) def __str__(self): return self.name views def products(request, slug): """ List all products of a category """ category = get_object_or_404(Category, slug=slug) products = Product.objects.filter(category=category) brands = Product.objects.filter(category=category).distinct('brand') # query brands and products when pressed list = request.GET.get('list', 'brands') == 'on' if list: products = Product.objects.filter(category=category).filter(Q(name__icontains=list) | Q(brand__icontains=list) | Q(description__icontains=list)) brands = Product.objects.filter(category=category).filter(Q(name__icontains=list) | Q(brand__icontains=list) | Q(description__icontains=list)).distinct('brand') context = { 'products': products, 'category': category, 'brands': brands, 'title': Product, } return render(request, 'products/products.html', context) html <div class="filter-content collapse show flex-wrap" id="collapse_2" style=""> {% for brand in brands.all %} <div class="card-body" id="tabl"> <label class="form-check" onChange="window.location.href=this.value"> <input class="form-check-input" type="checkbox" value="?list=brands" name="brands[]" id="brands{{ brand.id }}"> <span class="form-check-label">{{ brand.brand }}</span> </label> </div> {% endfor %} </div> When the checkbox is pressed, based on the brand.id on the given checkbox, it is supposed to change the query based products of that … -
Facebook Login - Problem redirecting after confirming permission for user info
I need help for the last step of my Facebook login function. The problem is that when a new user signs in for the first time, a popup called 'www.facebook.com/v11.0/dialog/oauth' appears which prompts the new user to confirm that they allow my page to access their information. The issue is that once that user accepts the terms and confirms by clicking the 'continue as name' button, instead of being booted to my home page like I wish it did, the users is kept on my login page instead. They then need to click a second time on the 'Connect by Facebook' button, which is now able to do its job and redirect my users to the proper page. Basically I'm looking for a way to tell the Facebook login to prompt the redirect from the inside of the oauth popup and skip the need for a double click. I have set up my access in JavaScript and my code looks like this: $(document).ready(function(){ $('.login-main').on("click", ".facebook_login_class", function(){ console.log('FACEBOOK LOGIN OPTION SELECTED'); FB.getLoginStatus(function(res){ if(res.status == "connected" ){ console.log('Connected on Facebook'); FB.api('/me?fields=email,name,first_name,last_name', function(fbUser) { $.ajax({ url:'facebook_login_ajax/', method:'GET', data:{ email:fbUser.email, code:fbUser.id, }, success:function(response){ if (response.Success == true){ window.location.href = '/myhomepage/'; } } }); }); … -
My django code is requesting a table that doesn't exist
! ! I tried to delete the 'db.sqlite3' file and do the migration again, but it didn't work -
django run script with on and stop with off button in a view
I am New to django, and i'm in pain right now, i can't find a solution to render a form with data that will go into an python script imported as a class, basically, this process is for freelancer bot, that will keep search project matching the skill tags and then bidding on it, all the data ill provide with a form and when i click "run bot" button the script will continue to run until another button "stop bot", would be pressed, i presented a similar situation corresponding to the real issue for better understanding of the question, html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="{% url 'bid_func' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button value="run-script">Run Bot</button> <button value="stop-script">Stop Bot</button> </form> </body> </html> form is amount = forms.FloatField() interval = forms.IntegerField() max_bid = forms.IntegerField() like below if request is post and run-script in request data, it will start the execuion of the data passed to the script, and when the stop-script is pressed, it will stop the process, def bid_func(request): form = BidBot() if request.method == 'POST': form = BidBot(request.POST) if 'run-script' in request.POST and … -
Populate Dropdown from another Table/View
I have a site model which is connected to the municipality where the site is located. Using this municipality in a dropdown field in the create form leads to quite long loading times. The reason is the large amount of municipalities in the database but also that the administrative units are linked to each other which seems to lead to cascading queries to populate the dropdown field. Is there a way to speed this up? I thought about making a materialized view and use it to populate the dropdown field but that would lead to a value error because the value from the dropdown must be an instance of the linked model as far as I know. Is there maybe another way to make the form load faster? Or is the materialized view the way to go and I am just getting something wrong? class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) class administrative_level_5(models.Model): al5_id = models.CharField(primary_key=True, max_length=10) al5_name = models.CharField(max_length=150) geom = models.MultiPolygonField(srid=4326) class administrative_level_4(models.Model): al4_id = models.IntegerField(primary_key=True) al4_name = models.CharField(max_length=150) adm_level_5 = models.ForeignKey('administrative_level_5', on_delete=models.PROTECT) geom = models.MultiPolygonField(srid=4326) class administrative_level_3(models.Model): al3_id = models.IntegerField(primary_key=True) al3_name = models.CharField(max_length=150) adm_level_4 … -
Django can't connet to PostgreSQL Docker container via psycopg2
I am trying to migrate a django project on macOS Monterey 12.3, and I am having some troubles. It seems like psycopg2 doesn't want to connect to my docker container at all. Everytime it prints this error: django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5433 failed: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. For my docker process, I create it by running docker run --name local-postgres -p 5433:5433 -e POSTGRES_PASSWORD=test123 -d postgres I am running python 3.9.12 in a virtual environment using pipenv, and my arch is arm64, for anyone wondering. I've tried changing the ports, I've tried resetting, completely removing docker and downloading it again, reinstalling django and reinstalling the venv again and so far nothing has worked. I've also tried setting the CONN_MAX_AGE=0 in settings, which has not worked. Please help -
Django forms - filter field by user.id
I have the following situation with Django that i cannot resolve. How to filter/sort field 'training' to represent only the trainings that are owned by the user that is logged in. Thank you in advance! class Exercise(mоdels.Model): MAX_LENGTH = 25 name = mоdels.CharField( mаx_length=MAX_LENGTH ) weight = mоdels.IntegerField() series = mоdels.IntegerField() reps = mоdels.IntegerField() training = models.FоreignKey('Workout', оn_delete=mоdels.CASCADE) class CreateExerciseFоrm(forms.ModelFоrm): class Meta: model = SingleExercisе fields = ('name', 'weight', 'series', 'reps', 'training', ) -
Django : Display file content in the same page on the click of a file listed in a table
I have this page where I upload files to a blob storage and then they are listed in a table. I want that the user can visualize the files that he has uploaded. So I would like to add next this two vertical containers, one to display the content of the file when the user clicks on one of the listed files. I have no idea how I should include that on my view "upload" see below. Would it be easier to display it in a new view ? Anyone can show me how I can include that in my view and the template ? Thank you views.py @authenticated_user @check_user_rights() def upload(request, id_contrat): # INITIALIZE THE CONTEXT TO FIX THE AUTHENTICATION context = initialize_context(request) username = request.session.get('user').get('name') ############################################################ # WE SET THE BLOB STORAGE PARAMETER ############################################################ credential = "" account_url = "" container = "" blob_service_client = BlobServiceClient(account_url= account_url, credential= credential) ############################################################ # UPLOAD FILES ############################################################ if request.method == 'POST': form = FilesForm(request.POST, request.FILES) files_selected = request.FILES.getlist('Filename') if form.is_valid(): for f in files_selected : # THE PREVOUS FILENAME IS STORED previous_name = f.name content = f.read() # WE RENAME THE FILE ext = f.name.split('.')[-1] name = f.name.split('.')[0] f.name = "%s_%s.%s" … -
One To Many Connection in Django
So I have two models Field and Sensor which have a OneToMany connection. Im creating a page where I have all the fields and whenever i click on one i get its respective sensors. I've made 4 test sensors (3 of them are on Field1, 1 on Field2) but its printing first one to first field and 2nd one to 2nd field maybe because of the pk parameter. Any clue how to fix that ? class Field(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None) friendly_name = models.CharField(max_length=24, blank=True) soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True) cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True) class TreeSensor(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) sensor_name = models.CharField(max_length=200, blank=True) longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) View : def detail(request, field_id): try: sensor = models.TreeSensor.objects.get(pk=field_id) except models.TreeSensor.DoesNotExist: raise Http404("No sensors for this field") return render(request, 'dashboard/detail.html', {'sensor': sensor}) html: <h1> {{ field.friendly_name}}</h1> {% for sensor in field.treesensor_set.all %} {{treesensor.sensor_name}} {%endfor%} -
Error while accessing Django model in admin view
I was trying to access objects of StockDailyPrice model from my Django Admin view. But I'm seeing the following error while doing so Environment: Request Method: GET Request URL: http://localhost:8000/admin/api/stockdailyprice/ Django Version: 4.0.3 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'corsheaders'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (operator does not exist: character varying = bigint LINE 1: ..."api_stock" ON ("api_stockdailyprice"."symbol_id" = "api_sto... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception: File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", … -
Populating drop-down list with strings, but want to send integer 'id' in form
So I have a Django form where one of the fields selected_candidate is a drop down menu of candidates that exist in an election/vote. The field is currently a ChoiceField because when I use and IntegerField the dropdown menu is not populated. Here is the vote function def vote(request, id): election_to_vote = elections[id] candidates_to_vote = () for i in range(len(candidates)): if candidates[i][3] == id: candidates_to_vote += ((candidates[i][0], candidates[i][1]), ) if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): data = form.cleaned_data pps = request.POST.get('user_pps') cand = request.POST.get('selected_candidate') context = { 'form':form } return render(request, 'vote/test.html', context) else: form = VoteForm() form.fields['selected_candidate'].choices = [(c[0], c[1]) for c in candidates_to_vote] context = { 'form': form, 'election': election_to_vote, 'candidates': candidates_to_vote } return render(request, 'vote/vote.html', context) I am never able to pass the form.is_valid() statement. It gives me the following error: selected_candidate: Select a valid choice. 0 is not one of the available choices. I know that this is because I am passing the id associated with the candidate, but populating the list with the candidates name, which is a string, but I'm not sure how exactly I would populate the list with a string, but send off the canidates ID which is an … -
How to pass data from form in template to django views?
So I have this little project with messages and comments and i don't know how to save particular comment to particular message. Does anybody know how can i get message.id from template and send it to views.py? {% for message in messages_all %} <ul> <li>@{{message.host}}</li> <li>{{message.body}}</li> </ul> {% for comment in comments_all %} {% if comment.message == message %} <ul> <li>{{comment.body}}</li> </ul> {% endif %} {% endfor %} {% if request.user.is_authenticated %} <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Dodaj komentarz"> </form> {% endif %} <hr> {% endfor %} -
Issue importing modules with Django, but runs fine when I run it independently using '-m' flag
Currently I have a python project with the following directory structure. I can run the demo.py file directly fine (without importing it in my Django project) from the outermost directory shown above using the following command: python -m ObjectSegmentation.segmentation_api.apps.tools.demo However, in my Django project, I need to import the demo.py file in my django views.py file, but when I do so, I get the following error: from ObjectSegmentation.segmentation_api.apps.tools.test import * ModuleNotFoundError: No module named 'ObjectSegmentation' These are the first few lines from demo.py (including line 4) where the error occurs. My installed apps in settings.py for the whole project look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.tools.demo', 'rest_framework' ] How can I make it so that the imports work with both the project run independently and imported in my django project? -
How to check script is still running or not (which is called within subprcoess) in django
I am working on Django framework, there inside some function need to call one script (it is shell script). So have called it through subprocess.Popen(command). def func(request): if request.method=="POST": '''Collect data''' subprocess.Popen(command, shell=True) return render() The command which is inside subprocess.Popem may run for sometime. Now have to check whether this command is still running or not, means status of command whether it is running or completed. Could anyone help here? Thanks. -
django dynamic content in query
I am trying to "DRY" my code and would like to create a function to make my query dynamic. The code that I currently use is : rightone = [] for item in taglist: #taglist is a list of model instances, not relevant here content = content.filter(tags__title=item.title) #tags here is a M2M key : my problem, content is a query rightone.append(content) tagproofquery = rightone[-1] and I would like to convert it to: def uniquetogether(queryset,data, model): rightone = [] for item in queryset: content = data.filter(tags__title=item.title) # <--- problem is here with tags rightone.append(content) tagproofquery = rightone[-1] return tagproofquery I have no idea how to replace my M2M "tags" as in tags__title=item.title with the "model" parameter of my function. I tried f strings but it failed miserably (of course). Is there a way to do this? Many thanks -
How to add actions to Python django admin page
I have a django project in which the the form records the name and the email addresses of the users and I was able to put that data using forms.py and models.py. What I want to do nextis to create an action through which I can download that in csv file. My admin page looks like this now and I want to add action right above.