Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a good Django Test?
I am currently doing testing on Django API endpoint. My current objective is to ensure that the API endpoint return 200 as status code. But I am not sure whether if i done it in a right way although the tests are successful.Are there any suggestions or improvement for my test case ? tests.py from django.test import TestCase,Client from rest_framework import status from rest_framework.test import APITestCase from .models import * import json client = Client() username = 'jeff' password = 'jeff' class StaffModelTest(APITestCase): def setUp(self): response = client.post('/admin/login/', {'username': username, 'password': password}) self.assertEqual(response.status_code, 302) def get_api(self,url): response = client.get(url) self.assertEqual(response.status_code,200) if response.status_code == 200: return "200 OK" else: return "Error Occurred" def test_login_url(self) : url = '/admin/login/' response = self.client.get(url, format = 'json') assert response.status_code == 200 def test_accounts_api(self): self.get_api('/accounts/api/v1/accounts/staff/') self.get_api('/accounts/api/v1/accounts/staff/1/') def test_accounts_department_api(self): self.get_api('/accounts/api/v1/accounts/department/') self.get_api('/accounts/api/v1/accounts/position/') def test_staff_statistics_api(self): self.get_api('/accounts/api/v1/accounts/staff/statistic/department') self.get_api('/accounts/api/v1/accounts/staff/statistic/religion') def test_staff_id_api(self): self.get_api('/accounts/api/v1/accounts/staff/1/family/') self.get_api('/accounts/api/v1/accounts/staff/1/family/1/') -
How to create non django files in the static files template in a Django Project
I have a folder in my django project called "templates", its linked to my main project which can access the files (HTML...) correctly as I can make it display stuff like "Hello World" but the project considers the files in the folder as django files even though when creating them I typed stuff like "main.css" or "main.html". The issue is it doesnt tell me if I have errors and it doesnt let me autofill so I was wondering if there was a way to fix this. Thx for any answers! Picture of my Project -
Microsoft authentication login
I want to authenticate my Django base website users by Microsoft authentication, I have followed a solution . by following the solution I successfully redirect my user to Microsoft login page but when I enter my credentials I got an error I have also follow the solution provided by Microsoft by adding this ( http://localhost:8000/microsoft_authentication/callback ) URL in my azure application but it does not work for me so can you please tell me that how can I integrate Microsoft authentication with my Django project -
Django average grouped by foreign key
I have this model class Makes(models.Model): student = models.ForeignKey(...) instrument = models.ForeignKey( to='users.Instrument', on_delete=models.CASCADE ) begin_date = models.DateField( null=True, blank=True ) end_date = models.DateField( null=True, blank=True ) And I want to get the average, grouped per instrument, of the timedelta between begin_date and end_date I tried this: from django.db.models import Avg, F, ExpressionWrapper, fields duration = ExpressionWrapper(F('end_date') - F('begin_date'), output_field=fields.DurationField()) instrument_data = ( Makes.objects .exclude(begin_date__isnull=True) .exclude(end_date__isnull=True) .annotate(duration=duration) .aggregate(average=Avg(duration)) # I can't even figure out how to also get the instrument name here ) But that got me the average of all the durations, and not the average duration per instrument. I also tried this: instrument_data = ( Makes.objects .exclude(begin_date__isnull=True .exclude(end_date__isnull=True) .annotate(duration=Avg(duration)) .values('instrument__instrument_name', 'duration') ) But that got me the "Average" of each individual Makes instance so in conclusion, how do I get a result that looks a bit like this <QuerySet[ { 'instrument__instrument_name': 'alt-viool', 'duration': datetime.timedelta(days=142) }, { 'instrument__instrument_name': 'contrabas', 'duration': datetime.timedelta(days=62) }, { 'instrument__instrument_name': 'viool', 'duration': datetime.timedelta(days=49) } ]> -
Django static files not consistent between DEBUG=True and after `collectstatic`
My "Select all {amount} {model}s" action, which should be in the actions bar while viewing a model page in the Django admin, does not work in production. Expected behaviour, as recorded running locally with DEBUG=True in local_settings.py: Behaviour on staging deployment and while running locally with DEBUG=False: I'm having issues with inconsistency between the static files my templates are working with between a local running of the runserver command with DEBUG=True vs. running the same codebase after running collectstatic and then running it with DEBUG=False in my settings. The differences in static files is also apparent in the listed sources when inspecting the page. Working correctly: Not working correctly: Running the collectstatic command gives me this output: Loading .env environment variables... Found another file with the destination path 'admin/js/actions.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin/js/admin/RelatedObjectLookups.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path … -
Django : upload direct folder to input type file instead selecting multiple files
How can we upload direct folder to input type file ? I mean user can upload direct folder of images or files instead of selecting multiple files? -
django Get Group Ids from Whatsapp,
I have problems How to get a name, id from WhatsApp API in Django application? When I click in plus icon want create contact with that id and name . ******urls.py ` path('add_contact/<int:contact_id>' , views.add_contact, name="add_contact"),` 1. List item ******template ` {% for cont in contact %} <td>{{cont.name}}</td> <td>{{cont.id}}</td> <td> <a href="{% url 'add_contact' cont.contact_id %}" class=" btn text-secondary px-0"> {% csrf_token %} </a> <i class="fa fa-plus" aria-hidden="true"></i> </a> </td>` ******views `@login_required def add_contact(request,contact_id): contact = Contact.objects.get(contact_id=contact_id) form = CreateContactForm(request.POST,instance=contact) if form.is_valid(): form.save() return render(request, 'dashboard/contact.html') *************enter image description here -
How to solve "detail": "Authentication credentials were not provided." error for Class-based APIView Django REST Framework?
I am using Django REST Framework and following this tutorial for retrieving all users when admin user is authenticated. Class-based APIView of Django REST Framework I am using Postman to test and trying to retrieve the list of all users registered in the system. At first I try to use my "User Login with Token" API in Postman to create the necessary token as shown below: I copied the value of the "token" key and pasted it as the value of the "Authorization" key in the "Headers" section of "Get All Users" API in Postman as shown below. It is a GET request and I get the error "detail": "Authentication credentials were not provided." as the response. Necessary code snippets are as follows: views.py class UserAccountListView(APIView): """ List of All Users in the System / Application * Requires Token Authentication. * Only Admin Users are able to access this view. """ authentication_classes = (TokenAuthentication, ) permission_classes = (IsAdminUser, ) def get(self, request, format=None): """ Returns a List of All Users """ full_names = [user.full_name for user in UsersAccount.objects.all()] return Response(full_names) settings.py REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ … -
Filter the Modal Data in django staff side
I have a model name Complain in which i have a field station(return police station name) foreign key with station table and user field foreign key relation with user table. Now what i want when i add staff user then it will show only the complain data that have same station name. thanks! -
'set' object is not a mapping (Error trying to add a list of choices.)
Generally, when I remove from the html template {{ createnewauctionhere.category}} this all works, but I would like to display a list from which to select a category anyway. This is part of the CS50 course. Could someone please explain to me what am I doing wrong and where am I making a mistake? models.py class Category(models.Model): choicecategory = ( ('1','Food'), ('2','Toys'), ('3','Fashion'), ('4','Electronics'), ('5','Home') ) category = models.CharField(max_length=300, choices=choicecategory) def __str__(self): return self.category class Auctionmodel(models.Model): title = models.CharField(max_length=300) content = models.TextField() price = models.IntegerField() pic = models.CharField(max_length=300, blank=True) category = models.ManyToManyField(Category, related_name='Category') def __str__(self): return f"Title: {self.title} Content: {self.content} Price: {self.price}" class Addauctionform(ModelForm): class Meta: model = Auctionmodel fields = '__all__' widgets = { "title": TextInput(attrs={'placeholder':"Title Of Auction"}), "content": Textarea(attrs={'placeholder':"Content Of Auction"}), "price": NumberInput(attrs={'placeholder':"Price Of Auction"}), "pic": TextInput(attrs={'placeholder':"Image Of Auction"}), "category": Select(attrs={'placeholder:"Category Of Auction'}) } createnewauction.html <form action="{% url 'createnewauction' %}" method='post'> {% csrf_token %} {{ createnewauctionhere.title}} <br> {{ createnewauctionhere.content}} <br> {{ createnewauctionhere.price}} <br> {{ createnewauctionhere.pic }} <br> {{ createnewauctionhere.category }} <br> <input type="submit" value="Create"> </form> -
What is this 'from asyncio.windows_events import NULL'?
Good Morning and Evening Everyone, This morning in my django app under the views.py I saw the following import line in my code: from asyncio.windows_events import NULL I'm not sure how this got here, but I was wondering how and why was it added to my code. Last thing I remember I did was ran python manage.py migrate . Any ideas??? -
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) …