Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
accessing button toggle values in django views
I am working on a django web application. In this application, I have a form with a few buttons. these buttons act like tags that a user can press. When the user submits the form I want to access the value of the buttons the user clicked in my views. How do I do that? I designed the form with Bootstrap. this is the code to the HTML form. <form> {% csrf_token %} ... <p class='details-scrape'>Select the items you want to add to the list</p> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Tomato </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Eggs </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Bread </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Beans </button> <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Cheese </button> <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button> </form> Here is my views.py code def index(request): if request.method == 'POST': # ------------- New code will come here ----------------- #access the values of the clicked buttons here... return render(request, 'index.html') else: return render(request, 'index.html') -
How can i perform the right reverse query in ManytoMany in Django
I'm trying to perform a reversed query for a manytomany fields in Django, but it keeps gives me nothing, here is my code models.py class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=120) image = models.ImageField(upload_to='products') branch = models.ManyToManyField(Branch, related_name='branches') class Branch(models.Model): area = models.ForeignKey(Area, on_delete=CASCADE) name = models.CharField(max_length=1200) phone = models.CharField(max_length=30, null=True, blank=True) address = models.CharField(max_length=1200, null=True, blank=True) tax_value = models.DecimalField(decimal_places=2, max_digits=4) views.py for branch in product_object.branches.all(): print(branch) The branch is always nothing !! -
Why django admin page refuse to connect?
Whenever I run the command python manage.py runserver, the server gets starts without any error , but whenever i try to visit the admin page http://127.0.0.1:8000/admin/ , it keeps showing the error that: 127.0.0.1 refused to connect Image: enter image description here -
Django Thumbnail
I'm making a web app for photo resizing via the api. And the photos change in size, but only decrease, if I try to put a size larger than the current one, nothing happens. Perhaps this is a feature of thumbnail models.py: class Content(models.Model): width = models.IntegerField() heigth = models.IntegerField() image = models.ImageField(blank=True) def save(self): img = Image.open(self.image.path) output_size = (self.width, self.heigth) img.thumbnail(output_size) img.save(self.image.path) serializer.py: class ContentSerializer(serializers.Serializer): width = serializers.IntegerField() heigth = serializers.IntegerField() def create(self, validated_data): return Content.objects.create(**validated_data) def update(self, instance, validated_data): instance.width = validated_data.get('width', instance.width) instance.heigth = validated_data.get( 'heigth', instance.heigth) instance.save() return instance views.ContentView.put: def put(self, request, pk): saved_content = get_object_or_404(Content.objects.all(), pk=pk) data = request.data.get('content') serializer = ContentSerializer( instance=saved_content, data=data, partial=True) if serializer.is_valid(raise_exception=True): content_saved = serializer.save() return Response({ "success": "Picture '{}' updated successfully".format(content_saved.id) }) template: {% for picture in pictures %} {% with picture.image as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endwith %} {% endfor %} -
Which parameters from Request-Object are needed for instantiating a HyperlinkedModelSerializer in Django?
I can't pass the whole request-Object to the method where the serializer is instantiated, I can only pass dictionarys, so I want to extract the parameters I really need, but I can't figure out which they are. From django docs: When instantiating a HyperlinkedModelSerializer you must include the current request in the serializer context, for example: serializer = AccountSerializer(queryset, context={'request': request}) Doing so will ensure that the hyperlinks can include an appropriate hostname, so that the resulting representation uses fully qualified URLs, such as: http://api.example.com/accounts/1/ -
Django server not working with AzureLogHandler (opencensus)
I'm trying to connect my django project logs to Azure Application Insights using OpenCensus. The middleware for montirong requests works well but I also want to send telemetry logs (not just requests) to Azure. Here is my django LOGGING configuration : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname).3s %(process)d %(name)s : %(message)s', }, 'simple': { 'format': '%(asctime)s %(levelname)-7s : %(message)s', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'azure': { 'formatter': 'simple', 'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler', 'connection_string': 'InstrumentationKey=XXXX-XXXX-XXXX-XXXX' }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { '': { 'level': os.environ.get('LOGLEVEL', 'INFO'), 'handlers': ['console', 'azure'], }, 'devdebug': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'django': { 'handlers': ['console', 'mail_admins'], 'level': os.environ.get('LOGLEVEL', 'INFO'), 'propagate': False, } }, } Without 'azure' handler in my root logger config, everything works fine. With 'azure' handler, the server starts but doesn't work : I am unable to connect to it. I really don't know what is happening as it doesn't show me unusual logs (even with LOGLEVEL=DEBUG). My handler configuration should be good as I can receive logs in Azure (when I run any … -
how can I fix the application an error in the Heroku cloud?
I uploaded my website project on Heroku cloud a while ago and I needed to edit some stuff with the project and when I reupload the website again in the same app directory I get the message from Heroku that says Application error then I tried to create a new app directory in Heroku by command: create heroku appname and when I upload my project doesn't work again with the different directory on Heroku so what is the step I missed here? I followed up this lesson https://www.youtube.com/watch?v=MoX36izzEWY&t=1707s step by step and I don't know what the step I missed or what is may the new in Heroku didn't exist in this tutorial? - I did create a virtual environment - I did create all files that Heroku needs like: ProcFile pipfile requirements.txt and I installed everything as the tutorial said exactly: (gunicorn, django-heroku, whitenoise and so else) last note: I'm on Linux Ubuntu -
Django channels socket not connecting to consumer
I'm new to socket programming & I'm kindof stuck with an issue here. My client is not connecting to consumer. My Consumer class TestConsumer(WebsocketConsumer): def websocket_connect(self): print("connected") self.accept() async_to_sync(self.channel_layer.group_add)('app', self.channel_name) print(self.scope['user']) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)('app', self.channel_name) JavaScript Code <script> // websocket scripts console.log(window.location) var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname + '/' console.log(endpoint) var socket = new WebSocket("ws://127.0.0.1:8000/test-view/") socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("open", e) } socket.onerror = function(e){ console.log("error", e) } socket.onclose = function(e){ console.log("close", e) } </script> Routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( [ url(r'^ws/test-view', consumers.TestConsumer), ] ) ), }) Settings ASGI_APPLICATION = 'apps.sockets.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Redis is running The error WebSocket connection to 'ws://127.0.0.1:8000/test-view/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET Hint: It's not even hitting the consumer, when I first start the server it hits the consumer. But when I load the page it never hits the consumer and crashes on var socket = new WebSocket("ws://127.0.0.1:8000/test-view/"). That's all I can deduce so far, all the … -
Celery not executing my task after recieving?
Here I am crawling some websites with different keywords. Before It was only scraping and it worked but I implemented celery for this. After using celery I am not being able to get the scraping result but no error is showing. I am using rabbitmq as the message broker here. tasks.py @shared_task() def schedule_task(pk): task = Task.objects.get(pk=pk) keywords = '' # for keys in ast.literal_eval(obj.keywords.all()): #keywords change to csv for keys in task.keywords.all(): if keywords: keywords += ', ' + keys.title else: keywords += keys.title task_ids = [] # one Task/Project contains one or multiple scrapy task settings = { 'spider_count': len(task.targets.all()), 'keywords': keywords, 'unique_id': str(uuid4()), # unique ID for each record for DB 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } # res = ast.literal_eval(ini_list) for site_url in task.targets.all(): domain = urlparse(site_url.address).netloc # parse the url and extract the domain spider_name = domain.replace('.com', '') task = scrapyd.schedule('default', spider_name, settings=settings, url=site_url.address, domain=domain, keywords=keywords) views def post(self, request, *args, **kwargs): form = CreateTaskForm(request.POST) if form.is_valid(): unique_id = str(uuid4()) # create a unique ID. obj = form.save(commit=False) obj.created_by = request.user obj.unique_id = unique_id obj.status = 0 obj.save() form.save_m2m() print(obj.pk) schedule_task.delay(pk=obj.pk) return redirect('crawler:task-list') views before using celery ( which returns the scrapped results worked fine) … -
Cannot migrate Django from 1.7 to 1.8
When upgrading django 1.7 to 1.8 (final goal is actually migrating 1.4 to 1.11LTS) I am asked to remove SOUTH form my INSTALLED_APPS Fine, but then I get: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. So I tried to add in settings file: import django django.setup() but it bring this error at runtime, that make me think it is not the good way: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed my INSTALLED_APPS: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'mptt', # 'south', 'main', 'proxy', 'picocms', 'django.contrib.admin', 'reports', 'django_orphaned' Note that if I comment 'main' (my main code folder) and 'picocms' (an outdated lib), the AppRegistryNotReady exception is not raised anymore(but obviously the project cannot work without it) Does someone successfully went through the same kind of issue? -
how to do ajax pagination in Django?
!! I have a model named MediaPageCampaignContent !! class MediaPageCampaignContent(models.Model): image = models.ImageField(upload_to='Media/awards') title = models.CharField(max_length=255,blank=True) content = models.TextField(blank=True) and in the frontend I have <div class="col-md-6" id= "mydiv"> <div> <!-- pagination design start --> <div class="blog_bottom_pagination"> <div class="counter"></div> <button class="paginate left"><i class="fas fa-angle-left"></i></button> <button class="paginate right"> <i class="fas fa-angle-right"></i> </button> </div> <!-- pagination design end --> I don't find any reference how i implement pagination without page refresh and render two data at a time in that div section. and paginate right and left by the button for getting next two data and will replace those previous data in that div.... thank you in advance -
Azure service bus messages intermittently unauthorized despite using correct shared access signature values...why?
I have a django application that routinely injects messages into an Azure service bus. I am receiving intermittent errors indicating that its messages are unauthorized. I would say that 95% of messages are successfully authorized, with about 5% unauthorized). I have not changed anything in months related to access (shared access signatures, access keys etc) to the service bus, and I have validated that my python code is still using all the correct values (service bus namespace, topic, access key, etc). Despite this, I am receiving intermittent errors related to having an invalid authorization token signature: "AzureHttpError('SubCode=40103: Invalid authorization token signature',)` How can I correct this, and how can I find out the cause? -
Limiting ForeignKey fields in admin when editing section/site Django
how to limit the number of foreign key fields in Django next time editing? example : I've a model Project and Images, Images has many to one relation to Project. Project includes title, slug, description, etc. models.py class Images(models.Model): image = ImageField(upload_to='project/') multi_image = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='other_images') admin.py class ImagesInline(AdminImageMixin, admin.TabularInline): model = Images extra = 3 I can register this class using inline. before saving after saving and visiting again for editing I want to remove those extra empty image fields when I go for editing, I mean I don't want to show them anymore. Is it possible? -
Ngnix Django 502 Bad Gateway
I deployed a django app using CI/CD from gitlab. The app is wrapped in a docker container and uses Nginx server. The deployment is successful from git but I get the error when I visit the IP. 502 Bad Gateway nginx/1.17.4 I checked the log of the app's container and it outputs no destination no destination no destination no destination no destination no destination no destination Also, that of the Nginx container outputs 2020/06/06 16:49:29 [error] 6#6: *754 connect() failed (111: Connection refused) while connecting to upstream, client: 196.251.20.105, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://172.18.0.3:8000/favicon.ico", host: "18.189.11.120", referrer: "http://18.189.11.120/" 196.251.20.105 - - [06/Jun/2020:16:49:29 +0000] "GET /favicon.ico HTTP/1.1" 502 559 "http://18.189.11.120/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36" "-" For some additional context, I will post the content of some of my files Dockerfile FROM python:3.6-slim # create the appropriate directories ENV APP_HOME=/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME ENV PYTHONUNBUFFERED=1 # Add unstable repo to allow us to access latest GDAL builds # Existing binutils causes a dependency conflict, correct version will be installed when GDAL gets intalled RUN echo deb http://deb.debian.org/debian testing main contrib non-free >> … -
How do Iogin User with OAuth credentials after logout?
I have successfully obtained received an OAuth token, saved it the the DB as a new user, and logged the user in. If the user logs out either manually, through cookie purge, or some other method, do they just perform the same process again? This is problematic because my server will create a new account for them in this case as if it was their first time. Is there a different process to log them back in a second time without having to authorize through the same channel? I cannot get the user's refresh token/scopes because they are now anonymous after being logged out. -
Keep alive connection between two "request/response" services
we have a Django app running on servers in Central europe, a service provider who has servers in US and proxy servers with a simple Flask app in US. The Flask app takes requests from the provider and forwards them to our main Django app. We can't run the Django app in the US. Currently we run into a problem that the request (with response) pretty often takes a little bit longer than it can take - it has to be under 3 seconds - partially because of the heavy load on our main Django app, so we want to optimize the flow. Right now the communication between the Flask and Django app is a simple Requests.post for each request from the provider which opens a new TCP connection. This can be a little bit time consuming between US and Europe (because of the handshake). What I was thinking is to create some sort of a "permanent" connection between the two apps, which would not require the handshake for each request and thus saving us a little bit of time. The naive solution is to create a HTTP server on the Django side and some service (with multiple workers) on … -
How to change the URL redirection of method_decorator(login_required)
i added method decorator in my project for redirect user if they are not connected, the problem is the redirect go to " /accounts/login/?next=/organisation/collaborator/ " instead of " /userprofile/login/?next=/organisation/collaborator/ . Can i change that ? from django.conf import settings . . . from django.utils.decorators import method_decorator @method_decorator(login_required, name='dispatch') class CollaboratorView(View): template = 'team/collaborator.html' context = { 'title': 'Planificator', 'title_page': "Teams", 'description_page': "Collaborator profil", } def get(self, request, collaborator_id=None): context = self.basecontext() if collaborator_id is not None: context.update({ 'collaborator_choosen': collaborator_id, }) return render( request, self.template, context=context ) -
python video editor library receive file object instead of file path
i am working in django project and i want to make thumbnail from video file saved into defult_storage and i need python video editor library to receive file object instead of file path i check moviepy and opencv but couldn't fine solution i will be so thankful if someone can help me about this case this is model: class BusinessVideo(ModificationLogMixin, models.Model): video = models.FileField(upload_to='business_videos', null=True, blank=True) and this is way i want to pass video to editor video_cap = cv.VideoCapture(default_storage.open( os.path.relpath(self.video_url, settings.MEDIA_URL))) i need some library to recive file object because my default_storage is based on minio and i don't know how to get video path -
Hww to implement a follow sistem on django project
I am working on a django project and will like to impletment a following/follower sistem in it, currently I have a friend sistem which btw doesnt work at all but I will just like to have ideas of how I can write that code, the idea is to have a friend sistem like in instagram. -
Which email sending 3rd party application should be used with my django based accountting application
As the title suggested. we are making a django based application where will require to send emails on regular bases which one offer the best -
Django manage.py switching library locations
I'm not sure what I'm doing wrong here. I've tried removing the pyenv initialization from my rc file, taking pyenv out of PATH, manually adding the library location to the sys.path, recreating the virtualenv. I keep getting this error. Traceback (most recent call last): File "/home/ross/.pyenv/versions/3.8.3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/ross/.pyenv/versions/3.8.3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ross/PycharmProjects/reporting3/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/ross/.pyenv/versions/3.8.3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'boostrap4' -
How to pass data from an input form to django url
Hi I am trying to create a search function to be able to search for users. I have the following input form in my html that ideally should take in the username and if I hit enter on the keyboard it should redirect to the user-feed url. <form class="form-inline"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">@</span> </div> <input id="user_search" type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1" formaction="{% url 'user-feed' %}" formmethod="GET"> </div> </form> The URL is defined as such: path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed') As you can see it takes the username I want to enter on the form as the key. But I dont know how I can pass this to the URL -
What best resources for learning python you now? [closed]
Could you recommend the best resources for learning python you know , and what books and courses -
Using Django with jQuery
Hello someone kindly help me out with the code for changing a given placeholder's values depending on what the user has selected.for example change city values depending on the country selected. Using Django and jQuery ( the code please). Thank you in advance -
How to reference foreignkeys in history_list_display in django-simple-history?
I was able to display columns in history page in admin panel using history_list_display attribute. In those column, I have employee which can be displayed using employee in the history_list_display attribute tuple. But when I try to do ForeignKey reference using employee__person__person_name to other tables, it is displaying None. How can I display ForeignKey reference values in history page in django admin?