Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got 'category.id'
I'm trying to make a category in the DB, but when I try to access the category with the model that entered. it showing me this Error: ValueError at /category/Django/ Django is category I entered with the model I made using a ForeignKey. I tried a different method for the category but it didn't work either. so I think the problem is in the db.sqlite3 file or in the migrations files. I can't delete the sql3 db file, I have data that I can't easy replaces. I don't think the problem is in the settings.py, I tried to change it before and got the same outcome. the full Error: \Python39\site-packages\django\db\models\lookups.py", line 25, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value raise e.__class__( ValueError: Field 'id' expected a number but got 'published'. here is the views.py for the category class CatListView(ListView): template_name = "Blog/category.html" context_object_name = 'catlist' def get_queryset(self): content = { 'cat': self.kwargs['category'], 'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(category='published') } return content def category_list(request): category_list = Category.objects.exclude(name='default') context = { "category_list": category_list, } the urls.py from django.urls import path from . import views urlpatterns = [ path("category/<category>/", views.CatListView.as_view(), name="category"), ] and for … -
saving the data with user logout signal
I am using the logout signal for saving the logout time of user as follows class StaffLogData(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='staff_log_data', on_delete=models.CASCADE) log_in_time = models.DateTimeField(verbose_name='Log In Time', blank=True, null=True) log_out_time = models.DateTimeField(verbose_name='Log Out Time', blank=True, null=True) active_time = models.DateTimeField(verbose_name='Active Time', blank=True, null=True) active_log_time = models.TimeField(verbose_name='Active Log Time', blank=True, null=True) timestamp = models.DateTimeField(verbose_name='Timestamp', default=timezone.now) def duration(self): if self.log_out_time: return self.log_out_time.replace(microsecond=0) - self.log_in_time.replace(microsecond=0) else: return None def staff_log_in_data(sender, user, **kwargs): if user: StaffLogData.objects.create(user=user, log_in_time=timezone.now()) user_logged_in.connect(staff_log_in_data) def staff_log_out_data(sender, user, **kwargs): last_log_data = StaffLogData.objects.filter(user=user).last() if last_log_data: last_log_data.log_out_time = timezone.now() print('last logout', last_log_data.log_out_time) last_log_data.save() user_logged_out.connect(staff_log_out_data) It prints the output but not saving it, any help is appreciated. -
django debug toolbar problem with the failed to load module script
I have been installing djang-debug-toolbar, but it is not showing but in the chrome developer console, it shows following error. Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec. I have installed pip django debug toolbar using pip in pycharm I have changed the setting in the settings.py Also I have changed the urls.py in the project folder I went in the registry of the windows to check on the HKEY_CLASSES_ROOT\.js\Content Type from text/plain to but there is no Content Type folder under the folder .js Any hints? -
How can I create a basic Soap server with spyne in django
I want to create a server which uses Django and make and take response as SOAP, so I try to use spyne for this reason but I can't run the given code class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): """Docstrings for service methods appear as documentation in the wsdl. <b>What fun!</b> @param name the name to say hello to @param times the number of times to say hello @return the completed array """ for i in range(times): yield u'Hello, %s' % name application = Application([HelloWorldService], 'spyne.examples.hello.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) if __name__ == '__main__': import logging from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server = make_server('127.0.0.1', 8000, wsgi_application) server.serve_forever() -
pass a value from bootstrap to django modal
Here i am trying to pass the value outside for loop modal using ajax here is my template.html {% for compliance in compliance %} {% complience_category compliance request.user as compliances %} {% for qualification in compliances %} ..... ..... <td> <button data-id="{{ qualification.id }}" type="button" class="btn btn-warning margin-bottom edit-qualification"> edit </button> </td> .... ..... {% endfor %} {% csrf_token %} <div class="modal hid fade" id="modal-default"> <form class="form-horizontal" method="POST" enctype="multipart/form-data" action=" {% url 'update_qualifications' qualification.id %}"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Update Compliance</h3> </div> <div class="modal-body"> <div class="control-group"> <label class="control-label" for="inputdate_{{qualification.id}}">Expiry Date</label> <div class="controls"> <input type="date" id="inputdate_{{qualification.id}}" name="expiry_date" value="{{qualification.expiry_date|date:'Y-m-d'}}"> </div> </div> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal">Close</button> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </div> {% endfor %} This is my AJAX $(document).on('click','.edit-qualification',function(){ var id = $(this).data('id'); $.ajax({ url:'', type:'POST', data:{ 'id':id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, success:function(data){ $('#edit_modal .modal-dialog').html($('#edit_modal .modal-dialog',data)); $('#edit_modal').modal('show'); }, error:function(){ console.log('error') }, }); }); </script> Here my modal is outside of for loop Here my problem is when i click the edit button my modal popup is not working (it means when clicking the edit button nothing works for me ) -
how to transfer list from django view to django forms?
I have AppointmentCreateView, which performs the function of booking, and I have hours(), which returns a list of hours the worker has received from his individual schedule, i need to return this list to forms class AppointmentCreateView(CreateView): model = Appointment form_class = AppointmentForm template_name = 'appointment/booking.html' success_url = reverse_lazy('workers') def hours(self, pk): worker = User.objects.get(id=pk) schedule = Schedule.objects.get(id=worker.id) HOUR_CHOICES = [] from_hour = schedule.from_hour to_hour = schedule.to_hour while from_hour <= to_hour: HOUR_CHOICES.append(from_hour) from_hour = time(from_hour.hour + 1, from_hour.minute) return HOUR_CHOICES def form_valid(self, form): form.instance.worker = User.objects.get(pk=self.kwargs['pk']) return super(AppointmentCreateView, self).form_valid(form) i need the user to select the desired time from the list but i don't know how to transfer transfer this list here class AppointmentForm(forms.ModelForm): time = forms.TimeField(widget=forms.Select(choices=HOUR_CHOICES)) class Meta: model = Appointment fields = ('location', 'time') def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['location'].empty_label = 'Select' -
Wie kann ich meiner Web Anwendung sagen, dass sie auf gespeicherte Datei zugreifen und diese ausgeben soll? [closed]
Ich stehe vor folgendem Problem und hoffe ihr könnt mir weiterhelfen: Für meine Arbeit muss ich Daten aus einer Website auf meine eigenentwickelten Webanwendung exportieren und anhand dieser Daten ein Gantt Diagramm zeichnen. Für das Exportieren gibt es schon eine Funktion auf der Website. Die Daten können als html Datei oder XML Datei exportiert werden. Doch wie sag ich meiner Web Anwendung, dass diese auf die gespeicherten Daten zugreifen und auslesen soll? Auf was muss ich hierbei achten? Ist JS dafür eine geeignete Sprache oder empfehlt ihr mir mit einer anderen Programmiersprache zu arbeiten wie z.B Python? Oder sogar vllt. dass Framework Django nutzen? Ich bin für jeden Tipp dankbar! Lg -
Setting callback domain in django allauth
I have fargate containers , the one has django and the other has nginx. And django use allauth for login. https://django-allauth.readthedocs.io/en/latest/installation.html In this case, when accessing OAuth allauth makes the callback url such as, 127.0.0.1/callback/something However, Of course it doesn't work. Callback url should be example.com/callback/something. How can I set the callback domain? -
AttributeError at / 'AnonymousUser' object has no attribute '_meta'
I was trying to use signin page but this error shows up. Image of error while running in Mozilla web browser localhost I had tried the solution using this link and ended up mixing auth model to the chatbot model. this is the link of my whole views.py file of chatbot app. https://pastebin.com/2E7mgyuR def get(self, request): return render(request, 'chatbot/signin.html') def post(self, request): context = { 'data': request.POST, 'has_error': False } username = request.POST.get('username') password = request.POST.get('pass1') if username == '': messages.add_message(request, messages.ERROR, 'Username is required') context['has_error'] = True if password == '': messages.add_message(request, messages.ERROR, 'Password is required') context['has_error'] = True user = authenticate(request, username=username, password=password) # if not user and not context['has_error']: # messages.add_message(request, messages.ERROR, 'Invalid login') # context['has_error'] = True if context['has_error']: return render(request, 'chatbot/signin.html', status=401, context=context) login(request, user) return redirect('chatpage') and This is my models.py of chatbot from django.db import models from django.contrib.auth import get_user_model # Create your models here. Mod = get_user_model() class User(Mod): is_email_verified = models.BooleanField(default=False) def __str__(self): return self.email and this is what it is showing in terminal Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 27, 2022 - 09:27:56 Django version 4.0.5, using settings 'Eva_Chatbot.settings' … -
category and paginator connections django html
I have a problem when I select one category and in this category when I want to go to another page it sends me just to a different page and I need it to send me to for example category=pk {{ page=2 }} or like this but now it sends to {{ page=2}} enter image description here -
How to Get queryset not dict django aggregate
i'm using this queryset for my requirements invoices = Invoice.objects.aggregate(total_amount=Sum('order__order_items__amount'),number_of_invoices=Count('pk', distinct=True)) which returns dict---> {'total_amount': Decimal('17700.00'), 'number_of_invoices': 2} but I want queryset how can i do that.. Thanks for any help -
Django differentiate between fetch requests
I have 2 different fetch request coming to the same view in Django. How do I differentiate between them? The first fetch request is loading new content and the second is used for a different purpose altogether but they both come from the same url and to the same view. I have the following code in my view: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return async_response(request, post) And what I need is something similar to: if request.headers.get('X-Requested-With') == 'XMLHttpRequest': if fetch function 1: django function 1 if fetch function 2: django function 2 Do i need to add some custom headers? -
No such file or directory when python manage.py runserver
I have function to upload the document in folder, after it i want to execute methods to transform this file. I wrote another functions where i am calling this methods, but after pyrhon manage.py runserver i receive No such file or directory: 'beeline/media/docs/assignment.xlsx' But if i execute python file with methods everyrhing is working fine class UploadView(generic.TemplateView): def get(self, request): form = ExcelForm return render(request, 'index.html', {'form': form}) def injection(self): post_team() post_db_service() post_database() post_db_schema() post_db_table() return "Everything is created" def post(self, request): if request.method == 'POST': form = ExcelForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] fss = FileSystemStorage('media/docs') fss.save(upload.name, upload) self.injection() return render(request, 'ty.html') return render(request, 'index.html') -
Django calculated fields on custom queryset
This seems like a basic question but for the life of me I cannot seem to figure this out. I have a Recipe model that uses a custom RecipeQueryset as a manager. Now I've been doing a lot of reading on where to put business logic of the application some people suggest a "services" layer others say to put it in a custom queryset which is what I am trying to accomplish now. None of them really give an example of doing calculations though only CRUD functionality. At the moment I have a property of total_cost defined on the Recipe model but according to a lot of articles/discussions I should be moving this "business logic" to elsewhere to the custom queryset for example? Is there a way to do the calculation in a custom queryset method for a queryset of Recipe objects and calculate that total_cost for each Recipe and return that queryset with the extra total_cost field? How would I then add this so it can be used in my serializer? Model class RecipeQueryset(models.QuerySet): """Custom queryset for Recipe Model""" def all_for_user(self, user): return self.filter(user=user) # this is where I think I should put it? def total_cost(self, recipe): return # … -
While downloading xls file from django download code, file is not opening, It shows corrupted
Here is my code for xls download using python(Django) views.py def downloadfile(request, filename=''): if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" path = open(filepath, encoding='cp437') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response else: return HttpResponseRedirect("adduser", {}) With this code I am able to download file properly, but while opening that file it shows me error. I attach screenshot of error. I have tried this code for solution, if filename != '': BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'SampleExcel.xls' filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" return FileResponse(open(filepath, 'rb') , True, filename) else: return HttpResponseRedirect("adduser", {}) This also not works, It shows error 'TypeError at /downloadfile/SampleExcel.xls HTTP status code must be an integer.', and it is not even downloading. Please help me. I am stuck here from last 3 days. Note: I need to download xls file only, as after downloading it I have to perform import functionality with that downloaded xls file. I can not change xls to xlsx. -
Django Form Is None
Im on investigation Django framework and now trying to create custom procedure of resetting password. I use this URL path path('password_reset_confirm/<uidb64>/<token>', PasswordResetConfirmView.as_view( template_name='user_account/reset_password/password_reset_confirm.html', success_url='/account/password_reset_complete/'), name="password_reset_confirm"), In template i use crispy form <form class="login-form p-4 rounded" method="post"> {% csrf_token %} <h1 class="h4 mb-4 font-weight-bold">Change your password</h1> <p>Use the form below to change your password.</p> {{ form|crispy }} <button type="submit" value="Change"> Submit </button> </form> So now this form do not showing in template, and if if type {{ form }} instead of {{ form.as_p }} or crispy form, that showing me None in form place. -
"GET /static/css/stylesheet.css HTTP/1.1" 404 1813
I tried to ling CSS file in Django framework by using " " It shows error but, it is showing error ""GET /static/css/stylesheet.css HTTP/1.1" 404 1813file Oder" -
Can't use context data in the HTML in django
models.py class ChapterQuestions(models.Model): question_id = CharField(primary_key=True, max_length=40) question_order = CharField(max_length=40, blank=True, null=True) question_wording = CharField(max_length=4000, blank=True, null=True) question_type = CharField(max_length=1, blank=True, null=True) sub_question = CharField(max_length=1, blank=True, null=True, default='N') sub_question_trigger = CharField(max_length=1, blank=True, null=True, default='Y') answer_required = CharField(max_length=1, blank=True, null=True, default='Y') parent_question = models.ForeignKey('self', on_delete=models.DO_NOTHING) chapter = models.ForeignKey(ReportChapter, on_delete=models.DO_NOTHING) update_date = models.DateField(blank=True, null=True) update_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, db_column="update_user", blank=True, null=True) class Meta: managed = True db_table = "Chapter_Question" views.py class LfrReportChapterOneView(PermissionRequiredMixin, TemplateView): permission_required = "RockHub_App.is_in_risk_and_ic_team" template_name = "../templates/dashboards/lfr/lfr_report_chapitre1_create.html" def get_context_data(self, *args, **kwargs): context = super(LfrReportChapterOneView, self).get_context_data(*args, **kwargs) data = ChapterQuestions.objects.filter(chapter_id=1).order_by("question_id") context["questions"] = data return context While debugging i can see all the data available in the database but in the HTML file when I write **<h1>{{ questions.question_id }}</h1>** or <div hidden> {% for qst in questions %} {{ qst.question_id }},{{ qst.question_name }} {% endfor %}</div> <div><h1>{{ qst.question_id }}</h1></div> Nothing is shown !! -
daphne service listen failure: Couldn't listen on 0.0.0.0:8001 Address in already in use
as the title indicates I am using django-channels with daphne in the production server but when I show the status of daphne.service it says 8001 is already in use. The interesting thing is that the socket connection is working perfectly with the frontend and easily exchanging messages. here is my configurations # /etc/systemd/system/daphne_seb.service [Unit] Description=daphne daemon After=network.target [Service] User=simple Group=www-data WorkingDirectory=/home/simple/my_proj ExecStart=/home/simple/my_proj/venv/bin/daphne -b 0.0.0.0 -p 8001 project.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target daphne asgi in supervisor # /etc/supervisor/conf.d/daphne_proj.conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8001 # Directory where your site's project files are located directory=/home/simple/my_proj # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/simple/my_proj/venv/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:fileno=0 --access-log - --proxy-headers project.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=4 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/home/simple/my_bg/daphne.log redirect_stderr=true finally, my nginx looks like this upstream websocket { server 0.0.0.0:8001; } server { listen 80; server_name MY_SERVER_DOMAIN; location = /favicon.ico { access_log … -
How to call a variable present inside a function into a different function present inside a class in python?
I want to compare the 'limit' variable present inside a function with another integer variable 'amount' present inside a different function inside a class. @login_required def Limit(request): if request.method == "POST": limit = request.POST.get('tlimit') en = UserLimit(limit=limit) en.save() print(limit) return render(request, 'limit.html') class PaymentView(View): def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) form = PaymentForm(self.request.POST) userprofile = UserProfile.objects.get(user=self.request.user) if form.is_valid(): token = form.cleaned_data.get('stripeToken') save = form.cleaned_data.get('save') use_default = form.cleaned_data.get('use_default') if save: if userprofile.stripe_customer_id != '' and userprofile.stripe_customer_id is not None: customer = stripe.Customer.retrieve( userprofile.stripe_customer_id) customer.sources.create(source=token) else: customer = stripe.Customer.create( email=self.request.user.email, ) customer.sources.create(source=token) userprofile.stripe_customer_id = customer['id'] userprofile.one_click_purchasing = True userprofile.save() amount = int(order.get_total() * 100) if (amount > limit): print("Not allowed") -
how to import excel file in mysql database with check the field validation which have country code or not in django python
how to upload excel file in mysql database before import , check the field validation for contact number which have country code or not in django python. Hi we are trying to import file to add data to database , for simple data it is working. but we want to know before import data we want to check whether contact number data have country code or not so how can we check? Is it possible to check data before import? -
Need to check if a timer is started when reload the page and continue running the timer
I did a timer with Django and Java Script to count how many hours a user is working into the company. My problem is, when i refresh the page the timer is rested. I need to get the timer continue counting up in accordance with the date and time in hours when the page is reload IF the timer is starting. HTML <link rel="stylesheet" href="../static/css/contador.css" /> <script src="../static/js/contador.js"></script> {% block content %} <!-- Main page --> <section class="container chrono"> <!------ Message displaying in a div ------> {% if messages %} {% for message in messages %} <div class="center"> <div class="{{ message.tags }}"> <div> {{ message }} </div> </div> {% endfor %} </div> {% endif %} <div class="row justify-content-center"> <div class="profile-complete-button col-sm-4 center" id="cronometro"> <div id="reloj"> 00:00:00 </div> <form name="cron" action="#"> <input class="btn btn-cron" type="button" value="Iniciar" id="button_1" name="boton1" /> <input class="btn btn-cron" type="button" value="Pausar" id="button_2" name="boton2" /><br/> </form> </div> </div> </section> {% endblock %} JS if($(this).val() === 'Iniciar') { $.ajax({ url: 'view_contador_start', headers: {"X-CSRFToken": getCookie('csrftoken')}, method: 'POST', contentType: 'application/json', data: JSON.stringify({ 'contador_time_start': '00:00:00', 'chrono_date': WithoutTime() }), dataType: "json", cache: false, success: function (response) { console.log(response) } }); ``` Django ``` def view_contador_start(request): """View to display the counter""" print('body', request.body) chrono_data_start = … -
encrypt data in django that need complex search
we have a Django Rest app with PostgreSQL db that in some parts business force us to encrypt data. but what I need is searching and heavy queries on data to be executed, I've used django-pgcrypto-fields but it's not updated until 2021 and have some bugs for production,what can I do?encrypting data directly does't allow me to execute queries for search the data,also I can't find any other library to help me. -
Django "no such table found" error even after makemigrations
I recently add a new table RunningTable in my models file and I do execute both: python manage.py makemigrations and python manage.py migrate. Both commands returned success. And I checked files in APPName/migrations/000x.py and the RunningTable lies really there. But my code runs with this table not found error. I tried check by Django shell with below picture shows. As you can see, I can import it from the correct path. But failed when I call RunningTable.objects.all(). Is there anyone can tell me why this error happens? -
How to set custom text for django on_delete function?
I have a model named 'Clients' and another model named 'Information'. class Information(models.Model): client_name = models.ForeignKey(Clients, on_delete=models.SET(get_deleted_client_intance)) I want to set a custom text when a name is deleted from 'Clients' model. The below function creates a new name 'deleted' as a new entry and is saved in 'Clients' model. I don't want that. I want if I delete a name it says 'deleted' or 'removed' on it's place. def get_deleted_client_intance(): return Clients.objects.get_or_create(name='deleted')[0] How can I do this?