Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display the field value based on the value selected from the drop down in django forms
I am a newbie!! I have a task to populate a field value based on the option selected from the drop down menu. Forms.py from django import forms from .models import MainPage import datetime from datetime import date techlist = ( ('DateOfDrive', 'DateOfDrive'), ('NameOfDrive', 'NameOfDrive'), ('Status', 'Status'), ('Marks_Scored', 'Marks_Scored'), ('First_Round_Interviewer_Name', 'First_Round_Interviewer_Name'), ('Second_Round_Interviewer_Name', 'Second_Round_Interviewer_Name'), ('Third_Round_Interviewer_Name', 'Third_Round_Interviewer_Name'), ('Management_Round_Interviewer_Name', 'Management_Round_Interviewer_Name'), ('HR_Round_Interviewer_Name', 'HR_Round_Interviewer_Name') ) class analysisForm(forms.Form): GroupBy = forms.ChoiceField(choices=techlist) where = forms.CharField() datefrom = forms.DateField(initial="2019-01-01") dateto = forms.DateField(initial=date.today()) views.py class analysis(FormView): template_name = 'analysis.html' # View for the analysis page def get(self, request): form = analysisForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = analysisForm(request.POST) if form.is_valid(): groupbyf = form.cleaned_data['GroupBy'] # Getting the groupby otpion from the user wheref = form.cleaned_data['where'] # Getting the search element from the user datetof = form.cleaned_data['dateto'] # Getting the end date from the user datefromf = form.cleaned_data['datefrom'] # Getting the from date from the user # Loading the excel to data frame query = str(Summary.objects.all().query) df_view_summary = pd.read_sql_query(query, connection) print(df_view_summary) # Extracting the month number from the complete date df_view_summary['Month'] = pd.DatetimeIndex(df_view_summary['DateOfDrive']).month analysis.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_p }} </table> <input type="submit"> … -
Run code when "foreign" object is added to set
I have a foreign key relationship in my Django (v3) models: class Example(models.Model): title = models.CharField(max_length=200) # this is irrelevant for the question here not_before = models.DateTimeField(auto_now_add=True) ... class ExampleItem(models.Model): myParent = models.ForeignKey(Example, on_delete=models.CASCADE) execution_date = models.DateTimeField(auto_now_add=True) .... Can I have code running/triggered whenever an ExampleItem is "added to the list of items in an Example instance"? What I would like to do is run some checks and, depending on the concrete Example instance possibly alter the ExampleItem before saving it. To illustrate Let's say the Example's class not_before date dictates that the ExampleItem's execution_date must not be before not_before I would like to check if the "to be saved" ExampleItem's execution_date violates this condition. If so, I would want to either change the execution_date to make it "valid" or throw an exception (whichever is easier). The same is true for a duplicate execution_date (i.e. if the respective Example already has an ExampleItem with the same execution_date). So, in a view, I have code like the following: def doit(request, example_id): # get the relevant `Example` object example = get_object_or_404(Example, pk=example_id) # create a new `ExampleItem` itm = ExampleItem() # set the item's parent itm.myParent = example # <- this should … -
save data to another table after creating django
i have two models ImageShoot and Image. models.py: class ImageShoot(models.Model): name = models.CharField(max_length=100) # image = models.URLField(name=None) created_at = models.TimeField(auto_now_add=True) def __str__(self): return self.name class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12) title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE) image_keyword = models.TextField(max_length=1000) credit = models.CharField(max_length=150, null=True) location = models.CharField(max_length=100, null=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title what i am trying to achieve that when i create a image it should show on imageshoot also like when i create image in shoot 1. this image should show on shoot 1 -
Error: Http failure during parsing for https://site/update/
I am writing a backend of an application which uses angular in frontend and Django in backend. There is a feature in application which wants to edit some information of an existing entity in the database. I have written the API for it. The API uses a stored procedure to update the database. I have tested the API using the POSTMAN tool by sending RAW JSON data and it works. I can see the data getting updated in the database table. But when I try to send the data through application frontend, I see the data is updated in the table but in the application frontend I am seeing an error: Error: Http failure during parsing for https://site/update/ What is this error and how to resolve it? -
Django - Import Export Update Field Type on import
I have an excel sheet that looks like this: var 1 var 2 var 3 20 abc 01/02/2010 20 abc 01/02/2010 20 abc 01/02/2010 and a model that looks like this: class ExcelData(models.Model): field_one = models.IntegerField() field_two = models.IntegerField() field_three = models.IntegerField() Is it possible to update the models field's name and type with the data from the excel file and generate new fields? Expected Result: class ExcelData(models.Model): var_1 = models.IntegerField() var_2 = models.CharField() var_3 = models.DateField() Thank you for any suggestions -
How do I display selected many to many result from database?
Lab_Group Class class Lab_Group(models.Model): group = models.CharField(max_length=100, unique=True,) Lab Class class Lab(models.Model): laboratory = models.CharField(max_length=50, unique=True) group = models.ForeignKey(Lab_Group, on_delete=models.CASCADE) LabRequest Class class LabRequest(models.Model): lab_test = models.ManyToManyField(Lab) This is my view lab_group = Lab_Group.objects.all() for lg in lab_group: print('Lab Group Result', lg) for lab in lg.lab_set.all(): print('Lab Result', lab) for lr in lab.labrequest_set.all(): print('Lab Reques Result', lr) Finally, I want to display all selected data from LabRequest class. When I was saving I selected some lab_tests from Lab class. So, now I want to display only saved data which are in LabRequest -
Not all arguments converted Python - Oracle
I have an issue regarding the using of django.db connection to an oracle database. Here is a sample of my query: "MERGE INTO TABLE E USING dual ON (Col1= :1) WHEN MATCHED THEN UPDATE SET Col2= :2, Col3= :3, UPDATE_TIMESTAMP = CURRENT_TIMESTAMP WHEN NOT MATCHED THEN INSERT (Col1, Col2, Col3) VALUES (:4, :5, :6)" Here are the values: ('1', '2', '', '1', '2', '') Here is the error stack trace: Traceback (most recent call last): File "xxx\db_mgr.py", line 17, in db_insert cursor.executemany(insert_query, sliced_data) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\utils.py", line 117, in executemany return super().executemany(sql, param_list) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\utils.py", line 71, in executemany return self._execute_with_wrappers(sql, param_list, many=True, executor=self._executemany) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\utils.py", line 90, in _executemany return self.cursor.executemany(sql, param_list) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\oracle\base.py", line 514, in executemany query, firstparams = self._fix_for_params(query, next(params_iter)) File "C:\FAST\Python\3.6.4\lib\site-packages\django\db\backends\oracle\base.py", line 500, in _fix_for_params query = query % tuple(args) Here is my db_insert method: from django.db import connection as conn def db_insert(data, insert_query, limit=100): """Persist data to database :param data: Tuple of tuples :param insert_query: String :param limit: Integer """ cursor = conn.cursor() temp_value = None try: for i in data: temp_value = i cursor.execute(insert_query, i) conn.commit() # for i in range(0, int(len(data) / … -
Inverted coordinates using Django Rest Framework Gis and MapBox
I would to render a polygon on a map based on MapBox using Django Rest Framework GIS. I've defined the serializer using GeoFeatureModelSerializer: class UserTaskSerializer(GeoFeatureModelSerializer): class Meta: model = UserTask geo_field = "geom" fields = ( "id", "geom", "geom_area", ) This is my views.py: @api_view(["GET"]) def usertask_api_view(request): if request.method == "GET": features = UserTask.objects.all() serializer = UserTaskSerializer(features, many=True) return Response(serializer.data) And urls.py: urlpatterns = [ path('api/', include([ path('user-data/', views.usertask_api_view, name="api_user_data"), ])), ] When I try to render the polygon using MapBox with this code: map.addSource('polygon_source', { type: 'geojson', data: '{% url 'api_user_data' %}', }); map.addLayer({ 'id': 'target_area', 'type': 'fill', 'source': 'polygon_source', 'paint': { 'fill-color': '#f30', 'fill-opacity': 1.0, 'fill-outline-color': '#000' } }); I see the coordinates inverted. This is the GeoJSON from the API: { "type": "FeatureCollection", "features": [ { "id": 1, "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ 40.56864121175715, 14.197631833842024 ], [ 40.54318254328975, 14.197906498331575 ], [ 40.544852266756976, 14.263000484090297 ], [ 40.57218795948987, 14.262176522053778 ], [ 40.56864121175715, 14.197631833842024 ] ] ] }, "properties": { "geom_area": "27931461.09" } } ] } What I've wrong? -
More than one calendar in Django Fullcalendar App
Sice i managed to implement Fullcalendar's functionality into my Django app, I have another question. Is it possible to render more than one Fullcalendar into my html page, depending of how many Calendars are made inside the database. And, i need them to be rendered HORIZONTALLY. I suppose that i need to change my div's id to 'calendar2' for example. But what should i change inside the initializer? This is full script and style from my calendar. <script> document.addEventListener('DOMContentLoaded', function () { let calendarEl = document.getElementById('calendar'); let calendar = new FullCalendar.Calendar(calendarEl, { minTime: "07:00:00", maxTime: "22:00:00", businessHours: { startTime: '08:00', // a start time (10am in this example) endTime: '21:00', // an end time (6pm in this example) }, height: 'auto', locale: 'sr', plugins: ['dayGrid', 'timeGrid', 'list', 'interaction'], defaultView: 'timeGridDay', header: { left: 'today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek' }, navLinks: false, // can click day/week names to navigate views editable: false, eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}T{{ i.start_date|time:"H:i" }}', end: '{{ i.end_date|date:"Y-m-d" }}T{{ i.end_date|time:"H:i" }}', }, {% endfor %} ] }); calendar.render(); }); </script> <style> body { margin: 40px 10px; … -
Get value from MultipleCheckBox to an attribute in Django User Profile Model
I'm trying to add something like User Profile to an exist django site. I've two troubles about that. One of them is I have to show a multiplecheckbox in the register page and i have to get that chosen data to selected_features attribute. But i couldn't find the suitable data type for that and I always get different errors. The second is I have got an error that; "UNIQUE constraint failed: auth_user.username" When I used ForeignKey, I got an error, too. Here is the Model class UserAttribute(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') company = models.CharField(max_length=50) selected_features = models.CharField(validators=[validate_comma_separated_integer_list], max_length=15, null=True) Here is the Form class RegisterForm(forms.Form): first_name = forms.CharField(max_length=50,label="İsim") last_name = forms.CharField(max_length=50,label="Soyisim") username = forms.CharField(max_length=50,label="Kullanıcı Adı") company = forms.CharField(max_length=50,label="Şirket İsmi") email = forms.EmailField(max_length=50,label="E-mail Adresi") phone = forms.CharField(max_length=50,label="Telefon") password = forms.CharField(max_length=20,label="Parola", widget =forms.PasswordInput) confirm = forms.CharField(max_length=20,label="Parolayı Doğrula", widget =forms.PasswordInput) features = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=FEATURES, label="Modelinizde Kullanmak İstediğiniz Özellikleri Seçiniz:") def clean(self): first_name = self.cleaned_data.get("first_name") last_name = self.cleaned_data.get("last_name") username = self.cleaned_data.get("username") company = self.cleaned_data.get("company") email = self.cleaned_data.get("email") phone = self.cleaned_data.get("phone") password = self.cleaned_data.get("password") confirm = self.cleaned_data.get("confirm") feature = self.cleaned_data.get("features") if password and confirm and password !=confirm: raise forms.ValidationError("Parolalar Eşleşmiyor") values = { "username" : username, "password" : password, "first_name" : first_name, "last_name" : … -
Can't give href to a link, error: "Reverse for 'foo' not found"
I'm new to the django and the error that i got is: "Reverse for 'influencers' not found. 'influencers' is not a valid view function or pattern name". What i want to do is redirect two different urls (site.com && site.com/influencers) to the same view. This is because i have a side menu which contains a tab called "Influencers" and i want both this link and "mysite.com" to work. I even accepted not using mysite.com/influencers and tryed something like href="{% url '' %}" but it didn't work either. This line is in my base.html file which causes the error: <a href="{% url 'app1:influencers' %}" class="side_link"> >&nbsp Influencers</a> Here is my view: class InfluencerList(LoginRequiredMixin, ListView): model = Influencer That's my urls.py file: app_name = 'app1' urlpatterns = [ path('', InfluencerList.as_view()), path('influencers', InfluencerList.as_view()), ] I appreciate any help or advices. -
Django internationalization in URL patterns with AJAX
How can I use i18n_patterns with AJAX Post? If I post with AJAX the language prefix does not appears in the url. -
How do I invoke a function with a timer.?
How do I invoke a function with a timer.? also how to get a value from another function Model # Choices time = [ ('1', 'Morning'), ('2', 'Afternoon'), ('3', 'Evening'), ('4', 'Night'), ] # Model class Calendar(models.Model): user = models.ForeignKey(AUTH_USER_MODEL,on_delete=models.SET_NULL) date = models.DateField() time = models.CharField(max_length=10, choices=time) location = models.CharField(max_length=32) conformation = models.BooleanField(default=False) View class CheckAvailability(APIView): permission_classes = [IsAuthenticated] def post(self, request): date = request.data.get('date') time = request.data.get('time') location = request.data.get('location') user = request.user if date and time and location: exists, created = Calendar.objects.get_or_create( user=user, date=date, time=time, location=location ) if created: serializer = CalenderSerializer(exists, context={'request': request}) return Response({'response': 'created', 'result': serializer.data, }) else: return Response({'response': 'Exists'}) def auto_delete(self, post): calendar_id= post.created.id # actually here i wanted the created id of calendar object from the above post method item = Calendar.objects.get(id=calender_id) if item.conformation == False: item.delete() return Response({'response': 'item deleted'}) timer = threading.Timer(60.0, auto_delete) timer.start() This auto_ delete def is completely wrong. I don't know how to select created(calendar object) ID from the above post function. When a calendar object is created, I wanted to invoke the auto_delete function after 1 minute how do I do that .? can anyone help me to do this .? -
Django: Unable to configure handler 'syslog'
I make docker image from django project, and it started to create error that I never had before. The error is seems like related to logging, specifically syslog. At first, I thought that missing /dev/log in docker image creates an error. So I added line to docker file to create /dev/ folder and log file. However, The error did not disappear. This is error logs. File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/local/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/local/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'syslog': [Errno 2] No such file or directory This is logging related settings. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'syslog': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'facility': 'user', 'address': '/dev/log', }, 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'stream': { 'level': 'INFO', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'root': { 'handlers': ['syslog', 'mail_admins'], 'level': 'ERROR', }, 'SocialAuth': { … -
What object does chart.js return?
im new to django and especially foreign to java script programming . I am trying to implement a chart.js chart in my django project , and i am thinking of creating a dynamic dashboard. In order to do so , the code for creating a dashboard should be reusable and therefore stored in a dashboard. However , i do not know what kind of object a chart.js returns . Here is my attempt at modularising it: function dashboard_creator(name_graph , type_graph , queryset , tablekey_label , tablekey_value ,backgroundColor_code , borderColor_code ,borderwidth){ var canvas = document.getElementById(value.toString(name_graph)).getContext('2d'); var name_graph = new Chart(myChart, { type: value.toString(type_graph) , data: { labels: [{% for item in queryset %}'{{item.tablekey_label}}',{% endfor %}], datasets: [{ label: '# of Votes', data: [{% for item in queryset%}{{item.tablekey_value}},{% endfor %}], backgroundColor: [ 'backgroundColor_code' ], borderColor: [ ' borderColor_code' ], borderWidth: value.toInt(borderwidth) }] }, }); return json } Your help will be greatly appreciated , thank you! -
Making voice-assistant API scalable
I'm currently developing a voice-assistant as a Service from scratch with Django + Anaconda packages. My current expectations are it should handle 5000 requests at the same time with response time no less than 10 seconds for each request. The service will have 10k skills at first, and it'll increased over time. User's access to a skill is limited to what skills he/she subscribed to. Whenever user accessing a skill, a tensor-flow model of that skill will be loaded into the server. Each different skills use distinct tensor-flow model. Because I'm still an inexperienced newbie, when I first developed this API, I built it ignoring scalability problems I'll faced later on. I saved users data using plain old sql database, recklessly calling local API everywhere, and never use asynchronous programming method. The problem is, I don't think my server could efficiently load 5000 tensor-flow models at the same time in the worst case that 5000 users accessing different skills. Is there a way to fix it? For clarity, here's my server specifications: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 64 On-line CPU(s) list: 0-63 Thread(s) per core: 2 Core(s) per socket: 16 Socket(s): 2 NUMA node(s): … -
Cannot view allauth login and signup pages
I have been following a tutorial on YouTube to create a facebook login and signup process using allauth https://www.youtube.com/watch?v=mmHn5XYlgto However, I whenever I try and visit the url /accounts/login the page loaded is my index/home page. Not sure what i am doing wrong. Here is my urls.py file from django.contrib import admin from catalog import views from django.urls import path, include from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('courses/', views.courses, name='courses'), path('course-details/', views.coursedetails, name='course-details'), path('accounts/',include('allauth.urls')), settings.py: INSTALLED_APPS = [ 'sendemail.apps.SendemailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'django_extensions' ] SITE_ID = 1 ... AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] -
How to implement javascript code in django template?
I am trying to prevent the submission of a button when pressed. But with my javascript code, the button still refreshes the page when the submit button is pressed. Here's my code (doesn't work): <html> <head> <title>tangina</title> </head> <body> <form action="POST" class='user-signup-form'> {% csrf_token %} <input type="text"> <button type="submit">submit</button> </form> <script> $(document).ready(function(){ var userForm = $(".user-signup-form") userForm.submit(function(event){ event.preventDefault(); }) }); </script> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> </body> </html> this is just a simple code, I'm just trying to try to prevent the button from submitting form when pressed. What am I doing wrong here? -
NoReverseMatch at Django when I tried to update model object
I am writing a view to update a record in the database, when I try to switch to a record for editing, I get an error: Error I wrote one to one from an existing view for another model, so I do not understand what the error is. How i can fix this? urls.py path( 'keys/<int:key_id>/', views.UpdateKeyView.as_view(), name='update_key' ), views.py class UpdateKeyView( SuccessMessageMixin, CustomPermissionRequired, UpdateView ): model = ApiKey pk_url_kwarg = 'key_id' template_name = 'db_visual/update_key.html' form_class = KeyForm success_url = reverse_lazy('keys') permission_required = ( 'db_visual.change_key', ) success_message = "Ключ <a href='%(url)s'>%(description)s</a> " \ "успешно изменен!" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, url=reverse_lazy( 'update_key', kwargs={'key_id': self.object.id} ), ) HTML-code {% for key in api_keys %} <tr> <td class="min-col"> <a href="{% url 'update_key' key_id=key.id %}"> {{ key.description}} </a> </td> <td class="min-col">{{ key.open_key }}</td> <td class="min-col">{{ key.secret_key }}</td> <td class="min-col"> <a class="btn btn-sm btn-link" href="{% url 'update_key' key_id=key.id %}"> <i class="far fa-edit fa-lg"></i> </a> </tr> {% endfor %} -
How include dropdown menu with django-mptt in template
I want to be able to create dropdown menu using admin panel. At this moment in model I can choose if subpage is children of another and in what order it should be displayed. But I don't know how to implement all of this together in template. Can anyone help please? model: class Subpage(MPTTModel): title = models.CharField(max_length=254) slug = models.SlugField(unique=True) display_order = models.IntegerField(default=1) parent = TreeForeignKey('self', verbose_name='is child:', on_delete=models.CASCADE, null=True, blank=True) view: def generated_page(request, slug): unique_subpage = get_object_or_404(Subpage, slug=slug) homepage = Homepage.objects.first() subpage_sorted = Subpage.objects.exclude(is_active=False).order_by('display_order') context = { 'unique_subpage': unique_subpage, 'subpage_sorted': subpage_sorted, 'homepage': homepage, } if unique_subpage.is_active or unique_subpage.slug == 'admin': return render(request, 'subpage.html', context) else: return render(request, '404.html', context) template: {% recursetree subpage_sorted %} <li class="nav-item dropdown"> {% if not node.is_child_node %} <a class="nav-link" href="{% url 'generated_page' node.slug %}">{% trans node.title %}</a> {% elif node.is_child_node %} <a class="nav-link dropdown-toggle" href="{% url 'generated_page' node.parent.slug %}" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans node.parent.title %}</a> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'generated_page' node.slug %}">{% trans node.title %}</a> {% endif %} </li> {% endrecursetree %} -
Printing PNG image in Zebra printer
I have an HTML page which has some texts and Barcode, I used the HTML2Canvas javaScript library to crop the part that I want to print from this page. Here is the function: printBarcode() { var element = jQuery("#capture")[0]; html2canvas(element).then(function (canvas) { console.log("ready"); var myImage = canvas.toDataURL("image/png"); var tWindow = window.open(""); $(tWindow.document.body).html("<img id='Image' src=" + myImage + " style='width:100%;'></img>").ready(function () { tWindow.focus(); tWindow.print(); }); }); } Now I want to print this PNG image in Zebra printer how can I do that? do I need to use ZPL? or adjusting the printer driver is enough? I've tried to adjust the printer driver but the font was too small. Thanks, -
form validation fails some times and shows value erorr
<< VIEWS>> some times form is validating but some times form is not validating and shows value error def hai(request): if request.method == 'POST': obj1 = hello(request.FILES, request.POST) if obj1.is_valid(): r eturn HttpResponse("success") <<FORMS>> does form need to be cleaned every time submiting class hello(forms.Form): uname = forms.CharField(max_length=100) img = forms.FileField() <<HTML>> * html for submiting form * <html> <head></head> <body> <form action= {% url 'hai' %} method="POST" enctype="multipart/form-data "> {% csrf_token %} <div class="d-flex"> <div class="form-group mr-2"> <label for="" class="label">Pick-up date</label> <input type="text" name="uname" class="form-control" placeholder="Date"> </div><br> <div class="form-group ml-2"> <label for="" class="label">Drop-off date</label> <input type="file" name="img" class="form-control" placeholder="Date"> </div><br> <input type="submit" value="Book Now" class="btn btn-primary py-3 px4"> </div> </form> </body> </html> <> [enter image description here][1] -
Two models in one Django DetailView and filtering by relation betwen them
I have a question. In my DetailView I want to placed data from two models. Moreover, I want to filter them, that on my scenario-detail was only that comments related to specyfic scenario, related by ForeignKey->Scenario. My views.py: class ScenarioDetailView(LoginRequiredMixin, DetailView): model = Scenario def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.all() return context And in scenario_detail.html i have a simple {{ comments }} I thinking on filtering my comment object in views.py, something like: Comment.objects.get(commentScenario=Scenario.id) but it didn't work at all. My models.py: class Scenario(models.Model): scenarioTitle = models.CharField(max_length=256) scenarioArea = models.ForeignKey(ScenarioArea, on_delete=models.CASCADE) scenarioAuthor = models.ForeignKey(User, on_delete=models.CASCADE) scenarioDate = models.DateTimeField(default=timezone.now) scenarioDescription = models.TextField() def __str__(self): return self.scenarioTitle def get_absolute_url(self): return reverse('scenario-detail', kwargs={'pk': self.pk}) class Comment(models.Model): commentText = models.CharField(max_length=256) commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE) commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE) commentDate = models.DateTimeField(default=timezone.now) def __str__(self): return self.commentText And urls.py: path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'), Could someone help me? -
How to convert color image to gray image using opencv in django
i am a learner,i want to convert color image to gray image using OpenCV in Django but I'm tired to solve it. when i upload a color image then i show the original image but whwn i can't convert to gray scale or binary image then show me an error if any possible solutions please shear me def show(request): from.models import User from django.views.decorators.csrf import csrf_exempt, csrf_protect user=User.objects.all() p = user[len(user)-1].pic ptUMat=cv2.cvtColor(p,cv2.COLOR_RGB2GRAY) o=cv2.imshow('gray image',pt) #img= cv2.imread(p) #plt=cv2.cvtColor(img,cv2.COLOR_BAYER_BG2BGR) #q=request.FILES['img'] #ima=binary(pic=q) #ima.save() print(o.url) return render(request,'binaryimage.html',{'pic':o.url}) -
Django API ListView returns empty queryset in tests (works properly with postman)
I have an API ListView endpoint, which works properly when I shoot it with Postman, but returns empty queryset and status 404 in tests: test result: web_1 | > assert response.status_code == 200 web_1 | E assert 404 == 200 I use pytest fixture to create my object: conftest.py @pytest.fixture def event(system, new_conflict): return Event.objects.create(system=system, event_type='new_conflict', details=new_conflict ) Fixtures work fine in other (not API) tests, so I believe the problem might be in the way I'm testing my API. In pycharm debugger I can see that the view is executed, so it's not a url problem. In postman, this endpoint properly returns a json with Event objects and status 200. test_api.py from rest_framework.test import APIClient from event_finder.models import Event import pytest @pytest.mark.django_db def test_list_events_all(event): client = APIClient() response = client.get(path='/api/events/', format='json') assert response.status_code == 200 views.py from rest_framework.generics import ListAPIView from event_finder.models import Event from event_finder.serializers import EventSerializer class ListView(ListAPIView): queryset = Event.objects.all() serializer_class = EventSerializer