Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django/Python Serializing valuequeryset with number of objects limits per call (external service)
I am relatively new to Django and Python and have a quick question on the best way of going about breaking up serialization on object limits as apposed to call limits. I will be making calls to an external web service that limits the number of objects per call in addition to calls/timeframe. Currently I am creating a dictionary from a valuequeryset and then serializing. I have the json producing correctly, but I am looking for the best way to build the json in chunks. The API I am hitting allows for single object calls, but also calls with up to 5 objects. For example, I have a queryset with 25 records, what would be the best way to iterate through the list and break it into 5 json payloads which I could then iterate through, build json and fire off. Using the 5 per call instead of the 1 per call will help with the calls per time frame. Any help would be appreciated and thanks in advance. -
In my Dockered Django application, my Celery task does not update the SQLite database (in other container). What should I do?
This is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./docker_nginx:/etc/nginx/conf.d - ./timezone:/etc/timezone depends_on: - web rabbit: image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5672:5672" - "15672:15672" web: build: context: . dockerfile: Dockerfile command: /app/start_web.sh container_name: django_airport volumes: - ./:/app - ./timezone:/etc/timezone expose: - "8080" depends_on: - celerybeat celerybeat: build: context: . dockerfile: Dockerfile command: /app/start_celerybeat.sh volumes: - ./:/app - ./timezone:/etc/timezone depends_on: - celeryd celeryd: build: context: . dockerfile: Dockerfile command: /app/start_celeryd.sh volumes: - ./:/app - ./timezone:/etc/timezone depends_on: - rabbit Normally, I have a task that executed every minutes and it updates the database located in "web". Everything works fine in development environment. However, the "celerybeat" and "celeryd" don't update my database when ran via docker-compose? What went wrong? -
Multiple ForeignKey to the same parent table, but with a unique identifier
I have the following data structure: State has state_id and name. (Example: California) Area has state_id, area_id and name (Example: Area of San Francisco, which contains some villages and San Francisco) Town has town_id, area_id, state_id, and name. (Example: Town of San Francisco) Street has street_id, town_id, area_id, state_id and name. Note the following: state_id is not a real ID (like an auto increment int), but a fixed number for each state. area_id is neither an auto increment int, but a fixed number. This means that two different states (big enough to have several areas), will have states with the same ID. (The state of San Francisco will have San Francisco (area_id = 1) and the state NY will have NY (area_id = 1). town_id... you guessed it, same as state_id and area_id. Don't insist on why the data is structured that way, it goes beyond the scope of this question and beyond what I'm allowed to refactor. So don't waste time on suggesting me to change that. I already know it's wrong, but I'm not allowed to fix it. Full stop. This means that a town must contain both the area_id and the state_id for it to be identificable. … -
Django forms submit radio button value shows up as None
I have a django form like this: class HelpForm (forms.form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('What can we help you with today?'), required=True, choices=() ) The choices for this form are populated in the views like this: form = HelpForm(initial=initial_data) form.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + \ [('', 'Other')] The default rendering of this form in the templates when called as {{form.queue}} is a drop down list. But I needed it as a radio button field, so I did this in my template for each drop down value: <input type="radio" name="help_form" id="order_issues" value="{{form.queue.field.choices.2.0}}"/> <label for="id_order_issues">{{form.queue.field.choices.2.1}}</label> Now, when I submit this form, the queue value shows up as None even though I have made a selection and because this is a mandatory field, the form submit fails. Of course the form has other fields and they work as expected. What am I doing wrong? Any help will be appreciated! -
Error installing anaconda in docker container
I am quite new to docker. I am trying to make docker container to deploy web application (made by Django) to cloud. However, when I try to build by following Dockerfile, I got the error Using Anaconda API: https://api.anaconda.org ResolvePackageNotFound: -python 3.5.3 3 FROM ubuntu:16.04 # package install & update RUN apt-get update && apt-get -y upgrade RUN apt-get -y install build-essential RUN apt-get -y install git vim curl wget RUN apt-get -y install python-dev \ libmysqlclient-dev FROM continuumio/anaconda3 ENTRYPOINT [ "/bin/bash", "-c" ] ADD env.yml /tmp/env.yml WORKDIR /tmp RUN [ "conda", "env", "create", "-f", "env.yml" ] #ADD . /code/ RUN [ "/bin/bash", "-c", "source activate BAUES" ] #RUN [ "/bin/bash", "-c", "python manage.py migrate" ] #RUN [ "/bin/bash", "-c", "python manage.py runserver" ] Does anyone know why I am getting this error? Thank you. -
Django strange NoReverseMatch
I haven't found a solution to this online yet. By all accounts this should be working, but I'm still getting this error. urls.py urlpatterns = [ ... url( regex=r'^create/$', view=views.CreateOrderView.as_view(), name='create' ), ...] views.py class UploadSampleSheetView(LoginRequiredMixin, FormView): def post(self, request): ... if form.is_valid(): ... return reverse("orders:create", kwargs={'sample_sheet':sample}) class CreateOrderView(LoginRequiredMixin, CreateView): def get(self, request): return render(request, 'pages/complete_order.html') The error message is Reverse for 'create' with arguments '()' and keyword arguments '{'sample_sheet': Sample: Sample object}' not found. 1 pattern(s) tried: ['orders/create/$'] But when I just go to that url (/orders/create/) the page is there... I've tried return reverse("orders:create", kwargs={'sample_sheet':sample}) return reverse("create", kwargs={'sample_sheet':sample}) return reverse(orders:create, kwargs={'sample_sheet':sample}) return reverse(CreateOrderView, kwargs={'sample_sheet':sample}) But none work. Other answers here haven't helped me so far, nor have the docs. What's going on? -
Django server on amazon not reachable
I have a django application running on my localserver and it's working good and I cloned the final version of my repo on my AWS Ubuntu Instance, and added the AWS Instance IP as a valid IP in my settings.py Also, I added the port 8000 y my security group configuration. But, at the moment to run it: # python3 manage.py runserver 0:8000 Performing system checks... System check identified no issues (0 silenced). But, at moment to test it in the browser, I get: This site can’t be reached [the IP] refused to connect. Also, I tried to configure IPTable sudo iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 8000 -j ACCEPT but, still now working. Am I doing something wrong? -
ChoiceFieldRenderer removed. What is the solution?
It seems very few people used it, but... I did. Here you can read: Some undocumented classes in django.forms.widgets are removed: SubWidget RendererMixin, ChoiceFieldRenderer, RadioFieldRenderer, CheckboxFieldRenderer ChoiceInput, RadioChoiceInput, CheckboxChoiceInput My source code is: from django.forms.widgets import ChoiceFieldRenderer, RadioChoiceInput, \ RendererMixin, Select class BootstrapRadioFieldRenderer(ChoiceFieldRenderer): outer_html = '<span {id_attr}>{content}</span>' inner_html = '<div class="radio">{choice_value}{sub_widgets}</div>' choice_input_class = RadioChoiceInput class BootstrapRadioSelect(RendererMixin, Select): renderer = BootstrapRadioFieldRenderer _empty_value = '' I really dont know how to convert this to make it work with 1.11 and later: they say: Use a custom widget template instead. Well. How? -
Installing mysql-python inside cygwin - mysql_config not found [Windows 7]
I'm trying to install mysql-python for use with Django, but receive the following error: File "setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found I've seen other questions say this is due to it not being in the path. My path looks like this: /cygdrive/c/Users/ddnm/Documents/skincare/skincare/bin:/home/ddnm/bin:/usr/local/bin:/home/ddnm/.local/bin:/usr/local/bin:/usr/bin:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files (x86)/NVIDIA Corporation/PhysX/Common:/cygdrive/c/Users/ddnm/.babun:/cygdrive/c/Python27:/cygdrive/c/Python27/Lib:/cygdrive/c/Python27/DLLs:/cygdrive/c/Python27/Lib/lib-tk:/cygdrive/c/Program Files/MySQL/MySQL Server 5.7/bin In particular, I believe the problem is that mysql_config for Windows is a perl script, so the following is confusing cygwin: master » which mysql_config mysql_config not found master » which mysql_config.pl /cygdrive/c/Program Files/MySQL/MySQL Server 5.7/bin/mysql_config.pl Any suggestions/thoughts? Thanks -
Python Django Jinja2: How to use the range value within the for-loop statement as the index of a list?
I trying to display the items within a list. This is my code: #Django view.py file def display(request): listone = ['duck', 'chicken', 'cat', 'dog'] lents = len(list_one) listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars'] return render(request, 'display.html', {'itemone' : listone, 'itemtwo' : listtwo, 'lents' : lents}) This is the display.html file that display the list: <table> <tr> <th>Pet</th> <th>Price</th> </tr> {% for numbers in lents %} <tr> <td>{{ itemone.numbers }}</td> <td>{{ itemtwo.numbers }}</td> </tr> {% endfor %} </table> but with no luck it won't show the result according to the index 'numbers' which suppose to be from '0' to '3' the 'td' tags remaining empty. -
Annotating Django query sets through reverse foreign keys
Given a simple set of models as follows: class A(models.Model): pass class B(models.Model): parent = models.ForeignKey(A, related_name='b_set') class C(models.Model): parent = models.ForeignKey(B, related_name='c_set') I am looking to create a query set of the A model with two annotations. One annotation should be the number of B rows that have the A row in question as their parent. The other annotation should denote the number of B rows, again with the A object in question as parent, which have at least n objects of type C in their c_set. As an example, consider the following database and n = 3: Table A id 0 1 Table B id parent 0 0 1 0 Table C id parent 0 0 1 0 2 1 3 1 4 1 I'd like to be able to get a result of the form [(0, 2, 1), (1, 0, 0)] as the A object with id 0 has two B objects of which one has at least three related C objects. The A object with id 1 has no B objects and therefore also no B objects with at least three C rows. The first annotation is trivial: A.objects.annotate(annotation_1=Count('b_set')) What I am trying to design now … -
Django Model many to many self referenced with extra attributes
How can I create models in Django like this. t1 (id) t12 (id_1, id_2, status) t2 (id)