Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving file with date and user django
I am making an UPLOAD page and i want a model that will hold a link to the file uploaded, the date and the user. I'm really new to django and i'm confused about the relation between the forms and the models and how to pass data. I want to make a 1 field form, which will be the FileField and catch request.user and time on the go, then save them in database This is my code so far: forms.py class UploadForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(UploadForm, self).__init__(*args, **kwargs) docfile=forms.FileField(label="Select a file") views.py @login_required def upload(request): if request.method == "POST": form=UploadForm(request.POST, request.FILES, user=request.user) if form.is_valid(): #this is what i used to save the only the file #now i want to have file,user and upload date in db new_doc = Document(docfile=request.FILES['docfile']) new_doc.save() print(request.user) **???**-what do i insert here to pass user and time to the model and save it **???** return HttpResponseRedirect(reverse('after_upload')) else: form=UploadForm() return render(request, 'upload.html', {'form':form}) models.py class Document(models.Model): upload_user=**???** upload_time=**???** docfile=models.FileField(upload_to='documents/%Y/%m') -
Python Socket :socket connection refused
env:linux + python3 + rornado When i run client.py,he suggested that my connection was rejected, for a few ports,Using the 127.0.0.1:7233,The server does not have any response, but the client prompts to refuse to connect,Who can tell me why? server.py # coding:utf8 import socket import time import threading # accept conn def get_hart(host, port): global clien_list print('begin get_hart') s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) print(clien_list) while True: try: clien, address = s.accept() try: clien_data = clien.recv(1024).decode('utf8') if clien_data == str(0): clien_id = clien_reg() clien.send(str(clien_id)) print(clien_list) else: clien_list[int(clien_data)]['time'] = time.time() # print clien_data except: print('send fail!') clien.close() except: print("accept fail!") continue # client reg def clien_reg(): global clien_list tim = str(time.time() / 100).split('.') id = int(tim[1]) clien_list[id] = {"time": time.time(), "state": 0} return id # client dict def check_hart(clien_list, delay, lost_time): while True: for id in clien_list: if abs(clien_list[id]['time'] - time.time()) > lost_time: clien_list[id]['state'] = 0 del clien_list[id] # del offline client break # err else: clien_list[id]['state'] = 1 print(clien_list) time.sleep(delay) if __name__ == '__main__': host = '127.0.0.1' port = 7233 global clien_list # Dict: client info clien_list = {} lost_time = 30 # timeout print('begin threading') try: threading.Thread(target=get_hart,args=(host,port,),name='getHart') threading.Thread(target=check_hart,args=(clien_list, 5, lost_time,)) except Exception as e: print("thread error!"+e) while 1: pass … -
Import model from app to main django project
I have made my website in django. There is one main project folder names django_project and one blogging project names blogging. All the blogs i have created are stored in the model of blogging folder. If i want to show a list of all blogs in home page how can i import the models in django_project folder and show list of blogs there as well. -
How to connect the python path without '/ /' [on hold]
I have django project and here I have problem with join the path. Here is my BASE_DIR: BASE_DIR = '/data/projects/teamapp/apps/' Here is my another_path = /media/content/presse/download/image.jpg I tried connect paths in this way: os.path.join(BASE_DIR, another_path) and I get: /data/projects/teamapp/apps//media/content/presse/download/image.jpg Thanks for any hint. -
Django overriding validation given a specific variable
I have a form that has several unique fields that become readonly during edit. There are no problems during creation. Unfortunately the ModelForm.is_valid() method catches these and still validates during edit. My model is a simple Django object with its form: from django import forms from .models import Sample class SampleForm(forms.ModelForm): class Meta: model = Sample fields = "__all__" The view method is just a simple save() if is_valid() is true otherwise show the error messages. I manually setup the form in the view file/I do not use the auto-generated form structure by ModelForm. In node.js, I just have this simple validation to catch these (the field slug for example): isSlugUnique(slug, operation) { return new Promise((resolve, reject) => { Sample.findOne({ slug: slug }, (err, sample) => { if(err) throw err; if(sample === null) { resolve(); } else if(slug === sample.slug && operation === 'edit') { resolve(); } else { reject(); } }) }) }, It has a catch to skip the validation if the slug attribute is not unique and the form operation is editing. I tried catching it alongside my is_valid() method (the error message for existing fields is of the pattern "[Model] with this [Field] already exists." so … -
django - get() returned more than one topic and filter doesn't work
I have a problem with get() in Django. To wit I have such function: try: sth = Object(t=request.GET.get('data')) if request.method == 'GET': serializer = ObjectSerializer(sth) return Response(serializer.data) I got error: get() returned more than one Object -- it returned 2! So I have swapped get for filter: sth = Object.objects.get(t=request.GET.get('data')) But now I get error: AttributeError: Got AttributeError when attempting to get a value for field `data` on serializer `ObjectSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'data'. Any suggestions? -
Not model based Django auth
I am learning Django auth at the moment and it looks great! However it came to my attention that it seems a little bit too model-based. What I think of is that let's say I have two web pages (monitoring, statistics) and they both use the same model (event table). What I want is to add permission to different users to access monitoring and to statistics, like: can_use_monitoring, can_use_statistics. I presume it is not a problem to add the same model to these 2 permissions but seems unnecessary and misleading. Or am I missing something? How would you achieve that? Thanks, V. -
how to write custom command test statement that takes in an argument and then does file editing?
I have a custom command in my Django 1.10 called upload_pics_for_variants.py What it does is it takes in an argument about a directory path and then proceeds to use my app models to upload jpg images. Hence my command is python manage.py upload_pics_for_variants tmp/some_folder and it works perfectly I have read about how to write unit tests for custom command but it looks like it will simply test a command that has no arguments and then expects a certain output. How should I write my unit test to properly test my custom command class that is supposed to behave as stated above? -
Not sure how django and ldap work together
I have a django app and I want to add authentication to it. Django is very good friend so it has a great security part. I can use the User object and the built-in admin GUI to maintain users, groups, etc. I want to give the opportunity to the app user to connect to LDAP and use it to authenticate the user against. Ok, there are django-ldap modules that I can use, brilliant! However I don't understand at the moment how it works exactly. Will the user be propagated to the local django suth database (the reason why I ask that is that we still deal with the User object when call LDAP)? Or whenever we need the user or auth has to be done the LDAP will be called and authenticate the user there? Sorry for the novice question but I am a little bit confused. Thanks, V. -
Error while running command python manage.py runserver
i have just created django project through following command from cmd: django-admin.py startproject database then i edit settings.py the following: DATABASES = { 'default': { 'ENGINE':'mysql.connector.django', 'NAME' : 'music', 'USER':'python', 'PASSWORD':'123654789', 'HOST':'127.0.0.2', 'OPTIONS':{ 'automatic':True, } } } when running command python manage.py shell/ or python manage.py runserver i got error type Error None type object is not callable python version 3.4.3, os win8, django version 1.11, mysql 5.7, MySQL Connector/Python. ERROR: Traceback (most recent call last): File "C:\Users\Bibek Ghimire\djcode\database\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Python34\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python34\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "C:\Python34\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Python34\lib\site-packages\django\contrib\auth\base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File … -
RawPostDataException when accessing `request.body` the first time
In my Django form, I'm storing the request.body so I can restore the original form afterwards. I'm aware that you can read request.body only once. The second time you get a RawPostDataException Exception. So far so good. The problem is when I added a forms.FileField to my form. Now it seems like even the first access to request.body fails with RawPostDataException exception. It looks like when sending files in the form, django does something and reads the request.body object, practically locking it from reading afterwards. This happens even before the Form object initialization. Is it a bug? How can I access request.body content otherwise? -
Django-excel file imported but models are not saved
Well I am trying to update database by uploading excel file using Django-excel, however the data is not saved to db and neither I get any error message!!! My views.py @login_required def customerbulk(request): action = 1 if request.method == "POST": form = productupload(request.POST, request.FILES) def choice_func(row): q = request.user row[0] = q return row if form.is_valid(): request.FILES['select_excel_file'].save_book_to_database( models=[customer], initializers=[choice_func], mapdicts=[ ['user','name','address','state_code','shipping_address','shipping_state_code','email','telephone','GSTIN','PAN','discount','notes']] ) return HttpResponseRedirect(reverse('customerbulk'),messages.add_message(request, messages.SUCCESS,'Customers added Succesfully')) else: form = productupload() return render(request,'productbulk.html',{'form': form,'action':action,}) -
Django (Models): how to get instance from foreign key
i'm new to django and sqlite. Is that possible i can get the instance.name value from its foreign key that is related to modeldb? I need to save my pdf file under the same directory as the modeldb class. From the above experiment, im got nothing with modelDB.instance / modelDB.instance.name. -
Use distinct and annotate in query
My model is : class PostMetric(models.Model): post_id = models.TextField() likes = models.IntegerField() comments = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I record in this table once (or multiple times per day) the number of likes/comments of my posts. I would like to get the sum of likes and comments of each day for all the posts. Here is the query I use : PostMetric.objects.filter(my_filter).annotate(date_only=TruncDay('created_at')).values('date_only').annotate(engagement=Sum('likes') + Sum('comments')) The issue is that it works fine if for each post there is only one record per day, but if there are more than 1 record for a post, it will sum likes/comments for that post more than once. I would like to add between values & annotate attributes, the distinct function applied to post_id and select only the most recent metrics (like/comments) recorded (so I don't get duplicated) : PostMetric.objects\ .filter(my_filter)\ .annotate(date_only=TruncDay('created_at'))\ .values('date_only')\ .order_by('-media_id')\ .distinct('media_id')\ .annotate(engagement=Sum('likes') + Sum('comments')) But I can't use "annotate" and "distinct" in the same time : NotImplementedError: annotate() + distinct(fields) is not implemented. -
Swift: Open URL in safari with session storage
I would like to open URL with safari app inside my application. I do this with UIApplication.shared.open(myUrl, options: [:], completionHandler: { (success) in print("Url open") }) Now, I would like to store some data inside session storage, so that my page will know which user did open this page and he does not need to relogin. Python django uses token in session storage for authentication, and I know how to get current user token before call to my page. I figure it out that store inside NSHTTPCookieStorage does not do the trick. How to set session storage properties before open safari? Python code would be sessionStorage.setItem('token', this.token); -
showing text from uploaded text file in django
I am able send and show text sent as text via post method .. But i want to send a txt file and show the whole texts in the txt file in the html file . I have found similar posts to this one but unlike them i dnt want my file to be stored in database ... I am new in Django . All i need it a simple demonstration . I am using django 1.11 and python 3.5 . form.py class indexForm(forms.Form): file = forms.FileField() My views.py class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() def get(self, request): form = indexForm() return render(request,self.template_name, {'form':form}) def post(self,request): form = indexForm(request.POST,request.FILES) file = request.FILES['file'] fs = FileSystemStorage() ## removing the previous files chk = OverwriteStorage().get_available_name('spd') media_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'media') print(media_path) # f = open(media_path) file_file = fs.save('spd', file ) file_file_url = fs.url(file_file) if form.is_valid(): dataset = form.cleaned_data['dataset'] dict = { 'dataset': dataset, 'form' : form, 'file_file':file_file_url, } args = dict return render(request, self.template_name, args) using the above code i can display a uploaded photo without storing .. But now i want to show texts of a uploaded text file in html -
Why does CELERY_ENABLE_UTC=False broke beater?
If I set CELERY_ENABLE_UTC=False, beater sends task duplicates into queues. But if it is CELERY_ENABLE_UTC=True, beater works as expected. Why does it have so strange behavior? Is it possible to fix this? -
How to use CreateView for the model that has a primary key from the first model that you have already used createview
Hi guys I'm trying to create a simple todo-list but I'm getting some troubles, first I want to create a task an inside of it I want to create some activities, that is the problem that I could not get done. How can I create an activity using a CreateView end pass to it the pk from the task and after create how can reverse to same task detail thanks a lot models: from django.db import models from django.core.urlresolvers import reverse class List(models.Model): title = models.CharField(blank=True, max_length=100) class Meta: ordering = ['id'] def __str__(self): return self.title def get_absolute_url(self): return reverse('task-detail', kwargs={'pk': self.pk}) PRIORITY_CHOICES = ( (1, 'Low'), (2, 'Normal'), (3, 'High') ) class Item(models.Model): title = models.CharField(blank=True, max_length=100) created = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) priority = models.IntegerField(choices=PRIORITY_CHOICES, default=2) completed = models.BooleanField(default=False) todo_list = models.ForeignKey(List) class Meta: ordering = ['-priority', 'title'] views: class TaskDetailView(DetailView): model = List class TaskCreateView(CreateView): model = List fields = ['title'] success_url = '/home' class TaskUpdateView(UpdateView): model = List fields = ['title'] template_name = 'core/update.html' success_url = '/home' class TaskDeleteView(DeleteView): model = List success_url = reverse_lazy('home') class ActivityCreateView(CreateView): model = Item fields = 'title', 'priority', 'completed' success_url = '/home' class ActivityUpdateView(UpdateView): model = Item fields … -
Picking uploaded files with django
Hi i have to upload some csv files to make a pdf. The problem is i dont know how to pick this files and pass it to a function in the views. The code works if i put them manually but is not what i looking for. views.py def subir_archivos(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] file_obj = myfile.read() media_path = settings.MEDIA_ROOT file_path= os.path.join(media_path, "csv") if not os.path.isdir(file_path): try: os.makedirs(file_path) except OSError as e: pass file = os.path.join(file_path, myfile.name) with open(file, 'wb') as f: f.write(file_obj) uploaded_file_url = os.path.join("/media", "csv", myfile.name) return render(request, 'subir_csv.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'subir_csv.html') And i have to recive in the views function. How can pick this files and send it to my pdf_maker function?Like in form or something like that??.Feel free to ask me id the description is a bit confusing. Thanks for the help. HTML template <div class="container-fluid"> <form method="POST" enctype="multipart/form-data">{% csrf_token %} <input type="file" name="myfile"> <br> <button type="submit">Subir</button> </form> <br> <a class="btn btn-primary" href="{% url 'index' %}">Atras</a> </div> -
TypeError at /accounts/register/ RegistrationForm() takes exactly 1 argument (0 given)?
accounts/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm def RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user accounts/views.py from django.shortcuts import render, redirect from accounts.forms import RegistrationForm def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else : form = RegistrationForm() args ={'form':form} return render(request, 'accounts/registration_form.html', args) i am getting this error TypeError at /accounts/register/ RegistrationForm() takes exactly 1 argument (0 given) where am i going wrong can any one help , thanks in advance -
Hiding new pages from being created in Wagtail
I have tried searching the official documentation and related message boards for this however I have been unable to find anything related. Some of the templates for pages in my website are only to be used once - e.g. homepage. Is there a way in Wagtail to hide or disallow users from selecting that template/Page model when creating a new page? -
Right way of using conditional expressions on order_by django
I'm using Case method from conditional expression example docs and I found some answers on SO to order contacts by status_text or status, in this example I'm using status_text field. I'm doing all of this in my api get_queryset and I'm doing something like this, def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user # I have some other conditions here # This is the conditional expressions that I'm building for order_by case_sql = LeadContact.objects.annotate( custom_order=Case( When(status_text=LeadContactConstants.STATUS_CLIENT, then=Value(1)), When(status_text=LeadContactConstants.STATUS_QUALIFIED, then=Value(2)), When(status_text=LeadContactConstants.STATUS_CONTACTED, then=Value(3)), When(status_text=LeadContactConstants.STATUS_PRISTINE, then=Value(4)), output_field=CharField(), ) ).order_by('custom_order') return queryset.extra(select={'status_text': case_sql}, order_by=['status_text']) Now the database is throwing this Traceback: Traceback: File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 87. return self.dispatch(request, *args, **kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 466. response = self.handle_exception(exc) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 463. response = handler(request, *args, **kwargs) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list 42. page = self.paginate_queryset(queryset) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/generics.py" in paginate_queryset 172. return self.paginator.paginate_queryset(queryset, self.request, view=self) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/rest_framework/pagination.py" in paginate_queryset 303. return list(queryset[self.offset:self.offset + self.limit]) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in __iter__ 162. self._fetch_all() File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all 965. self._result_cache = list(self.iterator()) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/query.py" in iterator 238. results = compiler.execute_sql() File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 840. cursor.execute(sql, params) File "/home/vagrant/virtualenv/local/lib/python2.7/site-packages/django/db/backends/utils.py" … -
how can send parameter with post action in javascript or jquery function withou ajax type?
i want to send some parameter to Django with post action when i click on link in web page call javascript or jquery function then call URL and post some parameter in this function without AJXA type in other words when click in navigation bar in web page call URL and send some parameter to function in view in Django how con do this? thanks for help. -
os.walk searching improvement
I'm using os.walk to search a html file, but it took 2 minutes to return the file. Any suggestion to improve the performances? path1 = "//ggco/kk" shp_list = [] for dirpath, dirnames, y in os.walk(path1): for k in y: k.startswith(Lot_Operation_combine) and k.endswith(".html") fullpath = os.path.join(dirpath, k) shp_list.append(fullpath) if os.path.isfile(fullpath): path = "//ggco/kk" shp_list = [] for dirpath, dirnames, x in os.walk(path): for f in x: if f.startswith(Lot_Operation_combine1) and f.endswith(".html"): fullpath = os.path.join(dirpath, f) shp_list.append(fullpath) if os.path.isfile(fullpath): with open(fullpath, 'r')as f: f_contens = f.read() print(f_contens) kau = f_contens context = { "Final": kau } return render(request, 'Output.html', context) else: path = "//ggco/kk" shp_list = [] for dirpath, dirnames, x in os.walk(path): for f in x: if f.startswith(Lot_Operation_1A) and f.endswith(".html"): fullpath = os.path.join(dirpath, f) shp_list.append(fullpath) if os.path.isfile(fullpath): with open(fullpath, 'r')as f: f_contens = f.read() print(f_contens) kau = f_contens context = { "Final": kau } return render(request, 'Output.html', context) I'm new in python programming language. any idea using os.walk to search 1 specific file for faster performances? I hope you guys can share some idea for this problem ... Thank you........ -
Django Upgrade: Static Files Not Served
I have upgraded to Django 1.10 from 1.9.6. Below is my urls.py file which previously worked: from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve from dwad import settings urlpatterns = [ url(r'', include('meta.urls')), url(r'^straightred/', include('straightred.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^chaining/', include('smart_selects.urls')), url(r'^tinymce/', include('tinymce.urls')), url(r'^accounts/', include('allauth.urls')), ] # Get Django to serve media files in debug mode. if settings.DEBUG: urlpatterns += [url(r'^resources/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})] if not settings.DEBUG: urlpatterns += [ url(r'^resources/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ] When try to run the site I get: view must be a callable or a list/tuple in the case of include(). I know the above error is due to the 'django.views.static.serve' being in strings. If I remove them from strings and link to the actual view i get the following error: name 'django' is not defined If I delete everything from "Get Django to serve media files in debug mode." and below the site loads but no static or media files are served. This obviously means no css is applied and no images are loaded. If people can offer some advice on next steps that would be appreciated.