Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django, TypeError: doctor_code_create() missing 1 required positional argument: 'h_code'
doctor.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(h_code): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' h_code_test = h_code d_code = last_doctor_code.d_code doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + h_code_test + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'h_code' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I have to specify it? -
Filter Django query set by appended attribute
I'd like to filter/exclude instances in a query set where change=0 but I'm getting a FieldError with the below code. movements = part.history.all() previouslevel = 0 for movement in movements: movement.change = movement.stockOnHand - previouslevel previouslevel = movement.stockOnHand print(movements.exclude(change=0)) Is there a way to filter a query set with an appended attribute? -
django) Got a `TypeError` when calling `Doctor.objects.create()`, I want to solve it
hospital.py class HospitalList(models.Model): hospitalname = models.CharField(max_length=200) def hospital_code_create(): last_hospital_code = HospitalList.objects.all().order_by('code').last() if not last_hospital_code: return 'h' + '000001' code = last_hospital_code.code hospital_int = int(code[3:9]) new_hospital_int = hospital_int + 1 new_code= 'h' + str(new_hospital_int).zfill(6) return new_code code = models.CharField(primary_key=True, max_length = 200, default = hospital_code_create, editable=False) doctor.py class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) I want to display d_code as d002001, not d001. Here, 002 is the foreign key from which the primary key of hospital.py is imported. I've slightly modified doctor.py to implement this. doctor.py(Revise) class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(**h_code**): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code **h_code_test = h_code[-3]** doctor_int = int(d_code[3:6]) new_doctor_int = doctor_int + 1 new_d_code= 'd' + **h_code_test** + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) After modifying as above, Got a TypeError when calling DoctorList.objects.create(). Error occurred. What … -
Django Unable to open static file loading
enter image description here enter image description here enter image description here I was proceed "python manage.py collectstatic" enter image description here -
MKV file downloads and doesn't display
I have made a Django model where I store files and if there is a mkv file it doesn't display in the URL like how the others do. The URLs do show the video but if it is mkv it downloads in the link so what could I do to stop it. So I think in need to change the file type in python so like how can I do that or if there is a better way could you tell me how to. Thanks -
Como puedo asignar un valor iniciar a un foreignkey en vistas basadas en clase django
estoy tratando de seleccionar el valor inicial del Paciente ForeignKey: class Consulta(models.Model): Paciente = models.ForeignKey(paciente, on_delete=models.CASCADE) Area_de_consulta = models.ForeignKey(Area, on_delete=models.CASCADE) Notas_de_la_consulta = models.TextField("Ingrese las notas de la consulta", max_length=500) def __str__(self): return '%s %s %s' % (self.Paciente, self.Area_de_consulta, self.Notas_de_la_consulta) el objetivo es que al aparecer el form en la vista debe ir con el paciente que recibirá la consulta seleccionado. Como podría realizar esta acción ? he buscado y aun no termino de entenderlo, podrían orientarme por favor. -
How to make multiple choice field from Django many to many related model
I want to show products from product model using check boxes in my store form where user can select multiple products. Product Model: class Product(models.Model): product_name = models.CharField(max_length=30) product_price = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product_name Store Model: class Store(models.Model): AREAS = [ (0, 'Dhaka'), (1, 'Khulna'), (2, 'Chittagong'), (3, 'Barisal'), (4, 'Rajshahi'), ] SELLER_TYPE = [ (0, 'Manufacturer'), (1, 'Authorised Dealer'), (2, 'Distrubutor'), (3, 'Dealer'), ] store_owner = models.ForeignKey(User, on_delete=models.CASCADE,related_name='store_owner') store_name = models.CharField(max_length=256) store_address = models.CharField(max_length=300) seller_type = models.IntegerField(choices=SELLER_TYPE, default=0) area = models.IntegerField(choices=AREAS, default=0) products = models.ManyToManyField(Product, related_name='store_products') timestemp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.store_name Store Form: class StoreForm(forms.ModelForm): area = forms.ChoiceField(choices=Store.AREAS, label='Area', required=True) products = forms.MultipleChoiceField(queryset=Product.objects.all(), label='Manager', required=True) seller_type = forms.ChoiceField(widget=forms.RadioSelect, choices=Store.SELLER_TYPE) class Meta: model = Store fields = ('seller_type', 'store_name', 'store_address', 'products', 'area') I want to select multiple product item while I'm going to create a record for a store. Currently I can select multiple product items from the product list. But I want to represent them as check-boxes so that users can select multiple items from the check-boxes. -
On Django form, I want to know how to respond to form field data in JSON
I was successful using this method but, I want the repose code to be simpler. Is there such a way? The code is as follows: views.py class PersonnelInfoDetailView(DetailView): def get(self, request, pk): employee = Employee.objects.get(pk=pk) response = {'employeeType' : employee.employeeType_id, 'driverIndex': employee.driverIndex, 'routeId': employee.routeId_id, 'department': employee.department, 'employeeNumber': employee.employeeNumber, 'employeeName': employee.employeeName, 'employeeBirth' : employee.employeeBirth, 'employeeAddress' : employee.employeeAddress, 'employeeTel' : employee.employeeTel, 'employeeEmergencyTel' : employee.employeeEmergencyTel, 'employeeSalary' : employee.employeeSalary, 'employeeFixedRest1' : employee.employeeFixedRest1, 'employeeFixedRest2' : employee.employeeFixedRest2 , 'tableHoBong' : employee.tableHoBong_id, 'jobTitleType' : employee.jobTitleType, 'employeeStatus' : employee.employeeStatus } return HttpResponse(json.dumps(response), content_type='application/json') forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ('employeeType','driverIndex', 'routeId', 'department', 'employeeNumber', 'employeeName', 'employeeBirth', 'employeeAddress', 'employeeTel', 'employeeEmergencyTel', 'employeeSalary', 'employeeFixedRest1', 'employeeFixedRest2','tableHoBong','jobTitleType', 'employeeStatus') def __init__(self, *args, **kwargs): super(EmployeeForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control form-control-sm w-100' -
How To Serve media Files In Production
I have a Django project which sends automated e-mails with attached pdfs to users. At the moment I just have a normal /media/ folder with the pdf in it which the code points to. This works in development but throws a server error in production. My question is how do I server media files in production? I have read a lot about it but can't find exactly what I'm after. I use collectstatic in my production environment which works for static files, I'd expect something similar for media files. Thank you. -
Django HTMLForms AttributeError AttributeError: module 'polls.views' has no attribute 'index'
I'm using Django to create a simple HTML input page, right now I am just using the tutorial for Django Forms but I get the error AttributeError: module 'polls.views' has no attribute 'index' Here are all the relevant files: This is where the Error is happening: $ mysite/polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] This is views.py: $ polls/views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) and this is forms.py $ /polls/forms.py from Django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) I am so confused as to why this is happening because when I used it with the Writing your first … -
AttributeError: 'Query' object has no attribute 'explain_query'
I updated Django2.0.2 to 2.2.16. Then, I'm having a lot of errors of AttributeError: 'Query' object has no attribute 'explain_query' at many places. What's wrong? Any idea? -
django.db.utils.IntegrityError: UNIQUE constraint failed: cedente.cnpj (django)
After I delete a Cedente if I try to create another one with the CNPJ of the previous one, I have this error: django.db.utils.IntegrityError: UNIQUE constraint failed: cedente.cnpj this is the model: class Cedente(BaseModel): class Meta: db_table = 'cedente' verbose_name = "cedente" verbose_name_plural = "cedentes" razao_social = models.CharField(max_length=100, unique=True, verbose_name="Razão Social") nome = models.CharField(max_length=100, verbose_name="Nome Padrão") cnpj = models.CharField(max_length=14, validators=[validate_CNPJ], unique=True, verbose_name="CNPJ") nome_contato = models.CharField(max_length=100, verbose_name="Nome") ddd_telefone_contato = models.CharField(max_length=2, verbose_name="DDD", validators=[validate_int, validate_length_ddd]) numero_telefone_contato = models.CharField(max_length=9, verbose_name="Telefone", validators=[validate_int, validate_length_telefone]) email_contato = models.CharField(max_length=50, verbose_name="E-mail", validators=[validate_email]) calculo = models.ForeignKey(Calculo, verbose_name="Cálculo", related_name='cedentes', on_delete=models.CASCADE, null=True) commissao = models.ForeignKey(Commissao, verbose_name="Comissão", related_name='cedentes', on_delete=models.CASCADE, null=True) def __str__(self): return ("%s (ID: %d)" % (self.nome, self.id)) -
Quick help on how to format a logic statement
this might seem silly, but i need help, I have a model, in which if "is_vendor" is True, I want it to display something, while if "is_vendor" is False, I dont want the item to display. I already figured how to switch the is_vendor from True to False or vice versa, What i want now is to know how to complete {% if user_profile.is vendor... statement (Plus Im not sure if want i typed there is close to correct. Thank you Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') is_vendor = models.BooleanField(default=True) My template: **{% if user_profile.is_vendor** <div style="margin-left: 40px"> <a class="btn btn-sm btn-outline-primary mb-4 mr-3 "href="{% url 'vendor_register' %}"> Register </a> </div> -
Loading spinner after PayPal payment
So I'm building a Django e-commerce which allows payments via PayPal. Once the user introduces all his PayPal information and presses pay, the PayPal window disappears and take a few seconds to call the function I put inside onApprove. As I show here: // Finalize the transaction onApprove: function (data, actions) { return actions.order.capture().then(function (details) { submitFormData(); }); } As I said it takes a few seconds (3 or 4) to execute the call submitFormData() after the customer accepted the transaction. Is there any way I can put a loading spinner in the middle of the screen? I imagine I can but honestly I don't know where to start. Thank you very much -
i have accidently delete my sceret key form settings.py in django
while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project. while pulling from git hub i lost my secret key which i have updated. is there any way to obtain secret key for the same project. -
Django Class Based Views Download Video YouTube return 404 not found in File
I'm developing a website for training in Django (Class Based View) that downloads a video that the user informs the URL on the front end. However, when returning the exact URL, Django appears as 404 - Not Found. How can I pass the parameter to download the file? In urls.py I already inserted + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) to download the static files Below are the files: views.py class PaginaPrincipal(TemplateView): template_name = 'home/index.html' def get(self, request, *args, **kwargs): if not os.path.exists('media/'): os.makedirs('media', exist_ok=True) for file in glob.glob('media/*.mp4'): if file: os.remove(file) return render(self.request, self.template_name) def post(self, request): link = str(self.request.POST.get('link-youtube')) if link: func.videoDownload(link) return redirect(reverse_lazy('pagina-resultado')) return render(request, 'error.html', {'error': 'erro ao baixar, tente novamente'}) class PaginaResultado(TemplateView): template_name = 'home/result.html' def get_context_data(self, **kwargs): context = super(PaginaResultado, self).get_context_data(**kwargs) arquivo = None for file in glob.glob('media/*.mp4'): arquivo = file context['videoDownload'] = arquivo return context func.py def videoDownload(url): yt = YouTube(url) yt.streams.order_by('resolution')[-1].download() movingFileToCorrectPath(flag='video') yt.streams.filter(only_audio=True)[-1].download() movingFileToCorrectPath(flag='audio') joinFile() title = yt.title urlVideo = 'https://www.youtube.com/watch?v=' + yt.video_id views = yt.views thumbnail = yt.thumbnail_url author = yt.author renameLastFile(title=title) # print(title, urlVideo, views, thumbnail, author) def movingFileToCorrectPath(flag): if not os.path.exists('/static/video'): os.makedirs('static/video', exist_ok=True) try: if flag == 'video': for file in glob.glob('*.webm'): os.renames(file, f'video-{file}') a = f'video-{file}' shutil.move(a, 'static/video/') elif … -
Django forms, attrs cols and rows for textarea doesn't work, why?
I'm working on a project with Django and a textarea. The textarea by default renders cols="40" and rows="10", which is not great for my page. I'm trying to use Django's widgets to change those attributes to 20 and 5 respectively. This is my code: class NewContent(forms.Form): content = forms.CharField(widget=forms.Textarea(attrs={"cols":20, "rows":5})) Unfortunately, the code does not change the looks of the form at all when the page gets rendered. Meaning, it displays cols 40 and rows 10. But wait, things get really bizarre... when checking on the developer tools, on Google, I can see that the HTML code has changed to what I want! crazy!! I also tried the following code that I found in a different chat: attrs={"style": "height:60px; width:500px"} Which "changes" the size of the box but... for different reasons I'm not in love with this solution. Does anybody have an idea of what is happening here? I have a windows 10 and use VEC. Cheers! -
django form in bootstra modal not working
I am trying to show a django form inside a bootstrap modal, it kind of works, Everything except the form shows up when i try to launch the modal. folder_form.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <<div class="modal fade" id="modal-1"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <main class="p-5"> <div class="row"> <div class="col-sm-6 offset-sm-3"> <h1 class="myhead2">Create Folder</h1> <hr> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{form | crispy}} <input class="btn btn-dark my-3" value="Create Folder" type="submit" /> </form> </div> </div> </main> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> {% endblock %} home.html <a data-toggle="modal" href="#modal-1">Edit Contact</a> {% include "ahmed_drive/folder/create" %} <script type="text/javascript"> $(document).ready(function(){ $('#modal').on('submit', function(event){ event.preventDefault(); $.ajax({ url: '/ahmed_drive/folder_form.html', type: 'POST', // headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: $('#modal').serialize(), beforeSend: function () { $("#modal-1").modal("show"); }, success: function(data) { $('#modal-1 .modal-body').html(data); } }); }); }); </script> I don't know ajax so i copied it from somewhere and modified it. please tell me whats wrong. -
how to correctly link user model to a custom user model
i have this custom user model class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name and i use allauth package for authentication and once i sign up a new user i got this error in the main page of the website: RelatedObjectDoesNotExist at / User has no customer. is there a way to link the user to a customer automatically once the user got created? -
Properly get querry using javascript on Django
I'm developing a website and one of my priorities is a dynamic search table with autocomplete etc. I found this possible using ajax and javascript. I already mplemented a trigger everytime the user types in the search field. The problem is actually getting data from the database, right now i'm getting a 404 error, no data is being returned CODE: views.py if request.method == "POST": search_str=json.loads(request.body).get('searchText') bib = Bibrest51.objects.all().filter( autor__starts_with=search_str) | Bibrest51.objects.all().filter( autor__icontains=search_str) data = Bibrest51.objects.all() return jsonResponse(list(data), safe=False)``` JS: ``` const searchField = document.querySelector("#searchField"); searchField.addEventListener("keyup", (e) => { const searchValue = e.target.value; if(searchValue.trim().length > 0){ console.log("searchValue", searchValue); fetch("bibliografia-search", { body: JSON.stringify({ searchText: searchValue }), method: "POST", }) .then((res) => console.log(res)) .then((data) => { console.log("data", data); }) .catch(e => { console.log(e); }) } })``` Any help would be greatly aprecciated, i'm new on the site and i hope i di'nt do anything wrong on this post, feedback for improving my post is also aprecciated thank you! -
Django dynamic Q date filter gives mysterious results
I'm trying to query dynamically in Django with Q objects based on variables as follows: if end_date: end_time: datetime = get_end_of_time(end_date) q_objects = Q(_connector=Q.OR) query_filters = [field + '__lte' for field in fields] for _filter in query_filters: q_objects.add(Q(**{_filter: end_time}), Q.OR) things = things.filter(q_objects) q_objects looks as follows: (OR: ('created_at__lte', datetime.datetime(2020, 8, 6, 23, 59, 59, 999999, tzinfo=<DstTzInfo 'EET' EEST+3:00:00 DST>)), ('started_at__lte', datetime.datetime(2020, 8, 6, 23, 59, 59, 999999, tzinfo=<DstTzInfo 'EET' EEST+3:00:00 DST>))) However, it returns things that have created_at or started_at after the specified dates: started_at: 2020-07-22 12:45:48.160277+00:00 created_at: 2020-08-07 13:40:48.516932+00:00 It works fine if I manually query the objects as follows: things = things.filter(Q(created_at__lte=end_time) | Q(started_at__lte=end_time)) So I'm wondering, what am I doing wrong? And more importantly (so I'd learn), why is this happening? -
How do I use pagination for ViewSet with multiple models in Django Rest Framework?
I made a ViewSet to return response with combined data of two models (Items and Ads). My code is below: url.py urlpatterns = [ re_path(r'^feed/?$', FeedViewSet.as_view({'get': 'list'}), name='feed'), ] feed.py - views from rest_framework import viewsets from rest_framework.response import Response from api.models import Item, Ads from api.serializers.feed import FeedSerializer, ItemSerializer, AdSerializer from collections import namedtuple Feed = namedtuple('Feed', ('items', 'ads')) class FeedViewSet(viewsets.ViewSet): """ ViewSet for listing the Items and Ads in the Feed. """ def list(self, request): feed = Feed( items=Item.objects.all(), ads=Ads.objects.all(), ) serializer = FeedSerializer(feed) return Response(serializer.data) feed.py - serializers from rest_framework.serializers import ModelSerializer, Serializer from api.models import Item, Ads class ItemSerializer(ModelSerializer): class Meta: model = Item fields = '__all__' class AdSerializer(ModelSerializer): class Meta: model = Ads fields = '__all__' class FeedSerializer(Serializer): items = ItemSerializer(many=True) ads = AdSerializer(many=True) When I send GET request everything works fine I get response like following: { "items": [ {"title": value_1, ...}, // first item {"title": value_2, ...}, // second item //etc ], "ads": [ {"id": 1, ...}, // first ad {"id": 2, ...}, // second ad //etc ] } Now I want to add pagination to my ViewSet, how do I do it? I would appreciate if you can provide working example. -
How do I display the form in a template?
views.py from django.shortcuts import render from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form = TaskForm() context = {'tasks':tasks, How do I display the value of a Django form field in a template?'form':forms} return render(request, 'tasks/list.html', context) models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms.py from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('title','complete') I would like form fields to add new tasks for my todo beginner project. I use {{form}} on the html file but Django display <module 'django.forms' from '/home/***/.local/lib/python3.8/site-packages/django/forms/__init__.py'> instead of tasks fields How to get the form in the template ? -
Could it be possible to override the "is_active" method from my user model?
In my forms.py file: class RegistrationForm(UserCreationForm): class Meta: model = User fields = [ "first_name", "last_name", "email", "username", "password1", "password2" ] -
Raspberry Pi application with Django, Qt or something else?
I want to program a specialized solar controller using a Raspberry Pi. On the functional side I already programmed everything in Python. So inputs: temperatures, flow and flow switches and outputs: relais, datalogging are all more or less done. But the only way I have now to see what my code is doing is by print statements, that's not ideal. What is the best way to add a decent UI? Moreover I want to be able to see how the system is doing remotely. So I am in Holland and the RPi is in India. I have some experience in programming in Django, so one thought is to let the RPi run a website. Than use Django to visualize what the controller is doing. Another possibility would be to use Qt. I could program the UI with Qt and than remotely login to the RPi. Does anyone have recommendations what is the best/easiest way to get a decent UI?