Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unslugifying the already slugified text in django without using replace method
from django.utils.text import slugify urlparameter = slugify("This is my First trip") # this-is-my-first-trip now i want it to un-slugify it to previous text ('this is my first trip') but not using replace.("-", " ") Is there any django way to do so ?? -
Catching an exception in Django
I have been building an application using Django and Vuejs. The application using YouTube API to scrap for videos based on a few conditions that are set in the website that I am building. For some conditions I am getting a very weird error which I am not able to catch. What can be done to catch the error? Refer the screenshot: The error occurs at the place where I am printing Error 1. So many different times of errors occur here and I am not able to catch it, so that I can display customized messages based on the error. Area where the error was found -
Calling Hyperledger Fabric peer client and redirecting log in python
I'm creating a Rest API to interact with two systems (one of them is HLF). (peer is a binary of a program written in go that I don't want to change) I'm trying to use Django (Python) and Python Subprecess to call "./peer chaincode invoke...", but when I try to read the output, it returns an empty list. I would like to redirect the text from the console (log info) to the standard output. def read: os.chdir(str(Path.home()) + "/HLF/fabric/bin") os.environ['FABRIC_CFG_PATH'] = "../config/" cafile = "../../organizations/ordererOrganizations/omega.olympus.pt/msp/tlscacerts/ca-omega-olympus-pt-7054.pem" channel = "main-channel" label = "occv1" orderer = "cronus.omega.olympus.pt:7050" function='{"Args":["ReadAsset","00000"]}' command = ['./peer', 'chaincode', 'invoke', '-o', orderer, '--tls', '--cafile', cafile, '-C', channel, "-n", label, '-c', function] proc = subprocess.Popen(command, stdout=subprocess.PIPE) print("output", proc.stdout.readlines()) Output: 2022-06-14 12:11:13.254 UTC 0001 INFO [chaincodeCmd] chaincodeInvokeOrQuery -> Chaincode invoke successful. result: status:200 payload:"{\"ID\":\"00000\",\"ClientID\":\"00000\",\"consents\":\"\",\"timestamp\":\"2022-06-05 13:56:18\",\"cid\":\"12345\",\"hash\":\"--------------------------------------------\"}" output [] -
How to perform function from user uploaded image without saving it in database Django?
recently I'm trying to create a steganography tool in django, but I'm having some problems with how to perform function from a user uploaded image without saving the image in database. views.py def steganography(request): if request.method == 'POST': #Encryption if 'steg_en' in request.POST: cover_image = request.FILES['cover_image'] secret_message = request.POST['secret_message'] #perform steganography encryption function context_sten = { #return encrypted image } return render(request, 'steganography.html', context_sten) #Decryption elif 'steg_de' in request.POST: encrypted_image = request.FILES['encrypted_image'] #perform steganography decryption function context_stde = { #return decrypted text } return render(request, 'steganography.html', context_stde) else: return render(request, 'steganography.html') After performing the steganography functions whether encryption or decryption, it will return the output back to steganography.html steganography.html <!-- Encryption Input --> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="cover_image">Upload your cover image</label> <input type="file" class="form-control" name="cover_image" required> <label for="secret_message">Enter your secret message</label> <input type="text" class="form-control" name="secret_message" placeholder="Enter your secret message" required> <button type="submit" name="steg_en" class="btn btn-primary">Encrypt</button> </form> <!-- Encryption Output --> <!-- Decryption Input --> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="encrypted_image">Upload your encrypted image</label> <input type="file" class="form-control" name="encrypted_image" required> <button type="submit" name="steg_de" class="btn btn-primary">Decrypt</button> </form> <!-- Decryption Output --> {{ decrypted_text }} stego.py This is the code of steganography I refer. Refer link: https://dev.to/erikwhiting88/let-s-hide-a-secret-message-in-an-image-with-python-and-opencv-1jf5 -
JS script runs partially on heroku but fully locally (Django)
document.addEventListener('DOMContentLoaded', function() { // get button by id //document.getElementById('closedjs_$').style.display='none'; var trips = document.querySelectorAll('*[id^="closedjs"]'); // trips = document.querySelectorAll('.closedjs') trips.forEach((element) =>{element.style.display='none';}) // checking if current passengers >= max passengers so changing Join btn to Closed /* document.querySelectorAll('.joinleave').forEach((element) => { var route_id = element.dataset.id; var no_pass= parseFloat(document.querySelector(`#thepassengercounter_${route_id}`).innerHTML); var max_pass = parseFloat(document.querySelector(`#max_pass_${route_id}`).innerHTML); if (no_pass == max_pass){ if (element.innerHTML="Join"){ element.style.color = "#B22222"; element.style.border = "1px solid #B22222"; element.title="Closed"; element.innerHTML="Closed"; } else{ element.title="Leave"; element.innerHTML="Leave"; } } } )*/ // so as to not reload the page after joining or leaving a trip. It updates the innerHTML instantly //and then fetches as POST the route_id json page so as to update the DB document.querySelectorAll('.joinleave').forEach((element) => { element.onclick = () => { var route_id = element.dataset.id; fetch(`/route/${route_id}`) .then(response => response.json()) .then(route => { if (route.error) { console.log(route.error); alert(route.error) } var no_pass= parseFloat(document.querySelector(`#thepassengercounter_${route_id}`).innerHTML); var max_pass = route["no_pass"]; var dist = route["dist"]; var key_num = route["key_num"]; var co2=dist*2.40*2; var fin = document.querySelector(`#fin_${route_id}`).innerHTML; var diff_p = max_pass-no_pass //console.log(route_id); console.log('max passengers ', max_pass); console.log('current passengers ', no_pass); console.log('is date or time passed? ', fin); console.log('diff pass ', diff_p); alert('presssed') //CODE EXECUTES UP TO HERE THE ALERT 'PRESSED' IS DISLAYED// //console.log(dist) //console.log(key_num) // checking if current passengers >= max passengers so not allowing … -
How to assign model form field to a current logged in user in Django's class based views
I am trying to save a form with the current logged in user's username, but the error "Cannot assign "'Neshno_Games2'": "League.host" must be a "Manager" instance." occurs Views.py class CreateLeaguesView(generic.CreateView): model = League template_name = "leagues/create-league.html" form_class = LeaguesCreationForm success_url = "/leagues/leagues" def get_context_data(self, **kwargs): context = super().get_context_data( **kwargs) context['leagues'] = League.objects.all() return context def form_valid(self, form): manager = self.request.user.username League.objects.create( host = manager, ) return super(CreateLeaguesView, self).form_valid(form) Model.py class League(models.Model): name = models.CharField(max_length=30) no_players = models.IntegerField(default=20) start_date = models.DateField(blank=False, null=False) end_date = models.DateField(blank=False, null=False) prize = models.CharField(max_length=300) host = models.ForeignKey(Manager, on_delete=models.CASCADE) def __str__(self): return self.name forms.py class LeaguesCreationForm(forms.ModelForm): class Meta: model = League fields = ( "name", "no_players", "start_date", "end_date", "prize", ) -
login user and authenticate that but on mixin other app cant get user login
Please help me for problem I develop website via django-rest-framework and reactjs On backend code below code on app api import json from django.contrib.auth import authenticate, login, logout from django.http import JsonResponse from django.middleware.csrf import get_token from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_POST def login_view(request): data = json.loads(request.body) username = data.get('username') password = data.get('password') if username is None or password is None: return JsonResponse({'detail': 'Please provide username and password.'}, status=400) user = authenticate(username=username, password=password) if user is None: return JsonResponse({'detail': 'Invalid credentials.'}, status=400) login(request, user) return JsonResponse({'detail': 'Successfully logged in.'}) below code on other app and i want get user login mixin but on mixin return AnonymousUser class driverapi(storekeeperMixin,viewsets.ViewSet): def get(self,request,format=None): driverslist = driver.object.all() serilizer = OBJdriver(driverslist, many=True) return Response(serilizer.data) class storekeeperMixin(): def dispatch(self,request,*args,**kwargs): print('****************************' + str(request.user.username)) -
Docker with package files included
I have a legacy project with Django 1.5 and Python 2.7. I would like to create a docker container and copy my local virtualenv files into it as some packages are not available anymore. Is it possible? -
Connecting Neo4J Database to my Django App
I am currently working on a project in which i need to use Django together with a Neo4J graph database. According to the articles i read online i have to use the django_neomodel library to do that. But when i try to install django_neomodel through pipenv or pip i get the following error: The above errors says a certain geos_c.dll file of the shapely==1.7.1 library was not found. I don't really know how to start solving this issue. Thanks in advance. NB: I also get the same error when trying to install just the neomodel library. I'm using python 3.10.4 for this project -
Update_or_create method with unique field in Django
I would like to update or create data in my database by importing a CSV file. I tested and when I import the CSV file when the "plants" have not already been created it works but when there are the same name of the plants in my database I have an integrity error: IntegrityError : duplicate key value violates unique constraint "perma_plants_plant_name_key" DETAIL: Key (name)=(Test bis) already exists. So my update_or_create method does not work because in my model the name field must be unique. How can I do to solve this problem? Here is my model : class Plant(models.Model): name = models.CharField(max_length=150, unique=True) def __str__(self): return self.name Here is my view : class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): Plant.objects.update_or_create( name=row['Name'], ) return Response({"status": "Success : plants created"}, status.HTTP_201_CREATED) Thank you for your answers -
django-import-export: Line number: 1 - get() returned more than one Block -- it returned 2
I am importing data to a model/table with foreign key. It upload some rows but exclude others by throwing the error as: Line number: 1 - get() returned more than one Block -- it returned 2! , HARYANA, 11, FATEHABAD, 195, FATEHABAD, 641, AHLISADAR, 57891 Traceback (most recent call last): File "/home/webtesting/django_venv/lib/python3.9/site-packages/import_export/resources.py", line 660, in import_row self.before_import_row(row, **kwargs) File "/home/webtesting/Excel/DAMU_Excel_Upload_AMFU_DAMU/damuwhatsapp/resources.py", line 89, in before_import_row (cat, _created) = Block.objects.get_or_create(block_name=block_name) File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/query.py", line 657, in get_or_create return self.get(**kwargs), False File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/query.py", line 499, in get raise self.model.MultipleObjectsReturned( damuwhatsapp.models.Block.MultipleObjectsReturned: get() returned more than one Block -- it returned 2! the successful imports were as: But it throws errors for other rows having a similar data structure The data in CSV is as: The models.py file is as: #################################################################################### class Village(models.Model): state_name = models.CharField(max_length=50) state_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) district_name = models.CharField(max_length=50) district_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) block_name = models.ForeignKey(Block, on_delete=models.CASCADE) block_id = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(8000)]) village_name = models.CharField(max_length=50) village_id = models.PositiveIntegerField(unique=True, validators=[MinValueValidator(1), MaxValueValidator(750000)]) class Meta: db_table = 'Village_Names' def __str__(self): return self.village_name The resource.py file is as: where I have excluded the id column, as it is blank and block_name is the foreign key from some … -
Calling ebay trading api from within Django class based view does not work, but works in console
I am currently working on a listing module for ebay. The ebay trading API is done and works fine when I test run it in the console. However when I try to call the same function within a class based view, I get an 500 server error. This is the class: class ListSimpleProduct(generics.GenericAPIView, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): queryset = SimpleProduct.objects.all() serializer_class = SimpleProductSerializer def post(self, request, pk): product = SimpleProduct.objects.get(sku=pk) serializer = SimpleProductSerializer(product, many=False) data = serializer.data item = buildItem(data) addItemCheck(item) return Response({ 'data': "Item listed on ebay" }) And this is the addItemCheck function in the ebay API: def addItemCheck(item): (opts, args) = init_options() try: print("Line 100") api = Trading(debug=opts.debug, config_file=opts.yaml, appid=opts.appid, domain=opts.domain, certid=opts.certid, devid=opts.devid, warnings=True, timeout=20, siteid=opts.siteid) print("Line 103") response = api.execute('VerifyAddItem', item) print("Line 105") info = response.dict() print("Line 107") return info except ConnectionError as e: print(e) print(e.response.dict()) It works until line 100, so the function gets called. The mistake must be in api variable. The data I give to the function is the exact same I put in from the console. -
How can I load specific number of items in Django and then load more items after scrolling?
I added some products with using this function in my views: def All( request ): p=product.objects.all() return render(request,'home.html',{'p':p}) And my template looks like this: <div class="grid"> {%for p in p%} <div class='card'> <img src="{{p.image}}"></img> <p id="id">{{p.description}}</p> <a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'> <button ><span class="price"> ${{p.price}}</span> buy</button> </a> </div> {%endfor%} But I do not know what should I do to be able to limit the products, for example I want to have 10 products after the page is loaded and then after scrolling I want 10 more products to appear. How can I do that? -
Data in form not showing in dropdown Django
so I have this system that I am currently building currently I have implemented this form where the admin can select from a dropdown list of students and add those said students to a classroom but for some reason, the students aren't being shown in the dropdown list when I add a student through the form I created for the user but when I use Django admin I am able to get the students to show up in the class I select so I am really confused as to what the problem is and need some help implementing or altering to make it work. Overall my goal is to get the students to show up in the dropdown list to select and add to the class and know how to correctly add my students to my class as that is giving me issue views # check to see if students already exist in class and display those who aint to be added @login_required def manage_class_student(request, classPK=None): if classPK is None: messages.warning(request, 'Class ID is Unknown') else: context = {} context['classPK'] = classPK _class = Room.objects.get(id=classPK) # print(ClassStudent.objects.filter(classIns = _class)) students = Student.objects.exclude(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student').distinct()).all() context['students'] = students html_form = render_to_string('school/manage_class_student.html', context=context, request=request) … -
How do i pass django-rest-framewor backend session details to react front end?
I am trying to make a music controller room with django backend and react frontend. These are running on two different localhost servers, 3000 and 8000. I am using django session's session_key attribute to be able to identify who the host(the person who created the room) is. If the user using the app in the frontend creates a room and comes back to create another room before the session expires, the user should be taken to the room they have created instead of having the backend create another room. My problem is that each time I hit the create room button on the frontend seconds after creating another room(obviously the session hasn't expired so I expect to be taken to the previous room), the fetch method returns a new room. Here is a view in my views.py that handles this POST request: class CreateRoomview(APIView): # declaring the class we are going to serialize our data with. serializer_class = CreateRoomSerializer # manually defining the method we will use to handle post data from our frontend def post(self, request, format=None): ''' a check to see if in any of our rooms we have a room that that has a host with the … -
How to create a class just after starting Django server and access its members later in views.py
I encountered a simple issue in django, there were similar questions on this forum but haven't answered correctly so i'm writing it again. My issue is just same as this question. https://stackoverflow.com/q/66675546 I have to instantiate custom class when server is starts, and should integrate in the view by accessing methods of instantiated custom class. Let's say we made this class and instantiated when server starts and stored to variables that can be used in later like in urls.py or somewhere. (I don't know how) class MyClass: def __init__(self): self.a=3 def foo(self): return self.a ... #When django server starts new=MyClass() In the view.py, let's say that there is some magic that passes instantiated instance as a parameter in view's method. def index(request, instantiatedClass :MyClass): a=instantiatedClass.foo() return HttpResponse(f"{a} is your var.") This is What i want. but i investigated and in the urls.py there is no options that can passes custom parameters to pointed view.py's method other than passing url informations by the user. I believe that django's model behave and instantiated not same way like ordinary class. So how can i achieve this? Thanks for reading. -
How to upload a file in File Filed of Django automatically in backend without manual selection in front-end
My models.py from django.db import models # Create your models here. class Result(models.Model): Id = models.AutoField(primary_key=True, blank=False) Name = models.CharField(max_length=100) # Date = models.DateTimeField(auto_now=False, auto_now_add=False) # Comments = models.TextField(max_length=256) File = models.FileField(blank=False) My views.py from django.shortcuts import render from contextmapping.Connection import Connection from rest_framework.response import Response from rest_framework.decorators import action from django.shortcuts import render from rest_framework import viewsets,status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from result.models import Result class ResultViewSet(viewsets.ModelViewSet): queryset = Result.objects.all() serializer_class = Result authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) @action(detail=True,methods=['GET']) def resultfill(self,request,pk=None): response={'message':'its working'} return Response(response,status=status.HTTP_200_OK) I have a file named data1.py in a folder, I want to run resultfill function in views.py by url, and want to give a path to this file and that file should be automatically upload to File in models.py . How to achieve it ? -
Get output of jquery code in django views
I want to get the output of the jquery function which appends the selected rows ID into views.py I am using the code from this link: https://jsfiddle.net/snqw56dw/3182/ Need your help to get the selected data into views.py file. $('#frm-example').on('submit', function(e){ var form = this; var rows_selected = table.column(0).checkboxes.selected(); // Iterate over all selected checkboxes $.each(rows_selected, function(index, rowId){ // Create a hidden element $(form).append( $('<input>') .attr('type', 'hidden') .attr('name', 'id[]') .val(rowId) ); }); -
ImportError: cannot import name function from module
I am very new to Django and React. Using WSL2 and VSCode, I was trying to link my React frontend to the Django backend, and I'm getting the following error: ImportError: cannot import name 'index' from 'FastTravelDjango.views' (/root/dev/fast-travel/FastTravelDjango/views.py) FastTravelDjango was created by using "django-admin startproject FastTravelDjango" FastTravelDjango/urls.py from django.contrib import admin from django.urls import path, include from .views import index urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('index/', index) ] FastTravelDjango/views.py from django.shortcuts import render def index(request): return render(request, 'index.html') I was previously getting the same error with my api functions saying that it could not import the main function from views.py, but that mysteriously seemed to solve itself after a while without changing anything. api/urls.py from django.urls import path from .views import main urlpatterns = [ path('home', main) ] api/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main(request): return HttpResponse("<h1>Hello</h1>") Here is the console log: (.venv) root@LAPTOP-436E19C3:~/dev/fast-travel# python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/root/dev/fast-travel/.venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File … -
Need ideas or suggestions in creating a Survey App using Django Rest Framework
I got a project requirement for a survey app where an admin will create a survey and share the created survey link through the mail while the survey options should be point-based from 5 to 1. Kindly share with me any code samples or references -
Django form fails to validate
I have this form that I am passing a parameter to disable or enable the fields based on certain user clicking a particular hyper link. URL path("update-request/<str:pk>/", update_request, name="update_request"), path("update-request/<str:pk>/<str:action>", update_request, name="update_request"), views.py def create_new_request(request, action=None): description_form = DescriptionForm(action=action) forms.py class DescriptionForm(forms.ModelForm): prefix = "description" .... def __init__(self, action=None, *args, **kwargs): super(DescriptionForm, self).__init__(*args, **kwargs) print(action) example hyperlink: New Request My problem starts when I want to save the data to the database, I get all fields are displayed as being required even when data is in them. removing the action from DescriptionForm.init stops the problem, how do I circumvent this issue? The reason I needed to add the action in init is because I need to enable of disable fields if a condition is met. def __init__(self, action=None, *args, **kwargs): super(DescriptionForm, self).__init__(*args, **kwargs) if action == "new_request" or "review": for field in self.fields: self.fields[field].disabled=True My errors look like this: title This field is required. category This field is required. job_description This field is required. urgent_request This field is required. detailed_job_description This field is required. -
FORCE_SCRIPT_NAME in Djanog setting keeps adding the prefix to the URL
I have a URL: https://servername/appname/, so I defined in my Django settings.py like FORCE_SCRIPT_NAME='appname/' which does what I want to have the first time, but if redirect, it keeps adding the appname/ to the URL. How can I prevent adding the prefix multiple times to the URL? For example, I am here https://hammbwdsc02/culture-crawler/dashboards/dashboard/, now if I click logout, the URL will be https://hammbwdsc02/culture-crawler/culture-crawler/logout/, which does not exist and I got a 404 error. By the way, it is working on localhost perfectly but the problem ist only on the server. (Linux server, serving with Gunicorn and Nginx -
django in docker compose don't see posgresql
I have a problem with my django + postgresql docker compose. docker-compose.yml: version: '3.8' services: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . command: python MoreEnergy/manage.py runserver 0.0.0.0:8000 volumes: - ./MoreEnergy/:/MoreEnergy/ ports: - 8000:8000 env_file: - ./.env depends_on: - db volumes: postgres_data: Dockerfile: FROM python:3.9-alpine WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies COPY requirements.txt /app/requirements.txt RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # copy project COPY . . db container check: (shell) $ docker compose exec db psql --username=dmitriy --dbname=more_energy_db psql (12.0) Type "help" for help. more_energy_db=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ----------------+---------+----------+------------+------------+--------------------- more_energy_db | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | postgres | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | template0 | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | =c/dmitriy + | | | | | dmitriy=CTc/dmitriy template1 | dmitriy | UTF8 | en_US.utf8 | en_US.utf8 | =c/dmitriy + | | | | | dmitriy=CTc/dmitriy (4 rows) more_energy_db=# error: django.db.utils.OperationalError: could not connect to … -
Django Many to Many arrange sequence of selected item
Hey all have created a model in django and using django admin i want to import values in many to many fields according to their values placed in order the results are displayed IN my case :- max_combo then max_table etc How can a user from front end choose this particular sequence in django admin Click to view image -
"permission matching query does not exist" errors i encounter with django guardian
Am trying to enable my website users block other users they don't want again as friends just like we can on Facebook. I decided to implement it with Django guardian. when a user clicks a button, a view(block_user_view) is called and the profile the user wants to block is added to group which is assigned a custom permission i created(cant_view_profile). But i always get this error "permission matching query doesn't exist". I can assign these permissions from the admin panel but it runs into error when i try it from my views. I don't know of other ways to actualize this functionality with Django. this is my view def block_user_view(request, id): if request.method == "POST": grouped = Group.objects.get(name="blockedusers") friend = Profile.objects.get(id = id) assign_perm("cant_view_profile", grouped, friend) return render(request, "profiles/blockuser.html", {})