Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change condition in if template tag using javascript
I am trying to use some value that I get from clicking a button to be loaded in the if statement in my HTML template. but cannot do so.maybe I am doing everything wrong. I have used var tag and placed my variable inside it but it didn't work when I tried to edit it through javascript code {% for publication in page.get_children.specific %} {% if publication.pub_type == <var id="varpubtype">pubtype</var> %} {% if publication.pub_year == <var id="varpubyear">pubyear</var> %} <tr> <td>{{ publication.Authors }}</td> <td>{{ publication.name }}</td <td>{{ publication.pub_year }}</td> <td>{{ publication.pub_journal }}</td> <td>{{ publication.vol_issue }}</td> <td>{{ publication.pages }}</td> </tr> {% endif %} {% endif %} {% endfor %} here is my script function toggletable( var pubtypevar) { document.getElementById("varpubtype").innerHTML = pubtypevar; } function toggleyear( var pubyearvar){ document.getElementById('varpubyear').innerHTML = pubyearvar; } when i used var and span tags it showed template error. That Could not parse the remainder: ' -
i want to import excel file data into django database table,how to solve below errors?
class office(models.Model): office_name = models.CharField(max_length = 200) location = models.CharField(max_length = 200) class employees(models.Model): name = models.CharField(max_length = 200) designation = models.CharField(max_length = 200) officeid = models.ForeignKey(office,on_delete = models.CASCADE,related_name = 'emp') views.py from .models import office,employees from import_export import resources from tablib import Dataset class Simple_import(APIView): def get(self,request): if request.method == 'POST': employees_resource = EmployeesResource() dataset = Dataset() new_persons = request.FILES['myfile'] imported_data = dataset.load(new_persons.read()) result = employees_resource.import_data(dataset, dry_run=True) # Test the data import `if not result.has_errors():` `employees_resource.import_data(dataset, dry_run=False) # Actually import now return render(request,'info/index.html')` index.html {% block content %} {% csrf_token %} Upload {% endblock %}` if i click upload button enter image description here i got an error above shown in that image how to solve that error?? -
django.db.utils.OperationalError: (1054, "Unknown column
I'm trying to debug RALPH (a server using DJANGO framework to interact with MySQL). I've already seen this issue around but not a clear (to me) final answer. Please consider I'm a total python newby. The server is actually not working and returns a Server Error (500) while the log reports a django exception (see below). Here the _do_query() from cursors.py ... def _do_query(self, q): db = self._get_db() self._last_executed = q db.query(q) self._do_get_result() return self.rowcount ... and the query() from connections.py ... def query(self, query): # Since _mysql releases GIL while querying, we need immutable buffer. if isinstance(query, bytearray): query = bytes(query) if self.waiter is not None: self.send_query(query) self.waiter(self.fileno()) self.read_query_result() else: _mysql.connection.query(self, query) ... Here is the all log traceback: Traceback (most recent call last): File "/opt/ralph/ralph-core/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/opt/ralph/ralph-core/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1054, "Unknown column 'assets_asset.start_usage' in 'field … -
Django: Checks with web-view
I read the docs for checks: https://docs.djangoproject.com/en/2.2/topics/checks/ I am missing something: I would like to have a web view where an admin can see what's wrong. Calling this view should execute the check and the result (ok or failure messages) should be visible. I could hack something like this myself. But I would like to go a common way, if there is already such a way. As opposed to unit-testing this is about checking a production server. How to do this the django-way? -
"How to make Django-helpdesk Run"
I am unable to run Django--helpdesk. First I want to do basic test and start to add additional codes to meet my requirements but I am stuck in the first step I have gone through the document, tired uninstalling django 2.22 and install 1.11 but still cannot make it work. I tired downloading the zip file, I tired pip install helpdesk too and installation get succeed but dont see the code. I hope someone can guide step by step as I am stuck in the step 0 to 1. I have tried runserver. learned about manage.py. I have also downloaded and tried pycharm but no success. I have been trying this and that for last 5/6 days. Hope some one can help me with it -
Django - How to return all objects in a QuerySet in their subclass form, rather than their parent class form?
I have a class Set with a manytomany relationship to Item. I have lots of 'set' objects all containing lots of 'items'. However, the Item class has been subclassed to create Article, Podcast, Video, and Episode. Basically, everything on the database was originally an Item. If my_set is a Set instance, containing Items - how do I create a queryset which returns those objects in their subclass form? Ie, rather than me getting a Queryset full of Item instances, I get a Queryset with Article, Episode, Video, Podcast instances. How would I get `my_set.objects.all().as_subclass()' to work? class Item(models.Model, AdminVideoMixin): base_attributes = 'foo' def as_episode(self): return Episode.objects.get(slug=self.slug) class Video(Item): class specific fields class Article(Item): class specific fields class Podcast(Item): class specific fields class Episode(Item): class specific fields class Set(Item): front_page = models.BooleanField(max_length=300, blank=False, default=False, null=False) items = models.ManyToManyField(Item, related_name='in_sets', through='SetMeta', max_length=5000,) def get_absolute_url(self): return reverse('foo') def ordered(self): return self.items.all().order_by('-itemOrder__order') def episodes(self): episode_list = [] for each_item in self.items.all(): episode_list.append(each_item.as_episode()) return episode_list def __str__(self): return self.title As you can see I tried two methods - to write a model method on Item() which returns itself as an Episode - but this only worked for single instances rather than a queryset. As such … -
Why does my Django Project on Heroku not load the 404 page when debug is set to False?
I'm deploying my Django project on heroku and set debug to False but it returns an error 500. When I set it to true, it works fine. When I set my heroku config for Debug to False, it also returns an error 500. Here are my settings which when I set to False, returns a 500 status code. DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') on Heroku, the debug value is also true. When I change it to False, it returns a 500 status code. DEBUG_VALUE=True Basically, when my debug is True on my file & on heroku, it runs smoothly and shows the 404 page that returns You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. When DEBUG=False on my django settings and on heroku, it returns status code 500 ALLOWED_HOST = ['myapp.herokuapp.com'] I hope I explained it well -
How to overwrite get method in generic RetrieveAPIView in django rest framework to filter the results
I have an API that can list several buildings. Each building belongs to several building groups and each building group contains several buildings. I want to show single fields of one building group. More specifically I want to show all buildings of one building group in my RetrieveAPIView. I can list a single BuildingGroup instance using the generic view like so: class BuildingGroupRetrieveAPIView(RetrieveAPIView): serializer_class = BuildingGroupSerializer queryset = BuildingGroup.buildings.all() I assume that I can overwrite the get method to only display a single field of that retrieved object. Specifically I want to display all the objects that are in my many to many relation. Here are my models: class Building(models.Model): name = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) buildings = models.ManyToManyField(Building, default=None, blank=True) I tried this without success: def get(self): building_group = BuildingGroup.objects.get(id='id') qs = building_group.buildings.all() return qs I can attach a screenshot to be more clear. Any help is highly appreciated. Thanks in advance Here is my full view: class BuildingGroupAPIView(ListAPIView): permission_classes = [permissions.IsAdminUser] authentication_classes = [SessionAuthentication] serializer_class = BuildingGroupSerializer passed_id = None def get_queryset(self): qs = BuildingGroup.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(name=query) return qs … -
How to filter my database row whit their id?
I'm new to python and my question might be so simple and maybe i'm just confusing myself. I have a postgresql database table with 3 columns, one is id and other two are some information about users. How can I filter my table so that it give me one of my column's data and its id? My code is this: def new_item_lessons_learned(request): if request.method == 'POST': lessons_learned_form = LessonsLearnedForm(request.POST) if lessons_learned_form.is_valid(): getting_departments_id = Departments.objects.filter(mycolumn=pk) The problem is in .filter. I hope someone can help me. Thanks. -
Run Python tags through Textarea
I have setup wagtail cms application and i have build one snipets that have field "title" as charField,"key-word" as charField and "content" as TextBlock. - I have created one record with value title : "header" key-word: "header-design" content : "Slug Text" But when i open in browser it show image python script as it is instead of output path of image. {% get_contentholder "Logo Holder" as header_part %} {{header_part | safe }} {% get_contentholder "Logo Holder" as header_part %} {{header_part | safe }} Slug Text -
Custom Django Menu get a weird behaviour
Good morning everybody, I would like to get your help/advices in order to find with me why my behaviour is weird with my custom django menu. My environment: Django 1.11.20 Python 3.6.2 Django-simple-menu 1.2.1 modeltranslation django-cruds The expected result: I have a navbar menu which is completely dynamical. Admin can handle it as he wants by adding menu - submenu - position - ... Furthermore, this menu uses modeltranslation module which let to display content in English or French in my case. The model: class NavbarMenuSettings(models.Model): """ A class to manage navbar menu of the application """ collection = models.ManyToManyField('app.Collection', related_name='collection_list', symmetrical=False) application = models.ForeignKey('app.WebApplication', verbose_name=_('application'), related_name='application', on_delete=models.CASCADE) title = models.CharField(max_length=30, verbose_name=_('title')) url = models.URLField(max_length=256, verbose_name=_('url'), blank=True, null=True) order = models.PositiveSmallIntegerField(default=1, verbose_name=_('menu order'), blank=True, null=False) display = models.BooleanField(verbose_name=_('Display menu'), default=True) def __str__(self) -> str: return self.title class Meta: verbose_name = _('menu setting') verbose_name_plural = _('menu settings') The CRUD: I'm using a crud module which let to define my NavbarMenuSettings like this: class NavbarMenuSettingsCRUDView(MainConfigCRUDManager): """ CRUD views for Navbar Menu Settings """ model = NavbarMenuSettings default_sort_params = ('application', 'asc') # Configuration of fields search_fields = ['application', 'title', 'order', 'url', 'display'] list_fields = ['application', 'title', 'order', 'display'] create_fields = update_fields = ['application', … -
validate_email giving Attribute Error on ajax request
I am working on a project where I am validating an email field using onChange event on that input field. When I use validate_email on the email value fetched, It shows following error: AttributeError: 'str' object has no attribute 'GET' views.py from django.core.exceptions import ValidationError from django.core.validators import validate_email def validate_email(request): email = request.GET.get('email',None) data = { 'is_taken' : CustomUser.objects.filter(email__iexact=email).exclude(email__iexact=request.user.email).exists() } try: validate_email(email) except ValidationError: data['invalid'] = "Invalid email address." if data['is_taken']: data['error_message'] = 'Email already exists.' return JsonResponse(data) html $("#email").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("validate-email"), data: $("#email").serialize(), dataType: 'json', success: function (data) { if (data.is_taken) { $("#error_msg").text(data.error_message); $("#email").val("");} else if(data.invalid) { $("#error_msg").text(data.invalid); $("#email").val(""); } else { $("#error_msg").html(""); } } }); }); Also the functionality of checking for existence of email also gets Attribute Error if I use validate_email. Otherwise it works absolutely fine. -
why are there two manage.py in django project?
From what I understand,there are two different starting points where we can run server through python manage.py runserver command in Django: First > "mysite" (as in many tutorials, and this folder is called "project" right? Second > "app"(as in many django blog tutorials "blog") But as I entered the command "cd mysite"(notice it's not "cd app") and did git push to pythonanywhere, my pythonanywhere just shows "mysite" which I didn't even type in "python manage.py migrate"! So I realized because of that, I couldn't even enter the admin website since I didn't create user on this "project" level but only in my "app" level Is there anything I missed or did wrong with this? Is it normal for a user to set up admin password on "app" level right? What did I do wrong on this and how can I fix it so that pythonanywhere shows my "app"? -
How to correctly authenticate in Mayan EDMS
I'm using a Mayan EDMS running in a docker container to serve customer documents to my django app. Now I'm kinda stuck at downloading these documents. I use pythons requests to access the Mayan Api. In my requests I use auth = HTTPBasicAuth(settings.MAYAN_AUTH_USER, settings.MAYAN_AUTH_PW) documents = requests.get(url, auth=auth) to authenticate me. But each document has a full download link which I would like to access directly from the frontend. Is there a way to a authenticate via URL parameter? I wasn't able to find anything mentioning this. When I'm downloading with requests I get images and pdfs as a byte object without any encoding which I am unable to display in my template. -
Error -Login failed for user 'XXXX' azure SQL server database
I have a Python 3.6 Django azure web app, i am using Azure sql server database. For few months the user gets the following error: ('28000', "[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'XXXX'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'XXX'. (18456)") I tried several solutions non of them worked, yesterday i decided to set audit log on the database , and when looking in the logs i see the following error: Err 2812, Level 16, Server XXXX Could not find stored procedure 'sp_cloud_connection_set_sds'. I am not familiar with this store procedure and not sure why it tries to run it, any ideas on how to solve it? Thanks, Nir -
SQL query not showing any change in database
I have a model in django where I want to enter some data using the query below. The query is running without any errors but the tuple isn't added in the database. What could be the reason for this? conn=sqlite3.connect('C:\mysite\db.sqlite3') cursor=conn.cursor() query="INSERT INTO 'polls_finalscore' VALUES (1,'michel',22);" result=cursor.execute(query) -
'str' object has no attribute 'as_widget'
I've made a form in django and Added Template tag Add_attr the problem is i am getting these error. 'str' object has no attribute 'as_widget' to {{ form.session_type|add_class='form-control' }} Template tag: from django import template register = template.Library() @register.filter(name='add_attr') def add_attr(value, arg): return value.as_widget(attrs={'class': arg}) editSession.html <div class="form-group"> <label for="exampleInputEmail2">Session Type</label> <span class="input-icon icon-right"> {{form.session_type|add_attr:"class=form-control"}} </span> </div> views.py class sessionpdate_view(UpdateView): model = Session fields = '__all__' template_name = 'myapp/editSession.html' success_url = '/sessionDetail/' -
I want to build a quiz app with multiple users
I want to create a multiple users quiz app with dashboards.Can You how to give models to built such a app. I want have multiple users who can take quiz and results saved to their dashboards. -
django.db.utils.OperationalError: (1091, "Can't DROP 'company_id'; check that column/key exists")
When I migrate, i always get it error. First, I created the table and then dropped it. Now when I created the table again. I am facing this issue. It also does not create the columns. Model.py class AssociateCompany(models.Model): user = models.ForeignKey(User, related_name="associate_user", on_delete=models.CASCADE) company = models.ForeignKey(Company, related_name="associate_company", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) It does not Create the column, user_id and company_id, and displays the folling error: django.db.utils.OperationalError: (1091, "Can't DROP 'company_id'; check that column/key exists") -
Can we create microservices in python without using any framework?
I have to write a microservice in python but without using any framework.Is there any way to write a microservice without using any python framework? If possible kindly share any resource which can help in my development process. -
Store output of a function in another function in Django
I have a function Packer whose output is I am trying to save in DispatchPlan like this: for i in range(len(truck_objects)): DispatchPlan.objects.create(owner=request.user, comments="Autogenerated", truck_type=open_object, truck_name=truck_objects[i], origin=k.split("-")[0], destination=k.split("-")[1], total_trucks=1, material_type='Non-Fragile', scheduled_date=item_date, offered_price=0, weight=item_weight_sum, status='Hold', etd=open_etd_temp, route_link=route_map, eta=item_date, route_distance=temp_distance, route_tat=temp, pk=new_quiz.id) where truck_objects is this: [<truck_name: Tempo 407 2500>, <truck_name: Tempo 407 2000>] but now there is another output from Packer i.e. master_values which contains the items packed in each truck. master_values [{<Truckdb: Truckdb object (3)>: [<ItemBatch: Chains & Chain Link Fence Fittings>, <ItemBatch: Chains & Chain Link Fence Fittings>]}, {<Truckdb: Truckdb object (2)>: [<ItemBatch: Chains & Chain Link Fence Fittings>, <ItemBatch: Chains & Chain Link Fence Fittings>]}] Now, how do I save this master_values in my DispatchPlan ? One way I could think of is nested loops such that I store the whole list against a truck by creating an ArrayField in my DispatchPlan model. Is there any other way I can store that data ? -
Add global prefix for Django URLs
Instead of using subdomains I would like to add subfolders like: burger.domain.com -> domain.com/organization/burger/ is there any way to add /organization/<name:str>/ globaly? -
How can I excute languages like python, c++,Java etc on my website built with Django?
I have deployed a website on Django and now I want to add a feature by which users can run, save and execute languages as stated above. Please suggest me a way for it. -
show ip camera live feed in django webpage
code in which cameafeedview is defined in the url section please help where i am wrong Opencv Live Stream from camera in Django Webpage tired this code also but no help def camerafeedView(request): return render(request,'camerafeed.html') def gen(camera): video = cv2.VideoCapture() video.open("rtsp://user:pass@IP") video.release() ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) while True: frame = jpeg.tobytes() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def camerafeed(request): return StreamingHttpResponse(gen(),content_type="multipart/x-mixed-replace;boundary=frame") <html> <head> <title>Video Streaming Demonstration</title> <h1>test</h1> </head> <body> <h1>Video Streaming Demonstration</h1> <img src="{% url 'camerafeed' % }}"> </body> </html> it show only html page but no live camaera feed ..please help where i am wrong here -
Django REST Framework - action GET serializer with form
I'm using last version of django and django rest framework. I'm trying to create a detail action for a viewset and can't achieve to get a form on django rest framework in order to pass extra parameters. In fact i normally can pass extra parameters if i override get_queryset but i would like to have a form to indicates api user which parameteres are available or not. So i tried to override get_serializer class if the action is "export" but it doesnt work (not called). Following the code i use for the moment which does not provide any form and parameters. @action(methods=['get'], detail=False, permission_classes=[IsAuthenticated, IsAdminUser], url_path='export', url_name='export') def export(self, request, pk=None): dataset = SectorTypeResource().export(self.get_queryset()) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="sector_types.csv"' return response The goal is not allow multiple export type and to allow user to filter on model dates for examples. My question is: It's possible to achieve this and if yes how to do this ? Thanks a lot