Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run string command in pymongo
I have following string command query = "{}{'_id': False}" Now I want to run above command in following code client = MongoClient('mongodb://'+host+':'+port+'/') db_col = database.split(',') database, collection = db_col[0].strip(), db_col[1].strip() collection = client[database][collection] collection = collection.find(query).limit(10) Is there any solution for that -
Function that assign image from related model to parent model ImageField
Is it possible to write a function that assigns an image from another/related model to an models.ImageField? Sorry for the bad explanation, here is an example: models.py class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) class Image(models.Model): product = models.ForeignKey(Product, related_name='images') is_featured = models.BooleanFIeld(default=1) So my intention is to write/define a function above the Product model that assigns the image from Image that is set to is_featured = True. I've been playing around and no matter what I've tried cover_image remains blank or None. Currently the function looks like this: def get_cover_image(instance): cover_image = instance.architecture.is_featured == 1 return cover_image class Product(models.Model): cover_image = models.ImageField(default=get_cover_image) Am I completely of base here? Is what I'm trying to achieve possible? -
Model Relationship Failing, Can't Get Data in Template
I have model Profile and another model called 'Nation', and this model will take Profile and User as ForeignKeys. It's like this, class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_type=models.CharField(max_length=10, choices=M_CHOICES) class Nation(models.Model): user= models.ForeignKey(User, related_name='natuser') profile = models.ForeignKey(Profile, related_name='nat_hr') ref_number = models.CharField(max_length=20, default=pm_tag) The logic here is to check for the type of user and show fields 'values' related to the user model. For this, we believe the User belongs to the Nation model, so to get his ref number, In Views, I did @login_required def profile_detail(request, username): user= get_object_or_404(User, username=username) try: the_detail= user.profile except ObjectDoesNotExist: return None in Template, after checking that the user type belongs to the Nation model, I wrote the below code to get the user ref_number but it's failing. {{the_detail.nat_hr.ref_number}} {{the_detail.user.profile.nat_hr.ref_number}} What am I missing when it comes to using related_name to get data that belongs to a model via template? -
django pagination is not working properly
i am trying to do pagination function based-view , it does work but...I m going to give you an example: If i have a total of 100 results and i want to paginate by 50, it will give 2 pages, but both pages have same 100 results. Cause if i want to paginate by 50 it will give me 2 pages. I used the the function based view from this link. i don't want classed view cause if i implement that the rest of the code would not work. I m going to post a part of my code for this. views.py def search_form_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if request.method == 'GET': form = AllTablesForm(request.GET) if form.is_valid(): cd = form.cleaned_data title = cd['title'] url = cd['url'] query = t.objects.filter(title__icontains=title, url__icontains=url) page = request.GET.get('page', 1) paginator = Paginator(query, 50) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'search_table.html', {'tbl_name': table_name, 'users': users, 'form': form, 'details': query}) -
Django encode / decode and Store in psql
I'm trying to store the store the Gujarati string from Android to PostgreSQL using Django API. When I'm calling the same API by web, its working fine because I can see the Gujarati text in the database. but when I'm trying to store the same string from Android, it's coming in question mark format (EX: ???? ??) So I encoded the string in Android, as per this solution: Here Now I'm getting the correct output by using print only, but when I'm storing it into the database, it's storing in the encoded format, see the below example: Gujarati Text: ❛ઝીંદગ After AndroidEncoded:%E2%9D%9B%E0%AA%9D%E0%AB%80%E0%AA%82%E0%AA%A6%E0%AA%97 By using the urllib: >>>urllib.unquote_plus(a.encode('utf-8')).decode('utf-8') Output: u'\u275b\u0a9d\u0ac0\u0a82\u0aa6\u0a97' Now when using print on terminal: >>>print(urllib.unquote_plus(a.encode('utf-8')).decode('utf-8')) Output: ❛ઝીંદગ and when storing the same value in a database like: text = urllib.unquote_plus(a.encode('utf-8')).decode('utf-8') text getting store as %E2%9D%9B%E0%AA%9D%E0%AB%80%E0%AA%82%E0%AA%A6%E0%AA%97 But from browsers, it's storing ❛ઝીંદગ I want to know why it's showing the proper output when I'm using the print and when storing it's not working as expected. Thanks -
Error with Django Celery ,how to fix?
well i have same view same setting for celery in another app, when i launch another one, he is work, absolutely work, but when i launch this, nothing, i installed everthyng like in another one, but nothing, pls help me! if you have some ideas how to fix please let me know) This is full traceback Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\utils\__init__.py", line 423, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 449, in _ensured return fun(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 177, in _publish channel = self.channel File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 194, in _get_channel channel = self._channel = channel() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\utils\__init__.py", line 425, in __call__ value = self.__value__ = self.__contract__() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\messaging.py", line 209, in <lambda> channel = ChannelPromise(lambda: connection.default_channel) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 771, in default_channel self.connection File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 756, in connection self._connection = self._establish_connection() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\connection.py", line 711, in _establish_connection conn = self.transport.establish_connection() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection conn = self.Connection(**opts) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\connection.py", line 165, in __init__ self.transport = self.Transport(host, connect_timeout, ssl) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\connection.py", line 186, in Transport return create_transport(host, connect_timeout, ssl) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\shop\lib\site-packages\amqp\transport.py", line 299, in … -
Django - How can I load images created by site using image uploaded by users?
For any image uploaded by the user, I am generating a Thumbnail. The user uploaded image and thumbnail are stored like this. media_cdn (folder) -user_name_1 (folder) -user_name_2 (folder) --post_1_title_slug (folder) ---300x180 (folder) ----300x180_user_uploaded_image_1.png ---user_uploaded_image_1.png --post_2_title_slug (folder) -user_name_3 (folder) Since I am using ImageField in models, I can easily use {{ appname.image.url }} in templates, but this will load the image uploaded. I want to load the thumbnail. I search on stackoverflow and most people are saying to use {{ MEDIA_URL }}, like here I am leaning towards {{ MEDIA_URL }} because, in the future, the website will be generating more images based on the same user uploaded images. I am using this as of now, <img src='{{ MEDIA_URL }}/{{user.username}}/{{ upload.slug }}/300x180/300x180_{{ upload.get_filename }}'> this is giving out this in the page, (from Inspect element) /user_name/file_slug/300x180/300x180_image_name.png {{ MEDIA_URL }} is not giving its correct url. FYI, get_filename is from models.py where I wrote this to get the file name def get_filename(self): return(os.path.basename(self.image.name)) how can I make this work? I am Using Django 1.11.5, and Pillow 4.2.1 -
How to add custom button in django-admin
I have a another submit button in change_form and if this button clickled i want to validate and customize my requested data. admin.py def save_model(self, request, obj, form, change): data = request.GET.copy() if '_saveandclose' in request.POST: data['CloseDetail'] = "Save and Closed Clicked!" #and i need some validation obj.User = request.user obj.save() -
Running a python script after a button is clicked
So I have an html page like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Find the words</title> <h1>Find the Words</h1> </head> <body> <p>Find the largest and the smallest word</p> <textarea rows="25" cols="100"></textarea> <br> <button type="button">Find now!</button> <br><br> <label>Largest Word</label> <input type='largest word'/> <label>Smallest Word</label> <input type='smallest word'/> </body> </html> I want to run a python script which will find the largest and smallest word from a text and post the result back. The script is like this: #!/usr/bin/env python3 def find_small_large_words(given_string): new_list = given_string.split(" ") sorted_list = sorted(new_list, key=len) return 'Smallest: {0} & Largest: {1}'.format(sorted_list[0], sorted_list[-1]) words = "Ten years on from the financial crisis, it’s hard not to have a sense of déjà vu.Financial scandal and wrangles over financial rule-making still dominate " \ "the headlines.The cyberhacking at Equifax compromisedpersonal records for half of the adult population of the United States.At SoFi, a one-time fintech darling" print(find_small_large_words(words)) Ultimately, I want to run the python script on click of the "Find words" button and post them back in the two boxes. How can I do that here? I have read some suggestions about using django framework. Is there any other simple way? If so, how? -
Writing html files with python
I have read about some python frameworks for web development. I understand that django is a really high level and good platform. I want to put static data (results from several runs of a program) on a webpage. Should i use django or there is an easiest alternative because my needs are simple. Prehaps i will need to deal with dynamic data in the future- for that i do need django? Thanks, Or. -
When changing a Custom User model in Django Admin a plain text field is used instead of the special password field?
In the custom user with admin docs, it mentions that if your custom user model extends AbstractBaseUser you need to add it to the admin manually. I have done that in admin.py with: from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ('email', 'first_name', 'last_name', ) However when I go and edit a user I get: Instead of the usual password field: -
Extending admin index.html template
I have downloaded the following templates from admin.contrib: base.html, base_site.html and index.html. I would like to extend index.html, but no matter what I do it does not seem to work. In settings.py, I have declared the name of my app to override the order in which the admin files are render. So, I can edit the actual files and content does change when I run the server. But, I create a file in the directory templates/admin/foo.html. The code with foo.html is: {% extends "admin/index.html" %} {% block something %} <p>Hello</p> {% endblock %} And I have change the file templates/admin/index.html to have {% block something %}{% end block %} When I run the server, the content of foo.html does not display. Do I need to add foo.html to my urls.py and create a function within views.py to render the content? Any help would be greatly appreciated. -
Django AbstractEmailUser column does not exist
Yesterday i have made a CustomUser using AbstractEmailUser, today i wanted to add an avatar field, after finishing it and making migrations i'm getting this error: column account_customuser.avatar does not exist LINE 1: ...user"."name", "account_customuser"."valid_email", "account_c... models.py looks like this now class CustomUser(AbstractEmailUser): nickname = models.CharField('nickname', max_length=100, unique=True) name = models.CharField(max_length=200, blank=True, null=True, default=None) valid_email = models.BooleanField('valid email', default=False, blank=True) avatar = models.ImageField(upload_to='profile/photo', blank=True, null=True, default=None) What can i do to add avatar field? -
Django views 'int' object is not iterable error
Why does the error appear? If call any of if blocks after form.save() appear the 'int' object is not iterable error Code below: if request.method =='POST': if form.is_valid(): form.instance.user = request.user is_auction = request.POST.get("create_auction", "") phone_number = request.POST.get("phone", "") attr_dic = {} for attr in form.cleaned_data['subcategory'].attributes.all().order_by('ordering'): if request.POST.get(attr.name): attr_desc={} attr_desc['verbos_name'] = attr.verbos_name if attr.attr_type =='choice': attr_desc['value'] = str(attr.dict.model_class().objects.get(pk=request.POST.get(attr.name)).pk) # attr_desc['value'] = str(attr.attributevalue_set.get(pk=request.POST.get(attr.name)).pk) attr_desc['value_name'] = str(attr.dict.model_class().objects.get(pk=request.POST.get(attr.name)).name) # attr_desc['value_name'] = attr.attributevalue_set.get(pk=request.POST.get(attr.name)).vallue else: attr_desc['value'] = request.POST.get(attr.name) attr_desc['value_name'] = request.POST.get(attr.name) attr_desc['ordering'] = attr.ordering attr_desc['filtering'] = attr.filtering attr_dic[attr.name] = attr_desc form.instance.attributes = attr_dic form.save() if region is None: p, updated = request.user.userprofiletable_set.update(adress_state= form.cleaned_data['state'] ,adress_city =form.cleaned_data['city'] ) if (contact_phone == '' or contact_phone !=phone_number): p, updated = request.user.userprofiletable_set.update(phone=phone_number) if is_auction=='on': p, created =Auction.objects.get_or_create(product=form.instance,title=form.instance.name,description=request.POST.get("description_auct", ""), start_price=request.POST.get("start_price", ""), end_price=request.POST.get("end_price", ""), min_price_step=request.POST.get("min_price_step", ""), end_date=request.POST.get("end_date", ""), currency=form.instance.currency) return redirect(url) -
HTML 5 download attribute not working in safari
<a href="{{list.resource.url}}" style="display: none" id="file_id{{list.id}}" download="true">Export</a> I Need to download file in one click but in safari, the file is opening in new tab instead of downloading -
angular2/post request to django to create user
I am trying to create new users in my Angular app by sending post requests to Django backend (which is not developed by me but is believed to be implemented correctly). In my sign up service, I have the following function to create new user newUser(f: NgForm){ let username = f.controls['username'].value; let password = f.controls['password'].value; let email = f.controls['email'].value; let headers = new Headers(); headers.append('Content-Type','application/json'); headers.append('X-CSRFToken', this.getCookie('csrftoken')); return this.http.post('http://localhost:8000/users/', JSON.stringify({username: username, password: password, email: email}), {headers: headers}) .toPromise() .then(res => res.json()) .catch(this.handleError); } In my form component, I have onSubmit function that only "talks" to the sign up service onSubmit(form: NgForm) { let res = this.signUpService.newUser(form).then(result => res = result, error => this.errorMessage = <any> error); However, when I try to create new users, I get the following error: POST http://localhost:8000/users/ 401 (Unauthorized) I am thinking that the backend might be configured in a way that only superuser can create new users, and, hence, that's what throwing an error. Any ideas? -
Always login is rejected
I wrote e-mail address and password which is already registed in login form but always login is rejected. I wrote in html like <div class="container"> <form class="form-inline" action="{% url 'login' %}" method="post" role="form"> {% csrf_token %} <div class="form-group"> <label class="email_form">Email</label> <input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/> </div> <div class="form-group"> <label class="password_form">Password</label> <input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="Password" class="form-control"/> </div> <button type="submit" class="btn btn-primary btn-lg">Login</button> <input name="next" type="hidden" value="{{ next }}"/> </form> </div> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): __init__(*args, **kwargs) self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password'].widget.attrs['classF'] = 'form-control' I already confirmate whether email&password is right or not in admin site, but I am surely right to typed email&password in login's form.So I really cannot understand why I cannot log in.What is wrong in my code?How can I fix this? -
Django app doesn't recognize static files
I have a Django application which I'm not able to load static files in. My templates are perfectly loaded, but CSS and JS files can't be loaded. Here's my files: zeinab@ZiZi:~/Desktop/MyProject$ tree . ├── __init__.py ├── manage.py ├── myapp │ ├── __init__.py │ ├── lib │ │ ├── decorators.py │ │ ├── dorsa_forms.py │ │ ├── __init__.py │ │ └── utils.py │ ├── log │ ├── media │ │ └── admin │ │ └── background_login │ │ └── bg1.jpg │ ├── settings.py │ ├── static │ │ ├── calendar.js │ │ └── inbox.css │ ├── templates │ │ ├── 404.html │ │ ├── base.html │ │ └── index.html │ ├── urls.py │ ├── views.py │ └── wsgi.py └── requirements.txt 8 directories, 18 files When I runserver, I get "GET /static/file/url HTTP/1.1" 404 1265 for each CSS and JS file. Here's MyProject/manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) This is MyProject/myapp/settings.py: import os from django.contrib.messages import constants as messages BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sorl.thumbnail', 'myapp.lib', ) MIDDLEWARE_CLASSES = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) SITE_ID … -
python use pip to install the library, there is an accident, emergency! The I'm about to cry! The The The
各位大神,求求大家,来帮我看看吧,我已经没招了,3 天了问题都没解决,就差重装系统了!!,问题是 Python 当中 pip 安装库出现错误 我直接贴错误代码 了 (You big god, ask everyone to help me look at it, I have not strokes, 3 days the problem did not solve, it was installed on the equipment! The , The problem is that Python pip installation library error I posted the wrong code directly) 不要再说是版本的问题 因为我在其他两台电脑上面用相同的安装包 这是我,安装一个最简单的库 pip install requests 没有其他的库 安装失败了,我重装过 python 和 pip 版本是 清理过注册表 也使用过 管理权安装 也更换过 安装盘符变量路径也添加了 使用过WHL的方式安装 使用过 Anaconda 但是都是不可以的 我又回到了原点 如果谁可以帮我解决 感激不尽 ( It is me, install one of the most simple library pip install requests no other library installation failed, I reloaded python and pip version is python3.7, pip is the latest version, do not say that is the version of the problem because i am The other two computers above with the same installation package, are able to properly installed, I reload, clean up the registry, can clean up the way are cleaned up, also used, management installed, also replaced, installed Drive, variable path also added, also used .whl way to install, also used Anaconda, but are not, I went back to the origin, if anyone can help me solve, I am paid is willing, grateful Not! The The) -
invalid literal for int() with base 10: '
I recently added sentry for error tracking in my project and configure raven according to documentation here but getting the error shown below. System check identified no issues (0 silenced). October 02, 2017 - 11:31:58 Django version 1.10, using settings 'FoodCham.settings.development' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Sending message of length 2240 to https://sentry.io/api/224093/store/ Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 244, in _legacy_get_response response = middleware_method(request) File "/usr/local/lib/python2.7/dist-packages/raven/contrib/django/middleware/__init__.py", line 135, in process_request request.body # forces stream to be read into memory File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 267, in body int(self.META.get('CONTENT_LENGTH', 0)) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE): ValueError: invalid literal for int() with base 10: '' Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 244, in _legacy_get_response response = middleware_method(request) File "/usr/local/lib/python2.7/dist-packages/raven/contrib/django/middleware/__init__.py", line 135, in process_request request.body # forces stream to be read into memory File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 267, in body int(self.META.get('CONTENT_LENGTH', 0)) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE): ValueError: invalid literal for int() with base 10: '' [02/Oct/2017 11:32:04] "GET / HTTP/1.1" 500 69274 Any helpful answer will be appreciated! -
Graciously handle crash while saving model via Django Admin
Sometimes it is not possible to know beforehand and graciously reject model save inside a validator which shows nice error message in Django Admin. If a specific crash happens during the save operation (e.g. data integrity error) and we still want to catch it and show a nice error (similar to validation errors), there's no obvious way to do this that I could find. I tried overriding the save_model method on Django Admin, but this is a horrible thing to do according to the docs: When overriding ModelAdmin.save_model() and ModelAdmin.delete_model(), your code must save/delete the object. They aren’t meant for veto purposes, rather they allow you to perform extra operations. What's the correct way to catch specific exceptions and display nice error message then? -
Django with MongoDB and React-native
So I am relatively new and I am looking for a good stack to work on. I want to use react-native on the front-end, Django and MongoDB on the backend. I know I can easily use Node.js as the server but I don't want to. How good is this combination? Are there any boiler plates available for this? Please suggest. -
Django Rest DRF : accessing a foreign key reference from reverse relation
Let's say I have two models. Model class Item(models.Model): name = models.CharField(max_length=32) # other fields class ItemRelation(models.Model): item = models.ForeignKey(Item, related_name='relations_item') user = models.ForeignKey(User, related_name='relations_user') has_viewed = models.BooleanField(default=False) has_loved = models.BooleanFields(default=False) Now, what I want to do is to get the profile of one user which would contain the items associated with that user having has_loved=True and has_viewed=True. In my views.py file I had something like this. class UserProfile(APIView): def get(self, request, format=None): id = self.request.query_params.get('id') user = User.objects.filter(id=2).prefetch_related(Prefetch( 'relations_user', queryset=ItemRelation.objects.select_related('item').filter(has_viewed=True), to_attr='item_viewed' )) I was certain that I was wrong and I also got a serializer error, since I was trying to serialize an ItemRelation object using a serializer which used the Item as its model. -
How to squash all migration files in to one in django?
I have 82 migration files in my django app. Some of them are related to removed models. I want to merge all these 82 migration files into one migration file. How do I do without deleting the database? -
How to make a schedule status update in python Django. Like Fb page's schedule update
I try to make a social networking site using python django. In which i want to built schedule status update functionality where user make a posting schedule of their status update and on their schedule time it need to be posted on their timeline.is it any batter way to implement it rather then using celery or another scheduling task module? and can we use celery for that?