Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: source code string cannot contain null bytes when I install a new requirements.txt file
I did a pip install -r requirements.txt and after that, realized that my development server could nolonger start. I have been unable to tell which of the files installed caused this. I even tried to re-install a previous requirements.txt file I had before this one but the nothing changed. Could anyone be having a clue on what exactly is happening from this traceback message? Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Django templates using buttons for Boolean fields
I have a preferences page that has many Boolean fields. I created an UpdateView and when I use {{ form.as_p }} in my template it works, but I am trying to create individual buttons for each option instead of checkboxes. I couldn't find a way to make it work in my template. models.py class Preference(models.Model): user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True) option1= models.BooleanField(default=False) option2= models.BooleanField(default=False) option3= models.BooleanField(default=False) option4= models.BooleanField(default=False) views.py class preferencesview(UpdateView): model = Preference form_class = PreferenceForm success_url = reverse_lazy("profiles:preferences") forms.py class PreferenceForm (forms.ModelForm): class Meta: model = Preference exclude = ['user'] I want to have individual buttons for each option and a submit button to save the changes. Please let me know if you have any documentation or tutorials. Thanks! -
Django-Tables2-Column-Shifter <frozen importlib._bootstrap> Error When Getting Table Class
I am using the Django-Tables2-Column-Shifter Django library successfully in my Django application from one of my applications named app1. I am running into a bizarre error when attempting to use the same logic to use Django-Tables2-Column-Shifter from another app app2 which uses a different model. The error that I am receiving is below: File "/home/datavizapp/.virtualenvs/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project_name' The code posted below all works as expected. The error arises in the get_table_class code when I change the following: tabledata_table = get_table_1_class( self.table_class_version )(tabledata_queryset) to tabledata_table = get_table_2_class( self.table_class_version )(tabledata_queryset) Below is "views.py" inside app2 from project_name.app1.models import Table1 from project_name.app2.models import Table2 from project_name.app2.tables import get_table_1_class from project_name.app2.tables import get_table_2_class #from project_name.app1.tables import get_table_1_class # This also works if uncommented (original code is in app1) from django_tables2_column_shifter.tables import ( ColumnShiftTableBootstrap4 ) from … -
Got error when trying to remove auth and user tables in Django migration
I am using Django to create rest apis. But as I notice whenever I migrate tables to databases tables such asauth_ user_ got migrated as well. I want to prevent that so I remove some rows of INSTALLED_APPS in settings.py INSTALLE D_APPS = [ # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', 'devices', 'django_crontab', 'drf_yasg', ] But I go this error, when trying to run py manage.py makemigrations. Traceback (most recent call last): File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'admin' ...................... LookupError: No installed app with label 'admin'. -
Django: Is it possible to get field values for a list of objects in bulk?
This is probably a silly question, but for some reason I just cannot find a way to do this: I am working on a recommendation engine in Django, which recommends movies based on the similarities between your taste and other users' tastes. Since every database access takes time, I try to use bulk methods as much as possible. However, at one point I need to get the movie that is associated with a certain vote, and I just cannot figure out how to do this in bulk: The relevant models are: class Movie(models.Model): id = models.AutoField(primary_key=True) ... voters = models.ManyToManyField(Voter) ... and class MovieVote(models.Model): rating = models.FloatField() weight = models.FloatField() voter = models.ForeignKey(Voter, on_delete=models.CASCADE, null=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True) ... And the one line that currently takes 80%(!) of the time of the whole recommendation process is: for otherVote in listOfOtherVotes: ... movie = otherVote.movie ... Is there any way to look up the foreign key "movie" for the whole list of votes at once? And ideally return it as a dictionary that maps each vote to the movie? -
Iterate through fields using array Django
I have this model: class Some_model(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: # create a function to upload a model object given a json object def upload_object_values(model, json_values, keys=None): if json_values: # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object has keys to check if keys: # check if exists using the keys when called like this: upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2']) It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter). Some_model.objects.get_or_create(field_2='val_2') -
PostgreSQL - compare python list to table rows
tried to look around on the internet for this for a while without success. I have a python list which looks like this: [{'id': 5, 'field1': True}, {'id': 6, 'field1': False}] It's just a list of dictionaries containing key/value pairs. Now, I'm asking myself whether there is any way to look up an SQL Table by every id in the list and only return the row if 'field1' is different. Say my table looks like: id field1 ----------- 5 True 6 True Given that the row with the id of field 6 differs in the value of field1, only that row should be included in the resulting query. Is there any way to achieve this with SQL or would I need to loop through it manually? My use case involves a lot of rows, and this process would be repeated many times, so I'm trying to find the most efficient way to do it. As a sidenote: I am using Postgres. Thank you! -
Making django server tick?
I have a django server setup on Linux/Apache/Mysql with WSGI (WGSIDaemonProcess/WGSIDaemonGroup/WSGIScriptAlias). I'd like to write a python function that has access to all the backend models and stuff that a normal view function has, and to have that function run periodically (perhaps once a second or faster) while the server is up. I guess I could write a new view function and then write a local script to GET that url every second, but is there a way of doing this within the django app itself? -
How to show the number of items from database according to drop down menu number in django?
I am new to django. I have 100 items in database, and i have dropdown menu number [1,5,10,20]. if i select 20 then i would like to show 20 items with 5 different pages. if i select 10, i would like to show 10 items in one page with 10 different pages in django. I would really appreciate it if you could tell me how to do that. I have no idea how to do it. I made HTML drop down menu with number, but how can i connect it to database, and populate and show it? <option value="1">1</option> <option value="5">5</option> <option value="10">10</option> <option value="20">20</option> -
Making button content dynamic
I have a subscribe button on the nav bar of my index.html, which leads a user to subsribe.html, where they get to fill in a form and the data gets stored in the data base. The users are then redirected back to the home page. I want to make it possible so that when a user finishes filling in the form and submits, and he is redirected back to the homepage, then the button changes from subscribe, to subscribed. But only for users who have already submitted the form. Users who have not yet subscribed will still see the button in its original format. Which is the best and easiest way to do this? I have tried doing it through vue, where I can use axios, but I have been unable to integrate the two applications. If there is an easier method like Ajax, or even CSS, then kindly please share the procedure index.html <div id="app"> <a href="subscribe"> <button type="button" class="btn btn-warning mx-5"> Subscribe </button> </a> </div> subscribe.html {% extends 'index.html' %} {% block subscribe %} <div class="card mx-5"> <h1 class="mx-5 mt-3"> Subscribe</h1> <form method="POST" enctype="multipart/form-data" action="subscribe"> {% csrf_token %} <div class="mb-3 mx-5"> <label for="firstname" class="form-label ">First Name</label> <input type="text" … -
Overriding django-allauth views to use with modals
I am trying to handle login/registration functionality in a modal. I got successful login/registration working by importing the LoginForm and RegistrationForm into my modal view and then posting to the appropriate allauth URLs. The desired behavior is to have forms with errors rendered asynchronously in the modal. I have not been able to get forms with errors (email doesn't exist when trying to login, passwords don't match when registering etc.) to render as an html partial in a modal with the errors. I'm not too sure where to start when trying to add this functionality into my own view/how to piggyback on the allauth views and change their functionality. Adding the below to my views.py and url.py I've managed to get the allauth default template to load when the form is invalid (e.g. email field does not contain a valid email) but have not been able to get my template to load. From views.py: class LoginViewSnippet(LoginView): success_url = reverse_lazy('home') template_name = 'user_app/partials/loginmodal.html' def get_context_data(self, **kwargs): print('here1') context = super(LoginView,self).get_context_data(**kwargs) return context def form_invalid(self, form): print('here') error_msg = 'error' return HttpResponse(error_msg, status=400) login = LoginViewSnippet.as_view() From urls.py: path('accounts/login',user_app_views.login, name='account_login'), From user_app/partials/loginmodal.html: ... <div class="modal-body"> <form id="loginform" method="POST" action="{% url 'account_login' %}" … -
How to fix Pinax Django project getting started migration ERROR?
I am following this guide https://pinaxproject.com/pinax/quick_start/ but at the "Modern Local Development Steps" after the follwing command I get an error: ./manage.py migrate ERROR: Traceback (most recent call last): File "/Users/iuser/myproject/myapp/./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/apps/config.py", line 126, in create mod = import_module(mod_path) File "/usr/local/Cellar/python@3.9/3.9.7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/iuser/myproject/v1/lib/python3.9/site-packages/pinax/templates/apps.py", line 2, in <module> from django.utils.translation import ugettext_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (/Users/iuser/myproject/v1/lib/python3.9/site-packages/django/utils/translation/__init__.py) -
Filter Django model with json values
I have this function: # create a function to upload an object one to one given a json def upload_object_values(model, json_values, update_if_exists=True): if json_values: # the json values contain key value that match to the model # use a copy to avoid runtime error dictionary changing size for json_value in json_values.copy(): # remove all ids in model copy if json_value[-3:] == '_id' or json_value == 'id': json_values.pop(json_value) # assign a value to each key which is a the field in the given model for key, value in json_values.items(): setattr(model, key, value) # if the object is get or create, or an update if exists if update_if_exists: # if it exists if model.__class__.objects.seal().exists(): # retrieve the existing object retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values # assign values into it retrieved_object = model # save retrieved_object.save() print(retrieved_object) print('existing, saved successfully') # if it does not exist else: # save model.save() print('does not exist, saved successfully') # else just save else: model.save() print('created successfully') with sample json_values like: {'notes': '', 'name': 'test issuer', 'phone': None} I need to be able to filter using the json_values that I have, as shown in the line: retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the … -
sending calendar in mails using django
I am using mandrill for sending mails after registering the events- mandrill_client = mandrill.Mandrill(MANDRILL_API_KEY) message = { 'html': template_func, 'from_email': 'email@xyz', 'from_name': 'any_name', 'global_merge_vars': [], # need reply mail 'headers': {'Reply-To': 'email@xyz'}, 'merge': True, 'merge_language': 'mailchimp', 'subject': "Event Registered", 'tags': ['password-resets'], 'text': 'Example text content', 'to': [{'email': to_email, 'name': user_name, 'type': 'to'}], } result = mandrill_client.messages.send(message = message) print(result) status = result[0]["status"] This is working fine. but I also want to send calendar. Is there a way to add calendar with mandrill or by any other method. Thank you! -
How to get the User id from the URL search input that contains first name & last name
I created a search bar, where users can search by name and/or the last name of other users. When they submit, it should take them to the profile page of that user based on the search name/last_name provided in the URL. The script from the template, where the search bar is - works ok: <script> new Autocomplete('#autocomplete', { search : input => { const url = `/search/?search_item=${input}` return new Promise(resolve => { fetch(url) .then(response => response.json() .then(data => { resolve(data.data) })) }) }, }) </script> urls.py path('search/', views.search_name, name='search_name'), views.py which generates list of Users in db matching search item: @login_required def search_name(request): search_item = request.GET.get('search_item') payload = [] if search_item: search_item_objects = User.objects.filter( Q(first_name__icontains=search_item) | Q(last_name__icontains=search_item)) for search_item_object in search_item_objects: payload.append(search_item_object.first_name + ' ' + search_item_object.last_name) return JsonResponse({'status':200, 'data': payload}) Now, I added onSubmit to the script - so the updated template is: <script> new Autocomplete('#autocomplete', { search : input => { const url = `/search/?search_item=${input}` return new Promise(resolve => { fetch(url) .then(response => response.json() .then(data => { resolve(data.data) })) }) }, onSubmit : result => { window.open(`/member/?search_item=${result}`) } }) </script> Here is what I'm getting: http://club/member/?search_item=Johny%20Bravo How to obtain the ID of the User having the URL {result} … -
Containers in pod won't talk to each other in Kubernetes
I have three containers in a pod: nginx, redis, custom django app. It seems like none of them talk to each other with kubernetes. In docker compose they do but I can't use docker compose in production. The django container gets this error: [2022-06-20 21:45:49,420: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error 111 connecting to redis:6379. Connection refused.. Trying again in 32.00 seconds... (16/100) and the nginx container starts but never shows any traffic. Trying to connect to localhost:8000 gets no reply. Any idea whats wrong with my yml file? apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: creationTimestamp: null name: djangonetwork spec: ingress: - from: - podSelector: matchLabels: io.kompose.network/djangonetwork: "true" podSelector: matchLabels: io.kompose.network/djangonetwork: "true" --- apiVersion: v1 data: DB_HOST: db DB_NAME: django_db DB_PASSWORD: password DB_PORT: "5432" DB_USER: user kind: ConfigMap metadata: creationTimestamp: null labels: io.kompose.service: web name: envs--django --- apiVersion: apps/v1 kind: Deployment metadata: labels: io.kompose.service: web name: web spec: replicas: 1 selector: matchLabels: io.kompose.service: web strategy: type: Recreate template: metadata: labels: io.kompose.network/djangonetwork: "true" io.kompose.service: web spec: containers: - image: nginx:alpine name: nginxcontainer ports: - containerPort: 8000 - image: redis:alpine name: rediscontainer ports: - containerPort: 6379 resources: {} - env: - name: DB_HOST valueFrom: configMapKeyRef: key: DB_HOST name: envs--django - name: DB_NAME … -
If Select choice option is selected shows something in the django
I'm using django forms to make a user registration form and it has two different types of users I want that when selecting one of the types of user, in the html it shows registration information specific to that type of user example: if I choose a doctor I will ask for his medical identification, if I choose a patient with a medical history Like this -
Issue with pip install [Any package] on windows server
Good morning everyone I am having a serious issue with my Django projetc. After typing this : pip install django Here is the outcome : ERROR: Exception: Traceback (most recent call last): File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 472, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 341, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria if not criterion.candidates: File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_vendor\resolvelib\structs.py", line 151, in bool return bool(self._sequence) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 140, in bool return any(self) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 128, in return (c for c in iterator if id(c) not in self._incompatible_ids) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 29, in _iter_built for version, func in infos: File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\resolution\resolvelib\factory.py", line 272, in iter_index_candidate_infos result = self._finder.find_best_candidate( File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 851, in find_best_candidate candidates = self.find_all_candidates(project_name) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 798, in find_all_candidates page_candidates = list(page_candidates_it) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\sources.py", line 134, in page_candidates yield from self._candidates_from_page(self._link) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\package_finder.py", line 758, in process_project_url html_page = self._link_collector.fetch_page(project_url) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\collector.py", line 490, in fetch_page return _get_html_page(location, session=self.session) File "C:\Users\cpgnanih\AppData\Local\Programs\Python\Python39\lib\site-packages\pip_internal\index\collector.py", line … -
No related, column doesn't exist, None by None
Good night. Can someone explain me what happened in my situation? I have models and databases. When I decided to add some additional field in development, I often have issues like in the title of the question. So what I was doing to fix this. I'm using migrate --fake and deleted with migrations and returned back again with migrations. Obviously it works, but I still can't understand this magic.) But ok it works for me. When I deployed the code in production it displayed me again this errors. And I repeated the steps for production. It can be OK for me, but today I lost my data, it transformed into None by None. Is it because I add to new fields such attributes like null=True, blank=True? Or it happened because I have issues with migrations and I often faked them? -
Pass data from one form to another one in Django forms/views
I'm not too knowledgeable in Django, but I wanted to implement this idea that I have but I can't seem to think how to get there. Now, on my web app, there is a form with a field called "contractor", and it has a button which, when clicked, opens a modal with another form with different fields about the "contractor". I would like it to, when information is submitted about the contractor in the second form, it autofills the field in the first form with the data from the first field of the second form. Also, I want to make it so that when the user starts typing in that "contractor" field in the first form, already submitted data can be chosen. I leave my code here to give you an idea: models.py class Contratos(models.Model): name=models.CharField(max_length=30) contractor=models.ForeignKey(Vendors, on_delete=models.CASCADE, to_field='contractee_vendor') contractee=models.CharField(max_length=30) [......] class Vendors(models.Model): contractee_vendor=models.CharField(max_length=30, unique=True) company=models.CharField(max_length=30) description=models.TextField() [......] views.py def ContractView(request): form=contractsform(request.POST) if form.is_valid(): con =form.save() return redirect('contracts', con.id) else: form = contractsform() return render(request, 'contform.html', {'form': form}) class VendorsModal(BSModalCreateView): template_name = 'vendform.html' form_class = vendorsform success_message = 'Success: Vendor created' success_url = reverse_lazy('new-contract') from my contracts HTML to open modal <form action="" method=POST> {% csrf_token %} <label for="{{ form.subject.id_for_label … -
Django 4.x - Conditional QuerySet for Pagination and a many-to-many relationship
Disclaimer: I have searched and a question tackling this particular challenge could not be found at the time of posting. The Requirement For a Class Based View I need to implement Pagination for a QuerySet derived through a many to many relationship. Here's the requirement with a more concrete description: Many Library Records can belong to many Collections Web pages are required for most (but not necessarily all) Collections, and so I need to build views/templates/urls based on what the client identifies as required Each Collection Page displaying the relevant Library Records requires Pagination, as there may be 100's of records to display. The First Approach And so with this requirement in mind I approached this as I normally would when building a CBV with Pagination. However, this approach did not allow me to meet the requirement. What I quickly discovered was that the Pagination method in the CBV was building the object based on the declared model, but the many to many relationship was not working for me. I explored the use of object in the template, but after a number of attempts I was getting nowhere. I need to display Library Record objects but the many to many … -
Celery not getting ready message not comming
I'm having a bizarre problem when I run my celery it's loading but not giving the ready message, if I run any task it is running the function but not giving any success message within seconds this is my celery.py **from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ontym.settings') app = Celery('ontym') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()** celery server tasks.py from celery import shared_task @shared_task def hello_task(name): print("hello from task",name) result -
How to add an pre-seleted photo in file-upload filed?
My Form Image I am working on a upload post page which includes images. When I am on update page I want my previously uploaded photo to be chosen already in the file-upload field. I am doing like this in my html file but it is not working <div class="qq-uploader-buttonText-value"> </div> <input type="file" id="input_22" name="photo1" class="form-control-file" data-imagevalidate="yes" data-file-accept="pdf, doc, docx, xls, xlsx, csv, txt, rtf, html, zip, mp3, wma, mpg, flv, avi, jpg, jpeg, png, gif" data-file-maxsize="10854" data-file-minsize="0" data-file-limit="" value="{{Posts.photo1.url}}" data-component="fileupload" /> </div> Can anyone help me how I do this? -
backend doesn't found for apple auth
I use django auth system with this document I set each BACKENDS in settins.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.apple.AppleIdAuth', 'social_core.backends.facebook.FacebookOAuth2', ) then try to use url in template. <a href="{% url 'social:begin' 'google-oauth2' %}">Google login</a> <a href="{% url 'social:begin' 'apple' %}">Apple login</a> <a href="{% url 'social:begin' 'facebook' %}">Facebook login</a> google and facebook works correctly, but for apple shows 404 error Page not found (404) Backend not found How can I find the template name for apple?? -
Djnago rest framework how to overwrite update method for allow only update user onw content
I don't want to allow any user update another user object. I want to allow only update user own content. here is my code: models.py class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' def update(self, request, slug=None): pass