Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.DatabaseError using djongo to connect mongoDB
Everything was working fine up until i decided reset my migration ... when i try to make new migration it gives me django.db.utils.DatabaseError, Can't seems to figure out the problem. I'm using MongoDB as my database. Operations to perform: Apply all migrations: account, admin, articles, auth, authtoken, contenttypes, sessions, sites, socialaccount Running migrations: Not implemented alter command for SQL ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL Applying articles.0002_article_author...Traceback (most recent call last): File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 783, in __init__ self._query = self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 875, in parse raise e File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 435, in parse self._add(statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 598, in _add raise SQLDecodeError(err_key=tok.value, djongo.exceptions.SQLDecodeError: Keyword: int Sub SQL: ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL FAILED SQL: ('ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL',) Params: ([],) Version: 1.3.3 The above exception was the direct cause of the following exception: Traceback (most recent … -
How to communicate between 2 Django separate projects?
I have two separate Django projects and want to locate them in 2 different servers. Is there a way to communicate with each other? In one projects I need to be able to upload a file and send it to second project for processing. -
upload a file in django rest framework to s3 in python
I am bit new to boto3 and django rest framework.I have a django rest framework project in some folder,and I need to upload the image from (other folder,say D drive/someFile.PNG) I am trying to access the location of it to send to a upload function of s3,But when add the location of image file to the fucntion it says it cannot find the image url,can anyone help me with this?!Thanks in advance. Here is the upload fuction of s3 for the reference def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False """ # If S3 object_name was not specified, use file_name if object_name is None: object_name = file_name s3_client = boto3.client('s3') try: response = s3_client.upload_file(file_name, bucket, object_name) print('s3 response', response) key = file_name region = 'ap-south-1' url = f'https://{bucket}.s3.{region}.amazonaws.com/{key}' print('url test', url) except ClientError as e: logging.error(e) return False return True In the above file_name, if I pass the image name from other folder it is giving me the 500 internal server error saying that it cannot … -
How to run multiple django applications on IIS server?
I am new in django that runs on IIS server. I have manage to set up server that one django application/site is runnging..now I want to add another django application/site to this server. I cant find anywhere the sample web.config how to do that.. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <staticContent> <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" /> <mimeMap fileExtension=".config" mimeType="application/xml" /> <mimeMap fileExtension=".pdb" mimeType="application/octet-stream" /> </staticContent> <handlers> <add name="Python FastCGI" path="/page1/*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python27\python.exe|c:\python27\lib\site-packages\wfastcgi.pyc" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="page1.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\page1" /> <add key="DJANGO_SETTINGS_MODULE" value="page1.settings" /> </appSettings> </configuration>` This is my config so far, how can I add another django site that will be available on URL/page2/ ? -
Show value to HTML just like how value gets display in CMD prompt when executes print() in python
I am working on speech recognition by following this tutorial and implementing in Django. I'm wondering the way we execute print("Listening...") and print("Recognizing...") for user to understand when to speak in CMD prompt, is it possible to send value (Listening, Recognizing) in HTML page each time when user speaks something ? def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source) audio = r.listen(source) print(audio) try: print("Recognizing...") query = r.recognize_google(audio, language ='en-in') print("User said:",query) except Exception as e: print(e) print("Unable to Recognizing your voice.") return "None" return query -
How do I add Manage.py ClearSessions to crontab to automatically clean up expired sessions?
How do I add Manage.py ClearSessions to crontab to automatically clean up expired sessions? django manage.py clearsessions -
Is a Django model with parents that have a parent and child relationship among them?
To elaborate, I wish to set up a model where a blog post can have a like and a comment on the post can also be liked. I could build two models, post_like and comment_like where they would both be children of blog post and comment respectively. Is there a way through which I could implement the above functionality with a single model? Something more generic. Where 1 model can be used to implement the like functionality? class Like(models.Model): post = models.ForeignKey(post..., default = None) comment = models. ForeignKey(comment...default = None) like_type = models.CharField(choices, default = None) -
How to access Django's single set item?
I ran the following code in python shell: from main.models import ToDoList ls = ToDoList.objects.all() ls output: <QuerySet [<ToDoList: First List>, <ToDoList: Second List>]> but when I use: ls = ToDoList.objects.get(id=1) it says: main.models.ToDoList.DoesNotExist: ToDoList matching query does not exist. -
Issuing long commands in container deployments k8s
I want to issue django management commands via kubernetes deployment.yaml in a container (like command: ["/bin/sh","-c"] args: ["command one; command two && command three"]) on startup for user object creation such as python manage.py createuser --last-name xyz --email ij@test.com .... Since the user object I want to create has a large number of properties (almost 20), the command may become very long. Is there a better way of achieving this? -
Best way to store cv2.imencode information from Django into a Postgresql database table
I am performing object detection on live/recorded video feed using PyTorch Yolo algorithm. The inference output cv2.imencode('.jpg', infered_image)[1].tobytes() from machine learning model is feed into the Django view using StreamingHttpResponse into an img tag. This all works fine. Code Snippets. **views.py** def gen(camera): while True: with torch.no_grad(): frame = camera.detect() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera(source=r"C:\Users\Downloads\aircraft.mp4")), content_type='multipart/x-mixed-replace; boundary=frame') Output from **detect.py** class VideoCamera(object): def __init__(self): ... def detect(self): ... ret, jpeg = cv2.imencode('.jpg', im0) return jpeg.tobytes() Now I want to store this inferred images data into a database table. What is the best approach to store such data? Use ImageField or BlobStorage or any better approach. I am ok to store ``cv2.imencode('.jpg', infered_image)[1]` or the entire bytes information to database. -
Do you know why pip list shows one installed version but then python shell shows another?
I have created a virtual environment. I activate it with conda activate my_venv. I do pip list and check statsmodels version. result -->0.12.1 I do pip freeze. The same result. I get inside of the python shell and execute the next code: import sys import statsmodels print(sys.prefix) print(statsmodels.__version__) the output: '/home/skootik/anaconda3/envs/prodenv' '0.10.2' Does anybody know why? Thank you in advance -
aggrigate on many to many fields
i want to create a report for sum of duration that a adviser advise on this month. my model : class Adviser(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='adviser') patients = models.ManyToManyField('patient.Patient', through='adviser.AdviserPatient', related_name='advisers') class AdviserPatient(models.AbstractBaseModel): adviser = models.ForeignKey('adviser.Adviser', on_delete=models.PROTECT, related_name='adviser_patient') patient = models.ForeignKey('patient.Patient', on_delete=models.PROTECT, related_name='adviser_patient') duration = models.SmallIntegerField() assign_date = models.DateField(auto_now_add=True) release_date = models.DateField(null=True, blank=True) class Patient(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='patient') my query : ended_advise_this_mouth = Adviser.objects.annotate( total=Case(When( adviser_patient__release_date__gte=start_of_month(), adviser_patient__release_date__lte=end_of_month(), then=Sum('adviser_patient__duration')), default=Value(0), output_field=IntegerField())) but with this query i get response like that : <QuerySet [<Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [2 vahid imanian]>]> as you see adviser 1 repeat 6 time with separate total . when i use method values('id') or use distinct() not effected in result . my db is mysql and cant use distinct('id'). please help me . is there any way to use django-rest-framework serializers for this queryset? -
Deleting newline by python (Django) by taking string by textarea in html but the answer is wrong. WHY?
print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" print(djtext) for char in djtext: if char !="\n": analyzed=analyzed + char print(analyzed) suppose newlineremove is on and the input in textarea(html) is: dam dam djtext=request.GET.get('text','default') OUTPUT: on dam dam dam dam dam but it should have been: on dam dam dam dam damdam -
Use condition in update_or_create of django (DRF)
Here is my Serializer for API: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'name', ] def create(self, validated_data): from django.db.models import F, Case, When instance, created = self.Meta.model.objects.update_or_create( merchant=validated_data.pop('merchant'), client_id=validated_data.pop('client_id'), defaults={ 'name': Case( When(is_synchronizable=True, then='test'), default=F('name') ) } ) return instance I want to update the name just when is_synchronizable is True. But I get this error: django.core.exceptions.FieldError: Cannot resolve keyword 'test' into field. -
Django REST api Parent and child componet to use react js form submit as it is DRA?
guys i am beginner React js. i want get as it is rest API drop-down list box have to create in react. so how to do it ? could you guy please give way method -
How to create slug of many to many fields in django?
I want to make slugs on post save for my model using three fields one charfield and two ManytoMany Fields but getting error during saving. Here is my code: Heading ##class product(models.Model): id = models.AutoField(primary_key=True) image = models.ForeignKey(all_images, verbose_name='Product Images', on_delete=models.CASCADE, related_name='proimages') ProductName = models.CharField(max_length=200, null=False,default="None", blank=False,verbose_name="Product Name") CategoryName = models.ManyToManyField(category,related_name='procat', blank=False,verbose_name="Category Name") SubcatName = models.ManyToManyField(subcategory,related_name='prosubcat', blank=False,verbose_name="Sub-category Name") description = RichTextUploadingField(blank= False,verbose_name="Description") price = models.IntegerField(default=100, null=True, blank=True, verbose_name='Price') slug = models.SlugField(max_length=55, blank=True, null=True) def get_slug(self): slug = self.ProductName try: for items in self.SubcatName.all(): slug +=items.name try: for items in self.CategoryName.all(): slug +=items.CategoryName except: pass except: pass return slugify(slug) def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_slug() super(product, self).save(*args, **kwargs) -
How can I see all possible attributes of an context variables in django templates
I am trying to use double model form at once in one single view, I am using django-betterforms to merge those, It merged all fields from two model in one single form. I know I can use different class and id to separate them, But I can't extract them in template form, like {{ form }} it will place full form in template, I can render all field like this {% for field in form %} {{ field }} or anything {% endfor %} My question is how can I know all the possible attributes of this field like {{ field.* }} *=anything kind of dir(field). This is a problem I have facing but what will be solution to find all attributes or separate two forms in two side. Basically I need to separate two model, those will save in same time with same view but in front-end those will be different. Thanks in advance!!! -
Post gis raw query returns empty set on st_asmvt
I am trying to generate dynamic mvt tiles using django. I used the sql query given in the documentation to generate the tiles. I changed the z,x,y as per my requirements. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon WHERE ST_Intersects(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; This gives empty result. But if i only run the following query it returns the results: SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon And if i try to run the following query it again returns the empty set. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; -
How to upload gist(CSV) file to Django app database?
Good day! I need to upload info from gist file(Myfile.CSV) to my Django app database? Can anybody give me suggestion how to do it more correctly? I have gist file which is located on github. It's a csv file wich containes 3 columns(number, name, colour) and several rows. So I need to upload(save) to existing Django project info from this file and after it change names of columns to different one. -
AttributeError: 'WindowsPath' object has no attribute 'endswith'
When I run my project this error comes. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\checks.py", line 9, in check_finders finder_errors = finder.check() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 81, in check if prefix.endswith('/'): AttributeError: 'WindowsPath' object has no attribute 'endswith' -
How to pass a variable value in Django template URL name?
I need to pass the variable value in the Django template URL name. At first, I want to query the URL name from the database then the query URL name-value use in the Django template like as view.py: def user_home(request): user = request.user role = user.employinfo.designation element = role.sbtitleelement_set.all() context = { 'sb_title_element':element, } return render(request, 'home/index.html', context) Template: {% for element in sb_title_element %} <li class="nav-item"><a href="{% url 'element.url' %}" class="nav-link">{{element}}</a></li> {% endfor %} Here "{% url 'url-name' %}" i want to use URL name form {% url 'element.url' %}. How is it possible? Please help me to solve the problem.... -
How to write search query that gets input from separate fields in Django?
I need to create a search query that takes input from these fields. I would appreciate actual code example. I can query using one search field. But my project requires separated fields. Thank you. enter image description here -
Multiple Django services + centralised user authentication, management and provisioning
I have multiple running Django services, each with their own databases, and I'm trying to implement an authentication solution to achieve the following: Single Sign On. e.g. user can login to an authentication service at accounts.example.com, and when they browse to service-a.example.com or service-b.example.com, they will automatically be authenticated without any further login action. Centralised User Management. e.g. creating, updating an deleting accounts will all be done at accounts.example.com by an admin account Ability to provision service resources to new users even before the user's first login to the service. e.g. With an admin account, I created UserA at accounts.example.com, and then in service-a.example.com I would want to be able to assign tasks to UserA even if UserA has not first logged in to service-a.example.com yet. I have looked through and experimented with a number of SSO solutions such as OpenID, SAML, CAS, but it seems that with any of them I can't seem to achieve Point #3. This is because even if the new user account is created in the Identity Provider, the user object will not exist in the Django service until the user first login to the Django service (which only then the user object will be … -
What is the maximum length of TextField in django while using PostgreSQL
i wanna known what is the maximum length of TextField in django models while using PostgreSQL.. I just know Mysql uses the longtext data type to store the content, which can hold up to 4 Gigabytes but i wanna know what is the maximum length of TextField in django models while using PostgreSQL and if can increase it ? -
crispy form field type attribute ignored
I am trying to use crispy forms in my django app and I can not seem to get the type attribute to set on a field. #forms.py class ReminderForm(ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.helper=FormHelper() self.helper.layout = Layout( Fieldset('Reminder', Row( Div(Field('message'),css_class="col"), ), Row( Div(Field('messagetype'),css_class="col-md-6"), Div(Field('account'),css_class="col-md-6"), ), Row( Div(Field('reminddate',type="date"),css_class="col-md-6"), Div(Field('duedate', type="date"),css_class="col-md-6"), ), ) ) class Meta: model=Reminder exclude=['sentdate','confirmdate','completedate'] my modal form {% load cms_tags crispy_forms_tags %} <div class="modal fade" id="{{formid}}" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{title}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form > {% crispy form %} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> rendered html for the inputs below show reminddate and duedate style with type="text" <div class="modal-body"> <form> <fieldset> <legend>Reminder</legend> <div class="form-row "> <div class="col"> <div id="div_id_message" class="form-group"> <label for="id_message" class=""> Message </label> <div class=""> <textarea name="message" cols="40" rows="10" class="textarea form-control" id="id_message"></textarea> </div> </div> </div> </div> <div class="form-row "> <div class="col-md-6"> <div id="div_id_messagetype" class="form-group"> <label for="id_messagetype" class=""> Messagetype </label> <div class=""> <select name="messagetype" class="select form-control" id="id_messagetype"> <option value="">---------</option> <option value="email">Email</option> <option value="sms">Text Message</option> <option value="internal">Internal Website</option> </select> </div> </div> </div> <div class="col-md-6"> <div id="div_id_account" class="form-group"> <label for="id_account" class=""> Account </label> …