Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djongo model embedded data
I have to build a model on Django with Djongo connector to use it with mongoDB. I am parsing .nessus files (xml structure) with a python script and want to store it in the database with the following format: -Hostname -IP -Date Then the results for this workstation scan, so the following would be an array of results belonging to the above scan. -Plugin ID -Protocol -Port -Description So, my question is, how can I build a model on Djongo with this configuration making the results easy to query in the database with queries like show me the results with hostname = 'x' and getting the list or array of the results for this hostname. At the moment I tried with EmbeddedModelField but I can only store one result for each Scan/Hostname -
How can I get data from this xml and output in html with django
I have a HEX XML, I want to get data with python/django and output in a simple HTML page. I have read everything about xml but I can't figure it out hex.xsd This XML file does not appear to have any style information associated with it. The document tree is shown below. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:hex="http://hex.hasznaltauto.hu/ns" targetNamespace="http://hex.hasznaltauto.hu/ns" elementFormDefault="qualified"> <xs:complexType name="ar"> <xs:simpleContent> <xs:annotation> <xs:documentation xml:lang="hu" source="http://hex.hasznaltauto.hu/doc/ar/"> Vételár típusú mezők </xs:documentation> </xs:annotation> <xs:extension base="xs:string"> <!-- Megnevezés --> <xs:attribute name="megnevezes" type="xs:string" use="required"/> <!-- Nyers adat (Csak szám formázás és egységek nélkül) --> <xs:attribute name="nyersadat" type="xs:float"/> <!-- Kiemelt (kiemelt tipográfiai megjelenítés) --> <xs:attribute name="kiemelt" type="xs:boolean"/> <!-- ÁFA százalék (opcionális) --> <xs:attribute name="afa" type="xs:nonNegativeInteger"/> <!-- Bruttó összeg (opcionális) --> <xs:attribute name="brutto" type="xs:integer"/> </xs:extension> </xs:simpleContent> </xs:complexType> <xs:complexType name="altalanos"> <xs:simpleContent> <xs:annotation> <xs:documentation xml:lang="hu" source="http://hex.hasznaltauto.hu/doc/"> Általános mezők </xs:documentation> </xs:annotation> <xs:extension base="xs:string"> <!-- Megnevezés --> -
Update All records Django Orm
I want to update user_is_deleted to True in UserProfile Model whose user_company is 5. There are lots of users having same company id's class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE) user_dob = models.DateField(null=True, blank=True) user_phone = models.CharField(max_length=30, blank=True, null=True) user_image = models.ImageField(upload_to='user_profiles/', default='default_user.png',blank=True, null=True) user_created = models.DateTimeField(auto_now_add=True) user_is_deleted = models.BooleanField(default=False) user_deleted_at = models.DateTimeField(blank=True, null=True) -
Use Subprocess in a form action of a template
In a form action in a template, is there a way to run script ? <form action="{% subprocess.check_call(['python', 'myFile.py']) %}" method="post"> <input class="btn_ok" type="submit" value="Validate" /> </form> -
Setting up database replication using signals in django
I am trying to setup database replication in djnago. I have configured multi-db in settings.py So setting file look like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['DB_NAME'], 'USER': config['DB_USER'], 'PASSWORD': config['DB_PASSWORD'], 'HOST': config['DB_HOST'], 'PORT': config['DB_PORT'], }, 'tableau': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'taxonomy_v1_tableau', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': 5432, }, } I am able to read and write from both database like from myapp.model import People # writing to db People.objects.create(name='alok', location='India') # onto defalut db People.objects.using('tableau').create(name='alok', location='India') # onto replication db # reading from db People.objects.filter(name='alok') # from default db People.objects.using('tableau').filter(name='alok') # from replication db My requirement is to keep both database in sync(They should have same data). I want to keep both database in sync using djnago signals like django.db.models.signals.post_save and django.db.models.signals.post_delete For example if I am running People.objects.create(name='alok2', location='India2') Then such entry should get created in other database also. -
I there something i am doing wrong in below get_query method in below code. i want to override the get_queryset function but it is not rendering it
I want to serialize a model to json but the queryset function is not working as there is not synatax error i am unable to find the bug. class clientDetailAPIView(generics.RetrieveAPIView): def get_queryset(self): user_id = self.kwargs['pk'] campaign_id = self.kwargs['campaign_id'] if user.objects.filter(id=user_id, usertype=1).count() > 0: if Campaign.objects.filter(id=campaign_id).count() > 0: return campaign_allocation.objects.filter(campaign=campaign_id) serializer_class = CampaignAllocationSerializer -
ModuleNotFoundError: No module named 'basicapp'
I activated my virtual environment, started the project using django activate MyDjangoEnv django-admin startproject template_users django-admin startapp basicapp I also added basicapp to INSTALLED_APPS when i try to run python manange.py runserver i get an error ModuleNotFoundError: No module named 'basicapp' -
Dajgno 2.0 : Can we make another folder inside a view folder inside which we can keep a specific view file?
I used Python 3.7 Django 2.0 My Project Name : fusion My App Name : django_adminlte My App have one views folder and in this folder i have one folder and its name is desktop and in side one desktop.py file its views file specific for desktop which contain rendering crud functionality with html. issues is views normalization not working for views folder structure,I want Split views.py in several separated folder inside another separated folder due to lots of views files. I already do this things with model but unfortunately cant work with views folder. Path : C:\fusion\django_adminlte\views\desktop\desktop.py __init__.py from .desktop import* from .desktop_show import* desktop.py from django.shortcuts import render,redirect from django_adminlte.forms import EmployeeForm,DesktopForm def desktop(request): if request.method == "POST": form = DesktopForm (request.POST) if form.is_valid(): try: form.save() return redirect("/desktop_show") except: pass else: form = DesktopForm() return render(request,'inventory/desktop_index.html',{'form':form}) desktop_show.py from django.shortcuts import render,redirect from django_adminlte.models import Desktop def desktop_show(request): items = Desktop.objects.all() contaxt = { 'items':items, 'header': 'Desktop Inventory' } return render(request,'inventory/desktop_show.html',contaxt) -
Google App Engine very slow response time in file upload
I have a Django app running on GAE(Google App Engine) standard environment. I am uploading videos via my app to google cloud buckets (utilising dropzone on front end). The size of my videos are large so I am sending my file in chunks to GAE and then recreate and upload to GCS. It is working fine. My issues is the request to upload the chunks are taking a long time (15s for uploading a chunk of 1MB, I removed the processing of the chunk and still taking 15s) @login_required(login_url="/login/") @require_http_methods(["POST"]) def upload_chunks(request): try: file = request.FILES['file'] # upload_utils.upload_image_file(file); //Commented it out return JsonResponse({"status": True}) except Exception as e: return HttpResponseServerError(str(e)) Every Chunk Upload takes 15 sec and all of the time is spent in TTFB Also when increase my chunk size to let's say 8 MB the request get cancelled as it takes more than 30 sec. Please help!! -
Is there any function to display data as html content, i'm saving the data as html formats
I used summernote in my web page and getting the result from it has html tag. But when i tried to display as its not showing. I tried to use Parse data as HTML still not use. test.html <form action="{% url 'polls:gotopage' %}" method="POST"> {% csrf_token %} {{ form.content|safe }} <button type="submit">Submit</button> </form> <h3>Testing</h3> <p>{{ page.content }}</p> <div id="summernote"><p>{{ page.content }}</p></div> </form> <script> $(document).ready(function() { $('#summernote').summernote(); }); </script> I'm getting the data as raw data. No html style or changes. i want to make its look like html content. -
Django: ProtectedError exception handling is not working
I am trying to handle ProtectedError exception and try to post a custom error message in my template. def delete(self, request, *args, **kwargs): obj = self.get_object() get_success_url = self.get_success_url() try: obj.delete() messages.success(self.request, self.success_message % obj.__dict__) except ProtectedError: messages.success(self.request, "can't delete") return super().delete(request, *args, **kwargs) without ProtectedError it is sending me back to my list page with delete successfully message but for ProtectedError it is sending me to some generic error page with ProtectedError at /settings/currency/1/delete/ message. Thanks. -
Deploy django application without source code on server
We are creating a Django application which will be delivered in tar format to the end user, can we deploy it on the server using binary files(pyc in a more pythonic way or anything else). My ultimate target is to hide our source code from the client and some anti-pirate motives. My application use Django version 1.11, Python 3.5, uwsgi/nginx combo. I could see a similar approach in Angular to build in production mode with more security options, do we have similar options in Python Django. Please share your thoughts. -
I am trying to implement a choices option in models.py Countries to be selectable by user but I not able to display it properly
Following the example provided in Neomodel documentation I am not able to display choices in my form. class Person(StructuredNode): SEXES = {'F': 'Female', 'M': 'Male', 'O': 'Other'} sex = StringProperty(required=True, choices=SEXES) by using this example I get an error when Django is executed. packages/django_neomodel/init.py", line 122, in get_choices for choice, __ in choices: ValueError: not enough values to unpack (expected 2, got 1) Modifying the SEXES and specifying 'FF', 'MM' etc will allow the server to run but values appear as <option value="F">F</option> <option value="M">M</option> <option value="O">O</option> ``` I have used the following code in models. COUNTRY_CODE1=[('AF', 'Afghanistan (+93)'), ('AL', 'Albania (+355)'), ('DZ', 'Algeria')] ... ind_nationality = StringProperty(max_length=2,choices=COUNTRY_CODE1,label='Nationality') When this is populated in a browser the following is generated. <option value="A">F</option> <option value="A">L</option> <option value="D">Z</option> models.py class Person(DjangoNode): uid_person = UniqueIdProperty() ind_name = StringProperty(max_length=100 , label='Enter your First Name') ind_last_name = StringProperty(max_length=100,null=True, label='Last Name') ind_nationality = StringProperty(max_length=2,choices=COUNTRY_CODE1,label='Nationality') forms.py class PersonRegForm (ModelForm): class Meta: model=Person fields = ['ind_name','ind_last_name', 'ind_nationality'] widgets = { 'ind_name' : forms.TextInput(attrs={'size':50}), 'ind_last_name' : forms.TextInput(attrs={'size':50}), 'ind_nationality' : forms.Select(), } app_label = 'reg' class PersonRegView(generic.FormView): template_name='reg/personreg.html' form_class=PersonRegForm success_url = 'index' I am expecting the following result <option value="AF"></option> -
Uploading data from API to a Postgres DB just stops with no error messages
The strange behavior began when I've switched to the PostgreSQL, used sqllite3 before and there is were no problem like this. Just now recreated the sqllite3 db from the current state of my code. Just turned off the JsonFields that I used for one of the scripts to load to the Postrgre base. Still works. Loading to the Postgre just stops at a random point on a random report, with no messages, command line do not react to the Ctrl + K command. I've checked the Postgre server, it's running all the time. When I stop the service after this "freezing" of the loading to the DB in the command line, sometimes it throws an error, sometimes is not and just nothing happening. I need to reopen the command line. I’ve tried to record a screen video to illustrate this behavior. But unfortunately, my screen recording software do not work properly. You can see the code below, I'm not sure there is a problem in the code. Maybe something else needs to be done with the PostgreSQL setup? On the first day of using Postgre, I was able to load the script fully. There is a screenshot with an example … -
How to perform star rating using django and ajax?
I want to perform a star rating in my blog application for better user experience...But couldn't perform in django using ajax...I basically don't want to use any third party application for my blog project...I want to do manually using django and ajax... This is my blog model: class Blog(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) date = models.DateTimeField(default=datetime.now) blog_title = models.CharField(max_length=255,unique=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True) description = models.TextField() blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True) category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='blogs') blog_views = models.IntegerField(default=0) Any idea anyone how to perform this? Thank you in advance -
Float Number Ordering - Django-tables2
I try to order by accessor a django-tables2 table on a float value column. tables.py class GeneTable(tables.Table): float_number = tables.Column() def render_float_number(self, value): print(float(value)) return float(value) input on the table 100.0 99.65 100.0 81.76 97.88 96.96 97.57 69.87 97.87 result after sort by clicking on accessor 100.0 100.0 69.87 81.76 96.96 97.57 97.87 97.88 99.65 How solve this sort problem ? -
Django model save override without super(Model, self).save(*args, **kwargs)
I have a model in Django. From this model generating a list and add. Now I have to override save action to not saving to DB but making a request to rest api, is local service. After success request new record is created in the database and it's accessible from Django. I override save method in the model like this: def save( self, *args, **kw ): // my http request On the end, I don't call super(Model, self).save(*args, **kwargs). Post request is created correctly, but I don't know how to make that the form behave in this same way like when normal save is used. Now save action hanging up and after a while I'm receiving http error 502 What should I call on the end of this method, or what I should return from it? -
Calling a function from html
html: <button type="button" class="btn btn-primary">Notifications <span class="badge badge-light"></span> </button> python: def notif(): not_num = False if count > 0: return count else return not_num def count(): return 8 Can i get a way to call "notif" function into html body? What i want is to do an "if" inside a html button that tells me how many notifications i have and if i don´t have any, it doesn´t show me anything. -
Specify Django proxy model in admin foreign key
In Django 1.11, I have a model Friend, and a proxy model Relative: class FriendManager(models.Manager): def get_queryset(self): return super(RelativeManager, self).get_queryset().filter(is_relative=False) class Friend(models.Model): # Model fields defined here objects = FriendManager() class RelativeManager(models.Manager): def get_queryset(self): return super(RelativeManager, self).get_queryset().filter(is_relative=True) class Relative(Friend): class Meta: proxy = True objects = RelativeManager() def save(self, *args, **kwargs): self.is_relative = True super(Relative, self).save(*args, **kwargs) I also have a model FriendPortrait, which has a foreign key field friend: class FriendPortrait(models.Model): friend = models.ForeignKey(Friend) And a proxy on that: class RelativePortrait(FriendPortrait): class Meta: proxy = True Now, I want the detail view for RelativePortraits to only show relatives in the drop-down for friend. admin.py: @admin.register(RelativePortrait) class RelativePortraitAdmin(admin.ModelAdmin): fields = ('friend') def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'friend': kwargs['queryset'] = Relative.objects.all() return super(RelativePortraitAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) This works, in that only relatives are displayed in the friend drop-down. However, when I try to save a portrait, Django admin gives me a validation error: friend instance with id 14 does not exist. How can I specify that I want to use a proxy model for my foreign key in the RelativePortraitAdmin? -
How to fix NoReverseMatch at /
I am getting the error NoReverseMatch at / when I am trying to link my article to article detail page. NoReverseMatch at / Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['article\/(?P[0-9]+)\/$'] {% for articles in object_list %} <div class="article"> <div class="article-title"> <a href="{% url 'article-detail' pk=article.pk %}"></a> <p class="p-title">{{ articles.title }}</p> </a> </div> <div class="article-content"> <p>{{ articles.content }}</p> </div> </div> <hr> {% endfor %} path('', views.HomeView.as_view(), name='index'), path('article/create/', views.ArticleCreateView.as_view(), name='article-create'), path('article/<int:pk>/update/', views.ArticleUpdateView.as_view(), name='article-update'), path('article/<int:pk>/', views.ArticleDetailView.as_view(), name='article-detail'), ]``` -
Django - Implement Postgres Similar To
Very simple. I need a IN with CaseInsensitive and Full Like. Example Search Probe: "Crit,Norm" I need to find all of this rows with column's value: "critical, Crit, crit, normal, Normal" PostgreSql Searching on google, I found Postgres function "similar to" lower(column_name) similar to '%(crit|norm)%'; Is there a way to make it in Django? -
maintain session by authenticating fields on a custom table Django
I have a table in my database and I want to maintain session, login and logout functionalities based on fields of that table without using Django's default User table. Is that possible? if yes, how? -
Where are legacy references to the database tables of django models are hidden?
I am restructuring the postgresql database: renaming tables, changing foreign keys and linking the new and modified tables to the django models. But the old reference to the table historical_models_liveanalogvalue and an old attribute ts name appears in one of the models (maybe in all of them, but the code exits with an error). Django native migrations are out of the question due to some internal reasons even though it could have prevented this problem. I had to do inspectdb, based on that, fix the models.py and perform migrations with --fake-initial to keep the project running. Where else could the old reference be found and deleted? I searched for all the appearances of the string with the old table name but could not find anything. I tried to put the table name in double quotes, but also did not work. The new model in the models.py is the following: @architect.install('partition', type='range', subtype='date', constraint='day',column='source_timestamp') class LiveData(models.Model): """The base class for live models.""" # Timestamp when the sample was created. source_timestamp = models.DateTimeField( db_index=True, blank=False, null=False) class Meta: """Meta specification.""" managed = False db_table = 'livedata' The new 0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( … -
Can't connect to MySQL server in Django 2.x.x Python AppEngine
I am trying to use cloud SQL / mysql instance for my APPEngine account. The app is an python django-2.1.5 appengine app. I have created an instance of MYSQL in the google cloud. I have added the following in my app.yaml file copied from the SQL instance details: beta_settings: cloud_sql_instances: <INSTANCE_CONNECTION_NAME>=tcp:<TCP_PORT> I have given rights for my appengine project xxx-app's owner xxx-app@appspot.gserviceaccount.com the Cloud SQL Client rights. I have created a DB user account specific for the app XYZ which can connect to all hosts (* option) My connection details in settings.py are the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my-db', 'USER': 'appengine', 'PASSWORD': 'xxx', 'HOST': '111.111.11.11', # used actual ip 'PORT': '3306' } } I have also tried as per https://github.com/GoogleCloudPlatform/appengine-django-skeleton/blob/master/mysite/settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/<your-project-id>:<your-cloud-sql-instance>', 'NAME': '<your-database-name>', 'USER': 'root', } } I cannot connect from the local as well. However, if I do a Add Network of my local IP and then try to connect the local connects. THe app runs fine locally after adding the lopcal IP Address CIDR notation. My problems: I am unable to connect to the Cloud sql without adding the AppEngine assigned IP Address. It gives … -
How to show Exceptions custom message on Django template
I am using messages to show success, info and warning message from Django classed based views to Django template. def delete(self, request, *args, **kwargs): obj = self.get_object() success_url = self.get_success_url() try: obj.delete() messages.success(self.request, self.success_message % obj.__dict__) return super(CurrencyDeleteView, self).delete(request, *args, **kwargs) except ProtectedError: messages.error(self.request, "can't delete this category") Now I am confused how to show that ProtectedError message on the template and what to return after that message.error.