Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ORA-01465: invalid hex number in python django
I'm trying to upload multiple files in oracle 11g database using python django. Here's my view for filecol in request.FILES.getlist('file'): filename = filecol.name filetype = filecol.content_type fileblob = filecol.read() FileRecord.objects.create(O_FILE_ID=oID, FILE_NAME=filename, FILE_TYPE=filetype, FILE_BLOB=fileblob, DATE_UPLOADED=datetime.datetime.now().replace(microsecond=0)) Then I received this error message return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-01465: invalid hex number -
Getting title metadata given website url in python
I'm looking to achieve this using beautiful soup. Currently I'm able to pull og:title from a webpage. What if no og:title is given? Is there a way to identify the title and display that? -
How don't change '/media/' on heroku after "git push ..."
Help me please. I have django app on Heroku. I want that after '$ git push heroku master' folder '/media/' on Heroku don't change. Thank you. -
How to call in django index.html fle for "GET" "POST" method for get data from id (fields)?
In django I have create query like wise if someone want information: In district parameter select Pune, then output gives data for pune district only. for example : http:127.0.0.1/api/?district=Pune htt:127.0.0.1:8000/?crop = groundnut and so on. Next,I want to create a Html page for my starting django page(index.html) if I runserver http:127.0.0.1:8000/ display my html file , where Our models fields(paramter) is id and then user submit the question "if" condition will be trigger and searching information for that parameters. like wise: District = __________ submit gives data only for selected district name only also Crop = ______________ submit gives data only for selected crop name only likewise run this query http:/api/?crop=groundnut if user choose crop name is groundnut, if use choose crop name is guava, then http:/api/?crop=guava query will be run. So,now I want to create index.html file multiple parameters works.(AND query will apply) http:/api/district=Pune&crop=groundnut So, I want to create html page which call to this query and its show me this type Distrcit : ________ Crop : __________ submit here is my models.py from django.db import models from mongoengine import Document, fields class Tool(Document): crop = fields.StringField(required=True) district = fields.StringField(required=True) def __str__(self): return self.crop def save(self,*args, **kwargs): super().save(*args, **kwargs) … -
Ajax call on django show 2 navbar
I have a html template where the page reloads div after a few seconds, everything is working correctly but the navbar is duplicating itself twice Here is my html code with the ajax request {% extends "Index/header.html" %} {% block content %} <div id ="table"> <table style="width:100%"> <tr> <th>User Name</th> <th>Status</th> <th>Total Data</th> <th>Total Verified</th> <th>Total Pending</th> <th>Verified Today</th> </tr> <tr> {% for obj in users_list %} {% if obj.username == 'Agent1' %} <td>{{ obj }}</td> <td>{% if obj in online_list %}online{%else%}offline{% endif %}</td> <td>{{Agent1_total}}</td> <td>{{Agent1_total_verified}} </td> <td>{{Agent1_total_pending}}</td> <td>{{Agent1_total_verified_today}} </td> </tr> {% endif %} {% endfor%} <tr class="seperator"></tr> <tr> <td>Total</td> <td>Null</td> <td>{{Agent1_total}}</td> <td>{{Agent1_total_verified}} </td> <td>{{Agent1_total_pending}}</td> <td>{{Agent1_total_verified_today}} </td> </tr> </table> </div> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> function auto_load(){ $.ajax({ url: "/users/#table", success: function(data){ $("#table").html(data); } }); } $(document).ready(function(){ auto_load(); //Call auto_load() function when DOM is Ready }); //Refresh auto_load() function after 10000 milliseconds setInterval(auto_load,20000); </script> {% endblock %} Why is it happening what am i doing wrong? -
get_object_or_404 while using multi-table(?) Inheritance in Django
Currently working on Django 1.8, MySQL and South: I recently starting working with inheritance and Django models. I actually have two questions in regards to inheritance with Django models. Wondering if anyone has run into an issue where running get_object_or_404 from django.shortcuts yields 404 with the message no matches found, but writing the query normally using model.objects.get(pk=###) will yield a single answer. Similarly, if I use a foreign key with a related name to make a query, the query doesn't seem complete, and objects are missing. I want to emphasize that the model we are inheriting is not an abstract model. Using the code below as a sample: from django.shortcuts import get_object_or_404 Car(models.Model): name = models.CharField(null=True, blank=True, default=None,) trunk_size = models.IntegerField(default=0) fleet_leader = models.ForeignKey("Car", related_name='car_fleet', null=True, default=None) class Meta: verbose_name = "Car" verbose_name_plural = "Cars" Bigcar(Car): extra_storage_size = models.IntegerField(default=0) class Meta: verbose_name = "Car" verbose_name_plural = "Cars" So if I make the query: get_object_or_404(Car, pk=123) Assuming that the Car data entry with row or primary key 123 exists, I would not get any results, however the entry Car.objects.get(pk=123) Would yield a result. As for the second issue I'm talking about: xcar = Car.objects.get(pk=123) Car.objects.get(fleet_leader=xcar) would provide expected results, with every … -
How to get the file from multiple file upload using ajax with python django?
I have a project that requires uploading of documents. I don't know why the files turns empty when submitting in ajax going to my views in django. Here's my code template <div> <input type="file" name="userfile" id="userfile" multiple/><br/> <span class="btn btn-default btn-xs" onclick="btnUpload();">Upload</span> </div> ajax var form_data = new FormData(); form_data.append('userfile', $('input[type="file"]')[0].files) form_data.append('csrfmiddlewaretoken', $('input[name=csrfmiddlewaretoken]').val()); $.ajax({ url:"/onlinerpta/register_doc/", data:form_data, contentType: false, processData: false, type:'POST', success: function(msg){ bootbox.alert(msg.feedback); } }); views for userfiledata in request.FILES.getlist('userfile'): f = userfiledata.FILES['userfile'] print (f) It returns f='' on my output. -
how i can get views count on every searched videos using YouTube API v3 only
i am working on youtube api and searching videos by keyword, everything is working fine. but i need to add views count on every singe videos. how i can do that by hitting single api. because for getting views count i have hit another api with particular videoid , here is my code. def search_video(request): response = {"status": False, "errors": []} query = request.POST.get('q', '') result = 5 data = requests.get("https://www.googleapis.com/youtube/v3/search?q=%s&part=snippet&key=%s&maxResults=%s" % (query, settings.DEVELOPER_KEY, result)) if data.ok: response["result"] = data.json() response["status"] = True return HttpResponse(json.dumps(response)) -
Django channels and docker-compose error
When running runserver via docker and docker-compose, I get this error and I cannot connect to django: django_1 | 2017-01-09 08:24:44,328 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive django_1 | 2017-01-09 08:24:44,329 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive django_1 | 2017-01-09 08:24:44,331 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive django_1 | 2017-01-09 08:24:44,331 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive django_1 | Unhandled exception in thread started by <function wrapper at 0x7ff06bee5d70> django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper django_1 | fn(*args, **kwargs) django_1 | File "/usr/local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 84, in inner_run django_1 | Performing system checks... django_1 | django_1 | System check identified no issues (0 silenced). django_1 | January 09, 2017 - 08:24:44 django_1 | Django version 1.10.4, using settings 'backend.settings' django_1 | Starting Channels development server at http://0.0.0.0:8000/ django_1 | Channel layer default (asgi_redis.core.RedisChannelLayer) django_1 | Quit the server with CONTROL-C. django_1 | ws_protocols=getattr(settings, 'CHANNELS_WS_PROTOCOLS', None), django_1 | File "/usr/local/lib/python2.7/site-packages/daphne/server.py", line 41, in __init__ django_1 | ''' % self.__class__.__name__) django_1 | DeprecationWarning: django_1 | The host/port/unix_socket/file_descriptor keyword arguments to … -
Catching exception if a db exists but collection does not using django-mongodb
I am using django-mongodb engine for a django app that have multiple databases. Lets say I have a model named as Profiles. For selecting model values from correct db, I query it liked Profiles.objects.using(db_name). There are two cases for catching exceptions here. a) Db does not exists. b) Collection in that db does not exists for this model. Some exception at the time of db creation can lead to this state. What is the best way to handle exceptions in case of these two conditions. I need to catch both exceptions separately to log different messages. -
Django How to stop the execution of a function
I am trying to call a python function by Ajax. I want to stop the execution of that function. I have tried to refresh the page but it doesn't stop. When I stopped the Django server then it get stop. Here some code: This Call call HTTP request class ScrapData(): @classmethod def search_status(self, urls_list): for url in urls_list: r = requests.get(url) text = r.text #... return 1 Calling this view by Ajax class SearchData(View): def get(self, request, *args, **kwargs): urls_list = []; response = ScrapData().search_status(urls_list) return HttpResponse(response) I want to stop the function. How can I do this? Thanks -
pass all fields of model in django filter backend
is there any way in which we can pass all the fields of a model to django filter backend without explicitly passing the names of fields in search_fields and filter_fields i have made a generic viewset which serializes all the fields of the model passed to it, but i am facing problem in applying generic filters to it for eg, class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.SearchFilter,) search_fields = ('username', 'email') in the above code, we have explicitly passed search_fields but in my code, i can't pass the fields explicitely as everytime different model may be passed. -
How to avoid httpd restart/relaod (mod_wsgi) on adding/deleting a tenant
In our multi-tenant architecture (apache, django, mysql) For each new tenant we create, we add a conf file(/etc/httpd/conf.d/) e.g., customer1_http.conf We tried mod_wsgi, touch wsgi(mod_wsgi), but Apache able to pick the newly added tenant (unless we reload) WSGISocketPrefix run/wsgi WSGIDaemonProcess customer1.com processes=2 threads=15 display-name=%{GROUP} WSGIScriptAlias / /opt/org/site/dc/customer1_wsgi.wsgi Is there any better alternative (other than restart/reload) to make Apache know about the newly added/removed conf file. -
Common custom validation for DRF and Django admin
I have user table in which have to put unique email constrain on staff users and unique phone constrain on non staff user. Now I want to maintain this constrain in DRF API and in Django admin, how to achieve this without code duplication. As I see from DRF 3.0 onwards, all validations are performed explicitly for serializer (If I have overwritten unique_validation or clean method to perform conditional validation, I have to write this custom validation separately for serializer as well) so how to write a custom validation that works both for DRF API and Django admin without code duplication ? -
MySQL: django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'") with correct username and pw
I have django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'") when using mysql. The username and pw are correct: DB_HOST = '127.0.0.1' DB_USER = 'root' DB_PASSWORD = '' I can log into mysql as root: $ sudo mysql -u root Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 16 But not as cchilders: $ mysql -u root ERROR 1698 (28000): Access denied for user 'root'@'localhost' This may contribute to the problem. Last time I installed mysql this didn't happen, so it doesn't make sense to me. I have the client fine: $ pip3 freeze Django==1.10.5 mysqlclient==1.3.9 How can I allow mysql to be run by my normal user, so I can run django in the terminal? thank you -
mysql and gunicorn open connections at the same port
SOME BACKGROUND: I have created a django app and I am at the point where I want to deploy it. I have looked at multiple options including wsgi but since the new mac os update came about, I can not install mod_wsgi because I do not have apxs or apxs2 on my computer, (Some discussion on web about rights to write in files, If you know more and would like to explain, please do.) However, I looked into other options to try to deploy the app and I want to use Heroku. I have followed the dev guide for Django deployment until I reached the part where I test using "heroku local web". THE ISSUE The problem stems from here because the local mysql server uses the same port that the gunicorn is also trying to use. I have found similar posts on stackoverflow about 'connections in use' but none have shown how to change ports for gunicorn. I have found some open ports available on my localhost but everytime I try to change the mysql ports to those, the connection times out. Therefore, I would like to know how to change the port the Gunicorn connects to so it … -
Django - Multiple apps for management different users extending django-allauth
to Django newbie writing ... I'm trying to manage different user types with separated apps for a quotation system for printers (school project); My user types would be A) Printer profile and B) Customer profile. On each profile I just extend User for both apps from my users app (django-allauth, using django-cookicutter template for my project). My question is: am I misunderstanding django app design philosophy. This post should suggest same user app with profile class for user types. Would this be the best approach for my achievement? Thanks. -
Django unable upload media files
I'm unable to save and load files to the media folder. There are nor errors during the save process. The problem only with FileField anything else saves correctly. Here is my code. #Model class Product(models.Model): image1 = models.FileField(upload_to='product_images',default='1.jpg', blank=False, null=False) #Form class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image1'] #view.py def CreateProduct(request): context ={} if request.method =="POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("app:edit-products") else: form = ProductForm() return render(request,"SisianShop/create.html", context) #HTML From <form class="form-horizontal" action="" method="post" enctype="multipart/form-data" > {%csrf_token%} {%include 'SisianShop/includes/form_templates/form_template.html'%} <div class="form-group"> <div col-sm-offset-2 col-sm-10> <button class="btn btn-success">Submit</button> </div> </div> </form> #settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" Everything seems ok. Any Suggestions how ti fix this? -
Sandstorm - postgresql not running
I'm trying to port sayIt, a django app with postgresql as a sandstorm app. I have an instance running on Ubuntu, and using raw packaging to run it in dev mode. However, an error occurs as below: ...** SANDSTORM SUPERVISOR: Starting up grain. Sandbox type: userns Unhandled exception in thread started by Performing system checks... System check identified no issues (0 silenced). Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check_migrations() File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 168, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 119, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python2.7/dist-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
how to dry code? (for python 3.6 django 1.10.5)
I do not know how to remove the overlap in the class. And what if we want to change the datetime format? from django.db import models class A(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) class B(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) class C(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) -
django, secondary data in subfolders
I am working on an informational site. I am attempting to access files in a subdirectory using data from the django db. Ex: if the record.id = 1 and the file is desc.txt, I want to grab /1/desc.txt I currently have two items that I'm trying to access this way. The image file will work if I hard code the location, but I haven't been able to get it to work from the record data. The other one, I'm trying to load a description file into a div using jQuery and .html(), and can't get it to work at all. -
Many to many field django add the relationship both way
I'm trying to do a function that allow a user to follow another one. the problem is when I'm adding a new user to the "followings" the user that follow another user is also added in the following list of the followed user. For example if user a follow user b I will have that: view.py def follow_test(request): name = request.POST.get('name', '') user_followed = Dater.objects.get(username=name) current_user = Dater.objects.get(id=request.user.id) print "Current", current_user.followings.all() # display [] print "Followed", user_followed.followings.all() # display [] current_user.followings.add(user_followed) print "Current", current_user.followings.all() # display <Dater: b> print "Followed", user_followed.followings.all() # display <Dater: a> model.py: followings = models.ManyToManyField('self', blank=True) I would like the user b only to be add in the followings of a -
Problems sorting model data correctly
I'm having troubles correctly sorting the data coming from my database. My setup: I am using Django + Django Rest Framework extensively and VueJS as the frontend. I have a database table that contains messages with a ForeignKey reference to a user. These messages come from different contacts (phone numbers) and I want to be able to group them in conversations. This way, on the frontend, I will be able to see one conversation box containing all the messages with that phone_number, in another a separate conversation with a different phone_number etc. The way I want it arranged is that I want the most recent conversation box to appear on the top left, second most recent right of it, and then keep going with the least-most-recent in the bottom right. This is the Django model: class Message(models.Model): phone_number = models.CharField(max_length=100, blank=True) phone_number_clean = models.CharField(max_length=100, blank=True) contact_name = models.CharField(max_length=255, blank=True) date_time = models.DateTimeField(null=True) body = models.TextField(blank=True) user = models.ForeignKey(User) In my Django Rest Framework views file, I overrode the list() method like so: queryset = self.filter_queryset(self.get_queryset()).order_by("date_time") # get the data ordered by date_time serializer = self.get_serializer(queryset, many=True) data = serializer.data data.sort(key=itemgetter("phone_number")) conversation_list = [] for key, group in itertools.groupby(data, lambda item: … -
Django: Trying to get basic login page working for user authentication
New to Django and making some good progress, but been struggling with this for several nights and am just not getting the results I am after. Really doesn't seem like it is authenticating with the database. Using python manage.py shell to communicate with the DB works fine. Wondering if someone can recommend a tutorial that actually discusses setting up a login page from scratch as I have tried these ones and they don't seem to work: How to Use Django's Built in Login System Right way of adding user authentication to Django The last one just results in an django.urls.exceptions.NoReverseMatch: Reverse for '/login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] My / URL for the website is actually the login page. I have other URLs for /home, /documents, /help, etc. that the user needs to be logged in to view them. If they try to go to any of those URLs and they are not authenticated, it should redirect them to login. Really, just focusing on /home. Seems to let me view it without being authorized or I just keep getting redirected to the login page. Would post my code, but I know I … -
Filter queryset by optional start and end date
I want to filter a queryset by a date range where both the start and end date are optional. Specifically, if dt_from: results.filter(date_modified__gte=dt_from) if dt_until: results.filter(date_modified__lte=dt_until) where dt_from and dt_until are each either datetime.datetime, datetime.date, or None. The documentation about the behaviour of chaining multiple filters is extremely confusing however (see Chaining multiple filter() in Django, is this a bug?), and I'm not sure that the above does what I think it does (it may OR the filters rather than ANDing them). Does the above code achieve what I want (i.e. AND the two filters) or is there another way I should do this?