Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'WindowsPath' object has no attribute 'endswith' when using runmodwsgi Django command
Windows 10, Python 3.8.10, Apache 2.4.51, Django 3.2.8, mod_wsgi 4.9.0 When I try to run the Apache server using python manage.py runmodwsgi, I get this output: Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me Server Conf : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/httpd.conf Error Log File : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 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 "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 134, in handle options = mod_wsgi.server._cmd_setup_server( File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 3613, in _cmd_setup_server generate_apache_config(options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 1086, in generate_apache_config if target.endswith('/') and path != '/': AttributeError: 'WindowsPath' object has … -
Django Rest Framework - Cannot POST because username already exists
I am working on a basic rest api with django rest framework. And my database is on MySQL. For one of the functions, when I try to POST, it gives me an error because there is a row with the same username already. I have set the model to have all three of its fields to be unique_together. Please help me understand where i am going wrong, heres snippets of what i have currently: models.py: class VolunteerHours(models.Model): username = models.OneToOneField(Volunteer, models.DO_NOTHING, db_column='Username', primary_key=True) date = models.DateField(db_column='Date') hours = models.IntegerField(db_column='Hours') class Meta: managed = False db_table = 'volunteer_hours' unique_together = (('username', 'date', 'hours'),) urls.py: urlpatterns = [ path('timesheet/', views.TimesheetAPIView.as_view()),] views.py: from . import models from . import serializers from rest_framework import generics from rest_framework import mixins class TimesheetAPIView(generics.GenericAPIView, mixins.CreateModelMixin): serializer_class = serializers.VolunteerTimesheetSerializer def post(self, request): return self.create(request) serializers.py: class VolunteerTimesheetSerializer(serializers.ModelSerializer): class Meta: model = models.VolunteerHours fields = '__all__' The error im getting is: "username": [ "volunteer hours with this username already exists." ] What I want to happen is i can add as many rows with the same username as long as the date and hours are unique. Which are what is submit in my POST requests, but it says username … -
Django - Pymongo list index out of range error
I want to print the _id part of the results by running a query on the mongo db, but I am getting the "list index out of range" error. view; def deleted(request): q1=('XX') q2=('XX') client = MongoClient("XX") database = client["XX"] collection = database["XX"] query = {} query["Marketplace"] = q1 query["$or"] = [ { "Tuyx": q2 } ] cursor = collection.find(query) print(cursor) sonuc= loads(dumps(cursor)) id=sonuc[0]["_id"] print(id) client.close() return render(request, 'deletedlisting.html', {'id':id} ) ti want to print _id value as string; -
Continue uploading the file after connecting to the Internet
If the internet file is disconnected while uploading, how can I continue to upload the file using Django when it is connected? if request.method == 'POST' and request.is_ajax(): if formset.is_valid(): obj = formset.save(commit=False) obj.experience_id = experience_id obj.save() return JsonResponse({'error': False, 'message': 'video is uploaded.'}) else: return JsonResponse({'error': True, 'errors': formset.errors}) -
How to capture webcam input from ReactJS, stream to Django backend and display it back on the React frontend?
I have built a virtual makeover app using python like this one: https://www.maybelline.com/virtual-try-on-makeup-tools. I want to connect this to my React frontend by capturing the webcam input, send it to the Django backend and return the video stream to the frontend so that the virtual makeover happens in real-time i.e. apply lipstick, foundation, etc. Any ideas are welcome, and please let me know if you need anymore details. Thanks in advance!!! -
How to implement a custom renderer in Django REST framework for PDF and Excel export?
I have implemented two custom renderers in django rest framework which export data in Excel or PDF format. The problem is that I'm unable to set the file names when the response is generated. I have the following renderers: # app/renderers.py import os import openpyxl import pdfkit import random from django.template.loader import render_to_string from rest_framework.renderers import BaseRenderer from rest_framework.response import Response # for newer python, do the configuration for pdfkit config = pdfkit.configuration(wkhtmltopdf=r'path_to_bin/wkhtmltopdf') class XLSXRenderer(BaseRenderer): # ... code truncated class PDFRenderer(BaseRenderer): media_type = 'application/pdf' format = 'pdf' charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): if hasattr(data, 'items'): for key, value in data.items(): if key == 'results': html_string = render_to_string('user_mbe/EmployeeList.html', {'header': ('first_name', 'last_name', 'id_number', 'phone_number', 'email', 'job_title'), 'data': [tuple(x.values()) for x in value]}) result = pdfkit.from_string(html_string, output_path=False, configuration=config) return result return None # app/views.py from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from .renderers import PDFRenderer, XLSXRenderer from .models import Employee from .serializers.employee import EmployeeSerializer class EmployeeAPIView(ListAPIView): serializer_class = EmployeeSerializer # Are these correct here? renderer_classes = [PDFRenderer, XLSXRenderer, JSONRenderer] def get_queryset(self): return Employee.objects.filter(created_by=self.request.user) def get(self, request, *args, **kwargs): ?? super().get_paginated_response(request, *args, **kwargs) ?? unable to set a file name here return response -
Multi-level access with ManyToMany relationships in Django
I have models, objects from which can be represented as a directed graph: from django.db import models from django.contrib.auth.models import User class Record(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) content = models.TextField() sequels = models.ManyToManyField('self', blank=True, symmetrical=False, through='Extend', related_name='extending') author = models.ForeignKey(User, on_delete=models.CASCADE) class Extend(models.Model): ancestor = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') descendant = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_relationships", fields=["ancestor", "descendant"], ), models.CheckConstraint( name="%(app_label)s_%(class)s_prevent_self_extend", check=~models.Q(ancestor=models.F("descendant")), ), ] Anytime a new instance of Record is created and it has a relationship with another instance through the Extend model, I would love to calculate author.user.userprofile.income attribute in the User instance. The problem is I don't know how to calculate this attribute for all the ancestors of the newly created Record which follows some rule: if the newly created Record costs 50, the first-level ancestor gets 25 and 25 goes to other ancestors, constanly being divided by 2. I can write the formula for the first-level ancestor, but what for others? # In case of some purchase: class ExtendPurchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(Record) date = models.DateField(auto_now_add=True) cost = models.PositiveIntegerField() def calculate_income(self): for item in self.items.all(): item.author.userprofile.income += self.cost / len(self.items.all()) / 2 # first-level; if one would … -
Post request with an object via serializer many=False
I am trying to make a POST request with an object for example this is how I send my request : { "title": "Haloween", "body": " This is one of the greatest ones", "grade_level": { "id": 2, "country": "UG" }, "tags": [{"name": "Jamming"}] } So I wanted to post an object : "grade_level": { "id": 2, "country": "UG" } and below is my Serializer I use : class GradeClassSerializer(CountryFieldMixin, serializers.ModelSerializer): """GradeClass Serializer.""" class Meta: model = ClassGrade fields = ('id', 'grade', 'country', 'color_code', ) class PostSerializer(serializers.ModelSerializer): """Post Serializer""" owner = UserProfile(read_only=True) tags = TagSerializer(many=True) comments = CommentSerializer(many=True, read_only=True) slug = serializers.SlugField(read_only=True) grade_level = GradeClassSerializer(many=False) When I send the object grade_level , I cant seem to receive it it only receives the the id : def create(self, validated_data): """Create a blog post in a customized way.""" grade_level = validated_data.pop('grade_level', {}) status = validated_data.pop('status', '') post = Post.objects.create(**validated_data, owner=self.context['request'].user) if grade_level: grade = ClassGrade.objects.get(id=grade_level['id']) post.grade_level = grade post.save() return post When I make a request, this is what happens : KeyError: 'id' The object comes with only an country without an id. This is what grade_level = validated_data.pop('grade_level', {}) prints : OrderedDict([('country', 'UG')]) How can get the id from the object. NOTE: … -
Error during template rendering using extra_context django
Hello I'm using extra_context in views and in the HTML I'm passing it, but it seems that I am doing it wrong because I get this error: Error during template rendering Does anyone know why? views.py class InformacionTiendasAdd(CreateView): model=InformacionTiendas form_class=InformacionTiendasForm template_name='InformacionTiendas/informacion-tiendas-agregar.html' success_url=reverse_lazy('InformacionTiendas:list_tiendas') extra_context={'tiendas': InformacionTiendas.objects.all()} models.py class InformacionTiendas(models.Model): nombre=models.CharField(max_length=255) registro_desde=models.DateTimeField(default=datetime.now ) tax_id=models.IntegerField() def __str__(self): return f'{self.nombre} {self.registro_desde} {self.tax_id} informacion-agregar-tiendas.html <form class="needs-validation" novalidate> {% for tienda in tiendas %} <div class="row mb-3"> <div class="col-md-12"> <div> <label class="form-label" for="validationCustom01">Name</label> {{ tienda.nombre }} <div class="invalid-feedback"> Please provide the workshop name. </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom06">Registration</label> {{ tienda.registro_desde }} Please provide workshop`s registration number. </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom07">TAX ID</label> {{ tienda.tax_id }} <div class="invalid-feedback"> Please provide workshop`s registration number. </div> </div> </div> </div> {% endfor %} </form> -
why the selected answers is not showing? django
I am trying to make a quiz app using Django and js with using &.ajax jquery function ,, everything runs ok except for selected answers I can see the result and questions everything, why is that happing I had created an input for the answers I can view them on the page. my problem is in the post this selected answer views.py @csrf_exempt def save_quiz_view(request, pk): if request.is_ajax(): questions = [] data = request.POST data_ = dict(data.lists()) # delet the csrf_token data_.pop('csrfmiddlewaretoken') for k in data_.keys(): print('key', k) question = Question.objects.get(text=k) questions.append(question) print(questions) user = request.user quiz = Quiz.objects.get(pk=pk) score = 0 # Get the ratio of user's answers multiplier = 100 / quiz.number_of_questions results = [] correct_answer = None for answer in questions: a_selected = request.POST.get(answer.text) print("selected:", a_selected) if a_selected != "": question_answers = Answer.objects.filter(question=answer) # loop through an answers of praticlar question for a in question_answers: if a_selected == a.text: # question is correct if a.correct: score += 1 correct_answer = a.text else: # both cases display the correct answer if a.correct: correct_answer = a.text results.append({ str(answer): { 'correct_answer': correct_answer, 'answered': a_selected } }) else: results.append({str(answer): 'not answered'}) score_ = score * multiplier Result.objects.create(quiz=quiz, user=user, score=score_) if score_ … -
Declarative mechanism for Django model rows
With some frequency, I end up with models who contents are approximately constant. For example, I might have a set of plans that users can sign up for, with various attributes -- ID, name, order in the list of plans, cost, whether the purchaser needs to be a student/FOSS project/etc.. I'm going to rarely add/remove/change rows, and when I do there's likely going to be code changes too (eg, to change landing pages), so I'd like the contents of the model (not just the schema) to be managed in the code rather than through the Django admin (and consequently use pull requests to manage them, make sure test deploys are in sync, etc.). I'd also like it to be in the database, though, so I can select them using any column of the model, filter for things like "show me any project owned by a paid account", etc.. What are good ways of handling this? I think my ideal would be something like "have a list of model instances in my code, and either Django's ORM magically pretends they're actually in the database, or makemigrations makes data migrations for me", but I don't think that exists? The two workable approaches … -
Printing kwargs.pop displays the right value, using it in a method takes None
I ant to pass a PK in kwargs to a form : views.py def create_mapping_form(request, pk): context = { 'form': MappingForm(pk=pk) } return render(request, 'flows/partials/mapping_form.html', context) In the form i retrieve the PK using : forms.py class MappingForm(forms.ModelForm): class Meta: model = MappingField fields = ( 'fl_col_number', 'fl_col_header', 'fl_cross_field_name', 'fl_cross_position', 'fl_replace_list' ) def __init__(self, *args, **kwargs): pk = kwargs.pop('pk', 'Rien') super(MappingForm, self).__init__(*args, **kwargs) #print(pk) self.helper = FormHelper(self) self.fields['fl_replace_list'].widget.attrs[ 'placeholder'] = "Liste de tuples eg. : [('reman','ES'), ('Gasoline','Diesel')] " headers = GetCsvHeadersAndSamples(pk)['headers'] [...] For populating some fields' CHOICES, I use a method that returns a dic (last line above) headers = GetCsvHeadersAndSamples(pk)['headers'] But something I can't explain sends 'Rien' to GetCsvHeadersAndSamples while when I print(pk) the right value is shown. (GetCsvHeadersAndSamples is not useful, I don't show it) Nota: I display the form in template using HTMX. The issue seems not coming from HTMX because when I hard-code the PK, everything is ok. For the time, I have found nothing else but stocking the PK value in a "temp" file but this slows my script. Thanks -
How to make a model's entries as a field.options list in other model's field?
I have two models - Account, like checking, wallet, credit, etc. and Transaction which includes each purchase and earning. Transaction has a foreign key to Account. In Transaction, I want users to select the Account of purchase. I considered the field.choices but the choices are permanent. I want users to select a choice of Account from Account models. How do I do that? -
bootstrap cdn not working in a django website
this is how it looks with online CDN.how I want it to look and when I give it the offline CDN path this is how it looks -
Avoid csrf token in django post method
I am making part of the web app where (unlogged users, all visitors) can fill the form and I have to save that data (name, phone number, question) in database.. I am making REST using Django, but for frontend I will use React or Django, and I am making POST method in Django framework that reads JSON data from POST https request, and then I save that data to database.. But I get error CSRF verification failed. Request aborted. because I don not use CSRF token, because it is not required for this (I do not have logged users). But I do not want to disable CSRF, because for admin page I would use this to authenticate users? So anyone knows how to avoid using CSRF token for this method? Thanks in advance.. def saveDataToDatabase(request): if request.method == 'POST': json_data = json.loads(request.body) try: data = json_data['data'] except KeyError: HttpResponseServerError("Malformed data!") This is the part of method.. -
'Stocks' object is not iterable - Django
I saw that there are other people who have my problem, but I still can't solve the problem ... thanks to anyone who will help me! models.py class Stocks(models.Model): image = models.ImageField() name = models.CharField(max_length=50) value = models.FloatField() desc = models.CharField(max_length=299) link = models.CharField(max_length=30) views.py def stocks_mt(request): return render(request, 'azmt.html', {'stock': Stocks},) home.html <div class="container"> <div class="row"> {% for Stocks in stock %} <div class="col-sm"> <br><div class="card" style="width: 18rem;"> <img src="{{stocks.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center">{stocks.name}</h5> <!--<h5 class="card-text text-center">50.90€</h5>--> <p class="card-text ">{{stocks.desc}}</p> <h5 class="card-text text-center">{{stocks.value}}</h5> <a href="{{stocks.link}}" class="btn btn-primary">Buy</a> </div> </div> </div> {% endfor %} </div> I tried to capitalize the first letter but nothing has changed ... -
'GenericRelatedObjectManager' object has no attribute 'lang'
I am receiving the error 'GenericRelatedObjectManager' object has no attribute 'lang' when I making a post request. In this query and relationship I have two models Translation and Tags. class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5) field = models.CharField(max_length=255, null=True) translation = models.TextField(blank=True, null=True) def __unicode__(self): return u'%s : %s : %s' % (self.content_object, self.lang, self.field) class Tags(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) description = GenericRelation(Translation) I am creating a serializer mixin to send the same data to different serializer (not only the Tag described below): SerializerTranslationField and TagSerialzer: class SerializerTranslationField(Field): def __init__(self, method_name=None, model_name=None, translation_field=None, **kwargs): self.method_name = method_name self.translation_field = translation_field self.model_name = model_name kwargs['source'] = '*' kwargs['read_only'] = True print("KWARGS ----->", kwargs) super().__init__(**kwargs) def to_representation(self, value): content_type = ContentType.objects.get_for_model(self.model_name) queryset = Translation.objects.filter(content_type=content_type, object_id=value, field=self.translation_field) result = TranslationSerializer(queryset, required=False, many=True).data final_result = {k: v for d in result for k, v in d.items()} print("FINAL RESULT --->", final_result) return final_result class TagsSerializer(NestedUpdateMixin,serializers.ModelSerializer): class Meta: model = Tags fields = ['id', 'type', 'name','description'] def __init__(self, *args, **kwargs): fields … -
How show image in django pdfkit pdf file?
I have a issue, I create detail view in html and after i convert it in pdf for all models object. i use pdfkit, however it doesnt shows object's image, then i run code with image it has some errors. def customer_render_pdf_view(request, pk): posts = get_object_or_404(Person, pk=pk) enrolment =get_object_or_404(Enrollment, pk=pk) template = get_template('test.html') html = template.render({'costumer': posts, 'enrolment':enrolment}) options = { 'page-size': 'Letter', 'encoding':' base64.b64encode("utf-8")', } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response my HTML code : <img src={{costumer.image.url}} height='200px'> -
django retrieve all items filtering by FK
I would like to make an API for retrieve all the dailies of a specific tracker for then retrieve them in react native, could you give me some help about how do it? thanks in advance. I also have User and Habit classes, but in this case i just need this API. class Tracker(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='trackers', on_delete=models.CASCADE) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) published = models.BooleanField(blank=False) @property def habit_title(self): return self.habit.title def is_active(self): today = datetime.now().date() return (today >= self.start_date) and (today <= self.end_date) def no_of_days(self): return abs((self.end_date-self.start_date).days) + 1 class Daily(models.Model): STATUS = [('DONE', 'DONE'), ('TODO', 'TODO'), ('NOTDONE', 'NOTDONE'),] date = models.DateField() status = models.CharField(choices=STATUS, max_length=10, default='TODO') tracker = models.ForeignKey(Tracker, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'tracker'),) index_together = (('date', 'tracker'),) serizalizers.py class TrackerSerializer(serializers.ModelSerializer): habit_title = serializers.ReadOnlyField() class Meta: model = Tracker fields = ['id', 'start_date', 'end_date', 'published', 'is_active', 'no_of_days', 'habit', 'habit_title', 'user'] def create(self, validated_data): tracker = Tracker.objects.create(**validated_data) diff = abs((validated_data['start_date'] - validated_data['end_date']).days) for i in range(0, diff + 1): Daily.objects.create(date=(validated_data['start_date'] + timedelta(days=i)), tracker=tracker) return tracker class DailySerializer(serializers.ModelSerializer): class Meta: model = Daily fields = ['id', 'date', 'status', 'tracker'] views.py class TrackerViewSet(viewsets.ModelViewSet): serializer_class = TrackerSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Running pytest using django manage.py, clear cache option
There are several tests, written with pytest, in my django app I run test using manage.py test with setting TEST_RUNNER = 'PytestTestRunner' PytestTestRunner class class PytestTestRunner: def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb @classmethod def add_arguments(cls, parser): parser.add_argument( '--keepdb', action='store_true', help='Preserves the test DB between runs.' ) def run_tests(self, test_labels): import pytest argv = [] if self.verbosity == 0: argv.append('--quiet') if self.verbosity == 2: argv.append('--verbose') if self.verbosity == 3: argv.append('-vv') if self.failfast: argv.append('--exitfirst') if self.keepdb: argv.append('--reuse-db') argv.append('--cache-clear') argv.extend(test_labels) return pytest.main(argv) The problem is, that even i have option --cache-clear, the .pytest_cache directory is still created How to prevent this behaviour? -
submit html form django
i have this django app and i'm trying to submit form but study material file field have multiple file select option so what i'm trying to do create keylevel with name description status after that with keylevel id i'm saving files in another table. models.py: class KeyLevel(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(null=True, blank=True) status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class KeylevelFileUpload(models.Model): key_level_id = models.ForeignKey(KeyLevel, related_name="keylevel", to_field="id", verbose_name=_("Key Level Id"),on_delete=models.CASCADE, null=True, blank=True, db_column="key_level_id") study_material = models.FileField(upload_to='study_material', null=True, blank=True) status = models.SmallIntegerField(verbose_name=_("Status: 1 for Active; 0:Inactive"), default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) html: <form method="post" action="{% url 'keyLevelAdd'%}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-3"> <div class="formControl static"> <label for="levelName" class="formLabel">{{form.name.label}}</label> <input type="text" name="{{form.name.html_name}}" class="formField" placeholder="Scripture Key Level" id="levelName"> </div> </div> <div class="col-md-4"> <div class="formControl static"> <label for="" class="formLabel">Study Material</label> <div class="upload-input"> <input type="file" name="{{form.study_material.html_name}}" class="formField" placeholder="Scripture Key Level" id="studyMaterial" multiple> </div> <div class="upload-icon"> <div class="browseImg"> <i class="fas fa-upload"></i> {% comment %} <input type="file" class="browseField" name="studyMaterialbrowse" id="studyMaterialb" multiple> {% endcomment %} </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="formControl static textarea"> <label for="" class="formLabel">{{form.description.label}}</label> <!-- <label for="" class="formLabel">About Level Conditions</label> --> <textarea class="formField" placeholder="" rows="5" name="{{form.description.html_name}}">Description</textarea> </div> </div> <div class="col-md-3"> <div … -
For loop not working as expected in Django, HTML
I'm trying to create a search bar where the user can search for a specific user in the database. I've created a for loop in the search_users HTML file but the loop is not iterating through any of my users. Whenever I try to load the page the first line loads ("You searched for ...") but anything in the for loop does not. models.py class User(AbstractUser): """User in a club.""" username = models.EmailField(unique=True, blank=False) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) bio = models.CharField(max_length=520, blank=True) chess_experience = models.IntegerField(blank=False, validators = [MinValueValidator(0)]) personal_statement = models.CharField(max_length=10000, blank=False) created_at = models.DateTimeField(auto_now_add=True) views.py def search_users(request): if request.method == "POST": searched = request.POST.get('searched',False) users = User.objects.filter(first_name__contains=searched) return render(request, 'search_users.html', {'searched': searched, 'users': users}) else: return render(request, 'search_users.html', {}) search_users.html {% if searched %} <h1>You searched for {{ searched }}</h1> {% for user in users %} <a href="{% url 'show_user' user.id %}">{{ user }}</a><br/> {% endfor %} {% else %} <h1>You forgot to search for a member...</h1> {% endif %} -
Angular to Django. File Uploader with a Date Parameter
I have some working code on Django, where i created a simple file uploader with a date picker that is passed through a view and then uploaded onto a database using a standalone python class that utilise sqlalchemy. However, I have been working on migrating the UI aspect onto an Angular Front End, but hit a road block and not sure where I am going wrong. The user needs to be able upload a excel binary file, input a date and hit upload. This should send a request to a view which then handles the request. The view it self works perfectly, when the file and dates are inputted from the Django HTML template. But I can't seem to make it work once the inputs come from Angular. Here is my code views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, data, selectedDate); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } … -
Can not raise ValidationError in django update serializer
I'm trying to raise ValidationError in an update serializer, but couldn't. Here is my code: from rest_framework.exceptions import ValidationError class PersonUpdateSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ( "name", "surname", ) def validate(self, attrs): # type: (dict) -> dict errors = {} attrs = super(PersonUpdateSerializer, self).validate( attrs ) if "surname" not in attrs: errors["surname"] = "This field is required." if errors: raise ValidationError(errors) return attrs def update(self, instance, validated_data): for key in validated_data: setattr(instance, key, validated_data.get(key)) instance.clean() instance.save() return instance When I don't send "surname" parameter, it should raise ValidationError, but it doesn't. What am I missing? -
How to get user id from the related field model in django?
views.py @login_required def become_vendor(request): vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): vendordetailform.instance.vendoruser = request.user request.user=vendordetailform.save() request.user.is_active=False request.user.save() user_details = CustomUser.objects.filter(id=request.user) vendor_details = user_details[0].vendor_details.all() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/become_vendor.html', {'vendordetailform':vendordetailform}) I have two models 1. User model, 2. VendorDetails model (vendoruser is connected by foreignkey relationship with vendordetails) Here I save the User extra details (VendorDetailsForm) if the requested user is applying for a vendor. I could be saved the requested user details in VendorDetails Model. But when I am getting the requested user id, I can't . instead I get vendordetails model foreignkey field. Here I want to inactive the requested user who came with this vendor details form. I am getting Field 'id' expected a number but got <VendorDetails: yabeshofz@gmail.com-Customer1>.