Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deleting GeoServer layer with Django
I am trying to delete from the GeoServer using Django with request.delete, however, I get the 401 error. GEOSERVER_URL = f"http://admin:geoserver@GEOSERVER:8080/geoserver/rest/workspaces" def delete_geotiff_from_geoserver_task(owner_id, project_id, imageURL): layer_name = f'{owner_id}-{project_id}' workspace_name = 'geotiffs' geoserver_headers = {'Content-type': 'image/tiff'} url = f"{GEOSERVER_URL}/{workspace_name}/coveragestores/{layer_name}" response = requests.delete(url, data=open( f"{imageURL}", 'rb'), headers=geoserver_headers) return {"response code": response.status_code, "url": str(url), "project_id": project_id, "image data": str(imageURL)} I should have the necessary authorizations, and my code for adding a GeoTIFF, which is fairly similar, worked, so I am not sure why this would not work I have included the logs in my Geoserver below 2021-08-16 18:22:00,941 ERROR [org.geoserver.rest] - coveragestore not empty org.geoserver.rest.RestException 401 UNAUTHORIZED: coveragestore not empty at org.geoserver.rest.catalog.CoverageStoreController.coverageStoreDelete(CoverageStoreController.java:178) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931) at javax.servlet.http.HttpServlet.service(HttpServlet.java:666) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:352) at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:171) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.filters.ThreadLocalsCleanupFilter.doFilter(ThreadLocalsCleanupFilter.java:26) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:69) at org.geoserver.flow.controller.IpBlacklistFilter.doFilter(IpBlacklistFilter.java:89) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.wms.animate.AnimatorFilter.doFilter(AnimatorFilter.java:70) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.monitor.MonitorFilter.doFilter(MonitorFilter.java:142) at org.geoserver.filters.SpringDelegatingFilter$Chain.doFilter(SpringDelegatingFilter.java:66) at org.geoserver.filters.SpringDelegatingFilter.doFilter(SpringDelegatingFilter.java:41) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.geoserver.platform.AdvancedDispatchFilter.doFilter(AdvancedDispatchFilter.java:37) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.geoserver.security.filter.GeoServerCompositeFilter$NestedFilterChain.doFilter(GeoServerCompositeFilter.java:70) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) … -
How to fix an error which occurs when I am trying to delete an object related to another objects in Django app as an admin?
I have a class named Customer: class Customer(models.Model): # One to one relationship: customer is a user user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) # Returns the string representation of an object def __str__(self): return self.name ... And a class named Order (customer can have many orders). class Order(models.Model): objects = None # many to one relationship: customer can have many orders customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) # You can access the parent class from inside a method of a child class by using super() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.id = None def __str__(self): return str(self.id) When I am trying to remove the object of class Customer I have created, named Kasia (which is probably superuser as well) I cannot do it. I have previously deleted this customer's orders and now they are set to Null value. There is a type error and a message: 'Model instances without primary key values are unhashable'. The exception location is as follows: C:\Users\kasia\AppData\Roaming\Python\Python37\site-packages\django\db\models\base.py, line 536, in hash When I want to delete user, the same thing happens. What is happening here? -
Extended user registration (to Profileuser) before login, is it possible?
So am trying to solve this: Registration -> Registration Profile -> Login (In admin Registration = User and RegisterPage = Profileuser app) Got registration working connected to login, but would like the user to add info to the Profileuser app BEFORE login. Am trying to use signals to. Getting error: NoReverseMatch at /profileusers/register/ Reverse for 'RegisterPage' not found. 'RegisterPage' is not a valid view function or pattern name. Really appreciate any help on how to go about it! (And, yes, am new at this, still learning.) url.py from django.urls import path from . import views urlpatterns = [ path('', views.all_profiles, name='profiles'), path('profile_details/', views.profile_details, name='profile_details'), path('profile_edit/', views.profile_edit, name='profile_edit'), path('register/', views.Register, name='register'), path('register_profile/', views.RegisterPage, name='register_profile'), # <int:pk>/ path('login/', views.loginPage, name='login'), ] views.py from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db.models.functions import Lower from django.http import JsonResponse from django.core import serializers from django.views.generic import TemplateView, View from .models import Profileuser from .forms import ProfileuserForm, EditForm, RegisterUserForm def Register(request): # pylint: disable=maybe-no-member form = RegisterUserForm() if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' … -
Change href to django iterated object with Javascript
I have a template with a formset: <form method='post' id="data_form"> {% csrf_token %} {{ my_formset.management_form }} <table> ... <tbody> {% for form in my_formset %} <tr> {% for field in form %} {% if 'inventory_number' in field.auto_id %} <td> <a href="{% url 'invent:update_item' pk %}" class="update-link"> {{ field.value }} </a> </td> {% else %} <td>{{ field }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> </form> Since the field "inventory_number" is supposed to be immutable anyway, I want it to link to the UpdateView of this item. I can get pk for this item with JS: var links = document.getElementsByClassName('update-link') for (let i = 0; i < links.length; i++){ let link_row = links[i].parentNode.parentNode let item_id = link_row.lastElementChild.childNodes[1].attributes.value.value }; Now how do I pass this item_id form the script to django {% url 'invent:update_item' pk %}? Or maybe there's a better way to do it all together. -
Django duplicate primary keys
I have a form that creates an object with the same previous id after submission. How do I change the uuid to be random each time? class TbTerminalPermission(models.Model): id = models.CharField( primary_key=True, default=str(uuid.uuid4()).replace('-', ''), max_length=60) terminal = models.ForeignKey( 'app.TbTerminal', on_delete=models.CASCADE, db_column='ter_id') user = models.ForeignKey( TbUser, on_delete=models.CASCADE, db_column='user_id') class Meta: managed = False db_table = 'tb_terminal_permission' unique_together = ('id', 'terminal', 'user') class TbTerminalPermissionForm(forms.ModelForm): class Meta: model = TbTerminalPermission fields = ['user', 'terminal'] def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user if self.user: self.fields['user'].queryset = TbUser.objects.filter( id=self.user.id) self.fields['terminal'].queryset = TbTerminal.objects.exclude( tbterminalpermission__user=self.user).filter(customer=self.user.customer) the error Exception Value: (1062, "Duplicate entry 'ea870f29ec124e39aa5251b0862635f3' for key 'PRIMARY'") -
Django not saving form
Im abit lost, in relation to referencing other models in forms. I created the following form which references auditsModel as the model: class auditForm(ModelForm): class Meta: model = auditsModel fields = '__all__' Everything works fine and i am able to delete, add and save data in the form, but then i wanted to create drop down windows with options, and these options(Data validation) were stored in another model called dv_model. So i created the following field using ModelChoiceField which takes as a query the dv_model. Defect_Area_Associate = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) Everything works but when i click save, and refresh the page, it goes back to how it was. Something else that i noticed is that the other fields that would usually save, if i tried to change them, id get the following error: IntegrityError at /A3QGSDAKRQXG6H/ NOT NULL constraint failed: main_auditsmodel.Defect_Area_Associate So for some reason it doesnt save the form when referencing another model? This is my forms.py: class auditForm(ModelForm): class Meta: model = auditsModel fields = '__all__' #RADIO BUTTONS CHOICES = [('Defect', 'yes'), ('No Defect', 'no')] CHOICES_Action_correctly_captured = [('yes', 'yes'), ('no', 'no')] Audit_outcome = forms.ChoiceField(choices=CHOICES, widget=RadioSelect()) Action_correctly_captured = forms.ChoiceField(choices=CHOICES_Action_correctly_captured, widget=RadioSelect()) Defect_Area_Associate = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Defect_Area_dv',flat=True).distinct(),widget=forms.Select) def __init__(self, *args, **kwargs): super(auditForm, self).__init__(*args, **kwargs) # … -
What should one use for push notification from server side?
Most of the modern framework provide some means to leverage web sockets out of box for example django has django channel, rails has action cable. So in the scenario where you need to build a push notification services for your web application/mobile app what should one use websockets provided by the framework or some external services provided by different cloud providers like amazon sns. Can someone share pros and cons of both? -
Is there a JavaScript library I could use to create a musical notation website? [closed]
I'm working on a musical notation website. The site will provide users with the ability to create scoresheets, similar to noteflight. Is there any JavaScript library I could use for this? It would be even better if I could get an open-source project similar to noteflight. -
How can i get a dropdown for a CharField in Wagtail Admin?
In Django Admin, it is possible to add a dropdown selector with all possible enum values like this example: class ThesisStatus(models.TextChoices): OPEN = 'O', _('Offen') TAKEN = 'T', _('Vergeben') WORK_IN_PROGRESS = 'W', _('In Arbeit') COMPLETED = 'C', _('Komplett') ABORTED = 'A', _('Abgebrochen') status = models.CharField( max_length=1, choices=ThesisStatus.choices, default=ThesisStatus.OPEN, ) In wagtail, this does not work: panels = [ FieldPanel('status'), ] if the field is a CharField, but it does work for a TextField. How can I fix or implement this for CharField? -
How to use paginate_orphans in django function based views?
In Class-Based View We Can Use Like This. class PostListView(ListView): model = Post template_name ='blog/index.html' ordering = ['id'] paginate_by = 5 paginate_orphans = 2 But How can I Use this paginate_orphans in function-based views? page = request.GET.get('page', 1) paginator = Paginator(filter_qs, 2) try: filter_qs = paginator.page(page) except PageNotAnInteger: filter_qs = paginator.page(1) except EmptyPage: filter_qs = paginator.page(paginator.num_pages) -
one to many relationship not showing in admin
I was making a post system with two models Post and Image. I want one post to have multiple images Here is my models class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) content = models.CharField(max_length=150, null=False) images = models.ManyToOneRel( field="image", to="Image", field_name="images") class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) image = models.ImageField() post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="images") When I checked it in admin the images field is not shown. I am not entirely sure how to use ManyToOneRel in django. So far what I understood is I need my post saved before i can add an image. Is there any other way I can have multiple images for one post -
how to compare db fetched data with user selected inputs in django
I am currently working on a django project that store images in database along with additional information(Gender & age groups).To begin with when the project starts it will take user an index page(index.html) index page and after clicking take part button user gets to another page(test.html)challenge page where randomly 9 fetched images from db was showed in a grid manner and asked the user to select particular group of images from the shown images, now I have a "TRY ANOTHER" button in case user wants to reload new set of images with different question and I have a button "NO ONE" in case no images from the given group are shown in the grid. In addition to I have another and last button "VERIFY", by clicking which if the users guess is right ( selected images matches the result of the question ) it will redirect to the index page (index.html) or if user guessed input is wrong it will reload the challenge page with another set of images as well as new question. now my question is: how to compare the data fetched alongside with image with question. when the challenge page is loaded it take so much time, … -
FileNotFoundError when file obviously exists
I am trying to run a Django server in a dev environment (on Debian). I don't want to store my Django SECRET_KEY in the settings file itself, so I have it stored in the /home/admin/keys directory (the server is being run from the admin user). In my settings.py, I have added the following: _secret_key_path = '/home/admin/keys/django-secret-key.txt' with open(_secret_key_path, 'r') as f: _secret_key = f.read() SECRET_KEY = _secret_key When I try running the Django interactive shell (python manage.py shell), I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/admin/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/admin/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/admin/.local/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/admin/repos/server/app/settings.py", line 37, in <module> with … -
Django filter queryset __in=list for *every* item in queryset
Let's say I have the following models class Offer(models.Model): skills_required = models.ManyToManyField(Skill, blank=True) class Skill(models.Model) title = models.CharField(max_length=80, primary_key=True) class UserProfile(models.Model): skills = models.ManyToManyField(Skill) How can I filter Offer.objects with an instance of UserProfile in a way that skills_required of remaining offers would be a subset of user_profile.skills? -
How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked
I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit. This is my JS: function checkBoxes() { $(' input[type=checkbox]'). attr('disabled', true); $(document).on('click', 'input[type=checkbox]', function (event) { if ($(this).is(":checked")) { console.log("1") } else { console.log('2') } }); } The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django: <div style="height:30px"></div> <form method="post"> {% csrf_token %} {{ context.form.as_p }} <button type="submit">Submit</button> </form> How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again? -
how to copy variable to [clipboard] in django template
How do I copy a variable from inside the html page of Django templates? render(request, 'doc.html', {'stack': stack, 'text':text,}) -
how to get input from html form to python code
I have created a python code and an html form with text boxes and button. what I want is to pass the text box value into my python code I m using django, and I've tried whit cgi but nothing has given me the output that I'm looking for. besides I get in the browsers just the python code when I click on the button. so if anyone has an idea how this could be done please help -
How can I set default_currency= "INR" in settings.py file because its use many times in project?
I want to save MoneyField details in setting.py file so I can use it every places where I use MoneyField I want to save this.. MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=False, default=0.0) How can save it in settings.py -
Using django-elasticsearch-dsl-drf, how to implement autocomplete and term matching
I'm very new to elasticsearch, so some terminology may be wrong. I want to implement autocomplete as well as term matching. Say I have a document with the name "Foo Bar." If I query "fo," it works. However, I also want to be able to find this document by querying "bar" This is my document: @registry.register_document class ReviewableDocument(Document): id = fields.TextField() name = fields.TextField( fields={ "raw": fields.TextField(analyzer=html_strip), "suggest": fields.CompletionField(), } ) class Index: name = "reviewables" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Django: model = Reviewable fields = [ "url_name", "profile_picture", ] This is my serializer: class ReviewableAutocompleteSerializer(DocumentSerializer): class Meta(object): fields = ("id", "name", "url_name") document = ReviewableDocument And this is my view: class SuggestReviewableByName(DocumentViewSet): serializer_class = ReviewableAutocompleteSerializer permission_classes = (AllowAny,) document = ReviewableDocument filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { "name_suggest": {"field": "name.suggest", "suggesters": [SUGGESTER_COMPLETION]} } -
Value type dependant on column describing the type
I'm creating a tool where all you would need to add a new field in a website you would only need to add data describing the field in the database and css style (for minimal front-end developer and zero backend developer effort). In turn I need a database with a column storing dynamic value type. Example: | Type | Value | -------------------------------- | string | "abc": string | | number | 51: number | | Date | 2020-10-10: Date | How and with what database can this be achieved? Or is there an alternative way to achieve this goal? -
Django Wsgi ModuleNotFoundError: No module named 'project_name'
I am trying to deploy a Django project using WSGI and NGINX. The problem is that at startup, the logs show a module missing error When launched via the service uwsgi restart command, an error appears in the logs /var/log/uwsgi/app/django.log: Wed Aug 18 17:25:21 2021 - Python version: 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC 9.4.0] Wed Aug 18 17:25:21 2021 - *** Python threads support is disabled. You can enable it with --enable-threads *** Wed Aug 18 17:25:21 2021 - Python main interpreter initialized at 0x55f90e1e7700 Wed Aug 18 17:25:21 2021 - your server socket listen backlog is limited to 100 connections Wed Aug 18 17:25:21 2021 - your mercy for graceful operations on workers is 60 seconds Wed Aug 18 17:25:21 2021 - mapped 145840 bytes (142 KB) for 1 cores Wed Aug 18 17:25:21 2021 - *** Operational MODE: single process *** Traceback (most recent call last): File "project_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.8/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File … -
How to send a response from Django view function to a HTML popup windows
So, my app works like this: 1- user clicks and a function will call a ajax jquery send some data to a function in views.py, Done! 2- some process will be made in the function. some data are ready. Done! 3- I want to show the data on a html format like a popup window. I am new in this and I have not find any straight forward instruction. You can find my step 1 in How to send a simple data by Ajax jQuery to views.py in Django? Thanks in advance -
API interface in django
I am working in a project on connected objects. My job is to retrieve the data from the devices at the broker level by providing an HTTP push interface. I was therefore asked to set up an API interface. I am developing with django and I want to write an API with django restframework. I would like to know if a REST API could serve as an interface in this case. -
Is it possible to join 2 django models with no references?
I want to make a join with 2 django models with no relationship, so there are no foregn keys. class Person(models.Model): id = models.IntegerField() name = models.CharField() class Pilot(models.Model): id = models.IntegerField() vehicle = models.CharField() How do I join Pilot and Person by "id"? -
Handling Of Database (sqlite) for Django on Heroku
[Error Log][1] I had run "heroku run python manage.py migrate" yet the migrate aren't working. [1]: https://i.stack.imgur.com/QKtZr.png