Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign keys in extra() expression
I'm trying to use the Django extra() method to filter all the objects in a certain radius, just like in this answer: http://stackoverflow.com/questions/19703975/django-sort-by-distance/26219292 but I'm having some problems with the 'gcd' expression as I have to reach the latitude and longitude through two foreign key relationships, instead of using direct model fields. In particular, I have one Experience class: class Experience(models.Model): starting_place_geolocation = models.ForeignKey(GooglePlaceMixin, on_delete=models.CASCADE, related_name='experience_starting') visiting_place_geolocation = models.ForeignKey(GooglePlaceMixin, on_delete=models.CASCADE, related_name='experience_visiting') with two foreign keys to the same GooglePlaceMixin class: class GooglePlaceMixin(models.Model): latitude = models.DecimalField(max_digits=20, decimal_places=15) longitude = models.DecimalField(max_digits=20, decimal_places=15) ... Here is my code to filter the Experience objects by starting place location: def search_by_proximity(self, experiences, latitude, longitude, proximity): gcd = """ 6371 * acos( cos(radians(%s)) * cos(radians(starting_place_geolocation__latitude)) * cos(radians(starting_place_geolocation__longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(starting_place_geolocation__latitude)) ) """ gcd_lt = "{} < %s".format(gcd) return experiences \ .extra(select={'distance': gcd}, select_params=[latitude, longitude, latitude], where=[gcd_lt], params=[latitude, longitude, latitude, proximity], order_by=['distance']) but when I try to call the foreign key object "strarting_place_geolocation__latitude" it returns this error: column "starting_place_geolocation__latitude" does not exist What should I do to reach the foreign key value? Thank you in advance -
django login by second tab error
I am new to django. I am using django default LoginView. The problem is if user opens two tabs simultaneously and logs in in one of them, after trying to log in again on the second tab, an error arises Unexpected error occurred, try again and result is 403. Is there any special solution that user can login again? I assume loging again would expire the previous session and is not the best solution, maybe a way to just do nothing but refreshing page would be the best cure, but problem is how to realize she/he has already logged in. tnx -
django Restframework _ override rest_auth LoginView
I'm trying to override the rest_auth LoginView with my own LoginSerializer. class LoginSerializer(serializers.ModelSerializer): """Login Serialization for first_token""" first_token = serializers.CharField(write_only=True) phonenumber = serializers.CharField(write_only=True) class Meta: model = User fields = ['phonenumber', 'first_token'] def _validate_phonenumber(self, phonenumber, first_token): user = None if phonenumber and first_token: user = authenticate(phonenumber=phonenumber, first_token=first_token) else: raise exceptions.ValidationError('phonenumber does not exist') return user def validate(self, attrs): first_token = attrs.get('first_token') phonenumber = attrs.get('phonenumber') user = self._validate_phonenumber(phonenumber, first_token) attrs['users'] = user return attrs settings.py REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'blog.serializers.LoginSerializer', } when im trying to login errors comes up: KeyError at /api/login/ 'user' workspace/test-blog/env/lib/python3.6/site-packages/rest_auth/views.py in login self.user = self.serializer.validated_data['user'] my Usermodel is inheriting from AbstractBaseUser: class User(AbstractBaseUser): username = models.CharField(max_length=20, blank=True) email = models.EmailField(verbose_name='email address',blank=True, null=True, max_length=255, unique=True, default=None) phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, unique=True) first_token = models.ForeignKey(FirstToken, on_delete=models.SET_NULL, null=True, related_name='first_token', blank=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phonenumber' REQUIRED_FIELDS = [] I'm stuck. I need some help. -
Error trying to setup mysql with django
I'm new to django and I'm trying to connect it with mysql. I've never worked with setting up env variables before and I'm a bit confused as to this error when I run django-admin dbshell (venv) dhcp-ccc-12919:project user$ django-admin dbshell Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_fr om_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 327, in execute saved_locale = translation.get_language() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 187, in get_lang uage return _trans.get_language() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 55, in __getattr __ if settings.USE_I18N: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment v ariable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
One of my urls are not getting translated, giving me a 404 error
I'm currently having a issue with translation and url patterns on Django 1.11 using this approach. Here is my urls.py. from django.conf.urls import url # noqa from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from core.views import HomeView, SolutionsView, SolutionView urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), url(_(r'^solucoes$'), SolutionsView.as_view(), name='solutions'), url('{solutions}/{solution}$'.format( solutions=_(r'^solucoes'), solution='(?P<slug>[\w-]+)' ), SolutionView.as_view(), name='solution') ] The url with name solutions work, but solution does not, giving me a 404 error, even when I translate and run the compilemessages command. -
Can not run the `uwsgi --ini uwsgi.ini`, with the log of `no app loaded. going in full dynamic mode`
I have bellow config of uwsgi.ini, you can see the bellow config. I think there is no problem with my configuration but there still can not run uWSGI success. [uwsgi] chdir=/data/lll/repo/Qn uid=nobody gid=nobody module=Qn.wsgi:application socket=/data/lll/repo/Qn/uwsgi.sock master=true workers=5 pidfile=/data/lll/repo/Qn/uwsgi.pid vacuum=true thunder-lock=true enable-threads=true harakiri=30 post-buffering=4096 daemonize=/data/lll/repo/Qn/uwsgi.log then I run uwsgi --ini uwsgi.ini. get the bellow traceback in uwsgi.log: ... chdir() to /data/lll/repo/Qn your processes number limit is 4096 your memory page size is 4096 bytes detected max file descriptor number: 8192 lock engine: pthread robust mutexes thunder lock: enabled uwsgi socket 0 bound to UNIX address /data/lll/repo/Qn/uwsgi.sock fd 3 dropping root privileges after socket binding dropping root privileges after plugin initialization your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 486672 bytes (475 KB) for 5 cores *** Operational MODE: preforking *** *** no app loaded. going in full dynamic mode *** dropping root privileges after application loading *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 4004) spawned uWSGI worker 1 (pid: 4005, cores: 1) spawned uWSGI worker 2 (pid: 4006, cores: 1) spawned uWSGI worker 3 (pid: 4007, cores: 1) spawned uWSGI worker … -
Issues with Djang migrate on heroku
I am running (or trying) to run an app on heroku and so far it has been going well. However, now I would like to alter the table of my db and add an extra column. I did this locally by changing my django model and adding an extra column with this code: FAIRNESS = Choices("keineAngabe","Ja") fairness = models.CharField(choices=FAIRNESS, default="", max_length=20, null=True,blank=True) I ran locally then: python3 manage.py makemigrations python3 manage.py migrate Pushed the whole thing to heroku and then ran heroku python manage.py migrate However, heroku does not seem to change its postgres db-table accordingly and I get now errors such as column honoradar_datacollection.fairness does not exist When I try to look into the db. Can someone tell me what kind of reset etc. might help? -
Django alter table after model save
I have some django app to dynamically generate django models based on an description in an database. So if the description for the model in the database is changed, i wish to change the database representation for that dynamic-model, too. As example, if the name of the dynamic-model is changed, i wish to change the associated db table name for that dynamic-model, too: class DynaModel(models.Model): name = models.CharField(blank=False, max_length=255, unique=True) def save(self, *args, **kwargs): # ... check for name change, get name and dynamic-model ... with connection.schema_editor() as schema_editor: # rename the models table in the database schema_editor.alter_db_table(old_model, old_model._meta.db_table, new_table_name) return super(DynaModel, self).save(*args, **kwargs) The problem with the above code is, that i run in some table locks under sqlite, and so i get the following error: django.db.utils.NotSupportedError: Renaming the 'api_test' table while in a transaction is not supported on SQLite because it would break referential integrity. Try adding atomic = False to the Migration class. So obvious the change to the table, which describes the dynamic-model is not yet done, and the table is locked. I tought the solution must be, to alter the table after the commit of the save is done. But i did not find a … -
Generating A-Z, links that go to the same ClassBasedView and do a search
I have a list from A-Z (alphabet) and when a user click one any of them I need to do a search. I know, how to do the query: Post.objects.filter(name__istartswith='A') Because I want to use just one CBV, I need an approach for: 1) generate the urls patterns in the Django template -> (string.string.ascii_uppercase) 2) how to get the letter from the url pattern -
Django Custome Templatetags dont work in my production setup
I have my project structure as shown below project - utils - templatetags __init__.py date_format.py date_format.py has 2 filters, DEFAULT_FORMAT, CUSTOM_FORMAT I have a template which uses both DEFAULT_FORMAT and CUSTOM_FORMAT, I am also importing the tags using {% load date_format %} This works fine in my local environment, but strangely doesn't work in my production, It says Invalid filter: CUSTOM_FORMAT. Point to note here is DEFAULT_FORMAT comes ahead of CUSTOM_FORMAT in this template and yet one of the loads fine while the other throws error. Can someone point me in the right direction to sort this out. Thanks -
NoReverseMatch at /cart
I face this error even when i add forward slash / to the cart url its give no page found 404 No Reverse Match i think it because url routing it worked with me just for a few second without / for cart url and then it give me this error . urlpatterns = [ url(r'^', include('shop.urls', namespace='shop')), url(r'^cart', include('cart.urls', namespace='cart')), url(r'^admin/', include(admin.site.urls)), this is the view code @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart app urls from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.cart_detail, name='cart_detail'), url(r'^add/(?P<product_id>\d+)/$',views.cart_add,name='cart_add'), url(r'^remove/(?P<product_id>\d+)/$',views.cart_remove,name='cart_remove'), ] -
Django convert string into model for form
I'm trying to write a simple reusable Django app which links into the User model but since this can be replaced I need to link it into AUTH_USER_MODEL. This is fine within models but I have a formset based on the User so I need a form which I'm trying to populate as follows: from django.forms import ModelForm from django.forms.models import inlineformset_factory from optin.models import UserOptin from django.conf import settings #from django.contrib.auth.models import User USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', None) or \ 'auth.User' class UserForm(ModelForm): class Meta: model = USER_MODEL fields = '__all__' class UserOptinForm(ModelForm): class Meta: model = UserOptin fields = '__all__' UserOptinFormSet = inlineformset_factory(USER_MODEL, UserOptin, form=UserOptinForm, extra=0) This generates an error: AttributeError: 'unicode' object has no attribute '_meta' This is because USER_MODEL is a string. How do I convert it into the actual model? -
Python should I close the file after reading
I'm using Django 1.10 and Python 3.5.3 In one of the views the user is sending a file and I'm reading it like that: def create(self, request, *args, **kwargs): file_serializer = self.get_serializer(data=request.data) file_serializer.is_valid(raise_exception=True) if file_serializer.is_valid(): if 'file' in request.data: # hash file hasher = hashlib.md5() read_file = request.data['file'].read() hasher.update(read_file) current_file_hash = hasher.hexdigest() My question is - Should I close the file afterwards? Seems like I don't actually open it. -
pip install the latest version
I am new to python and django. In my requirements\common.txt I have the following line with version: django-simple-captcha==0.5.* the problem is that when I run pip install -r requirements\common.txt, as I have version 0.5.3 of that package, it wouldn't update it to latest version (0.5.6), only pip --upgrade requirements\common.txt would upgrade to latest version. Is there anyway to modify common.txt file so running pip install installs the latest version? I am asking because this file is going to be used by a couple of developers and if they have for example version 0.5.3 of that package already, it would'nt upgrade it and there are lots of packages needing upgrade. tnx -
Default Value in ModelForm from Database
I have a ModelForm in my Django App which should always display the latest given Option as default Input in the form but it's not working: models.py from django.db import models Anmeldung = ( ('1', 'Ja'), ('2', 'Nein'), ('3', 'Noch nicht entschieden'), ) Essen = ( ('1', 'Fleisch'), ('2', 'Fisch'), ('3', 'Vegetarisch'), ) class Eintrag(models.Model): Name = models.CharField(max_length=200) Anmeldung = models.CharField( max_length=2, choices=Anmeldung, default=Eintrag.objects.filter(Name=request.user).Anmeldung # Thats not working Essen = models.CharField( max_length=2, choices=Essen, default=1) pub_date = models.DateTimeField('date published') Only one row per user is in the data so that should not be a problem. How do I achieve this? Is models.py even the right place or do I have to write this into the views or form part? forms.py and models.py if it helps: forms.py from django import forms from .models import Eintrag class NameForm(forms.ModelForm): class Meta: model = Eintrag fields = ['Anmeldung', 'Essen'] views.py from django.shortcuts import render from django.utils import timezone from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from .forms import NameForm from .models import Eintrag @login_required() def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data … -
Fake admin login page in Django
I would like to have a fake login page, a.k.a honeypot, in Django. The real admin login page would have a different than standard URL, of course. I know that there is a django-admin-honeypot app, but it doesn't seem to work with Django 2+. Is there a quick way to create such a fake admin page which doesn't even have to have the IP logging capability? Alternatively, do you have a configuration of django-admin-honeypot that works with Django 2+? If yes, would you be able to share your URL file(s), please? Your help would be much appreciated. Best wishes, Marcin -
Django Count ForeignKey to ForeignKey data on CBV ListView
I don't have an idea what title should be on this question. but here the case. I have CBV (ListView) that list the data. But I need add other data from other model also. here my models.py class Employee(models.Model): name = models.CharField(max_length=255) class Periode(models.Model): start_date = models.DateField() end_date = models.DateField() class EmployeeSalary(models.Model): employee = models.ForeignKey(Employee, related_name='employee') periode = models.ForeignKey(Periode, related_name='periode') here what I need on my template.html: #table +-----------+----------------+---------------+-------------------------+ | Periode |Total Employee | Salary Data | Employee Not Have Data | +-----------+----------------+---------------+-------------------------+ | January | 100 | 50 | 50 | | February | 100 | 70 | 30 | +-----------+----------------+---------------+-------------------------+ this is what I do now. views.py class PeriodeListView(ListView): context_object_name = 'periodes' model = models.Periode template_list.html {% for periode in periodes %} <tr> <td>{{ periode.end_date.month }}</td> <td>{{ periode.periode.employee.count }}</td> <td>{{ periode.periode.count }}</td> <td>{{ }}</td> </tr> {% endfor %} periode & salary data work as well. but Total Employee & Employee Not have data I don't have an idea how to get it. trying with periode.periode.employee.count but din't work. -
Send email with Sendgrid in Django
I'm trying to send emails from a Django app using Sendgrid. I've tried many configurations, but I still doesn't get any email on my Gmail account. You can see my configurations bellow: settings.py: SEND_GRID_API_KEY = 'APIGENERATEDONSENDGRID' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'mySENDGRIDusername' EMAIL_HOST_PASSWORD = 'myEMAILpassword' #sendgrid email EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'MYEMAIL' #sendgrig email views.py from django.shortcuts import render from django.http import HttpResponse from .forms import ContactForm from django.core.mail import send_mail from django.conf import settings from django.template.loader import get_template def index(request): return render(request, 'index.html') def contact(request): success = False form = ContactForm(request.POST) if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") message = request.POST.get("message") subject = 'Contact from MYSITE' from_email = settings.DEFAULT_FROM_EMAIL to_email = [settings.DEFAULT_FROM_EMAIL] message = 'Name: {0}\nEmail:{1}\n{2}'.format(name, email, message) send_mail(subject, message, from_email, to_email, fail_silently=True) success = True else: form = ContactForm() context = { 'form': form, 'success': success } return render(request, 'contact.html',context) Do you guys know what could be happening? I can get the email locally and I can see it in the terminal, but no email can be sent at all. -
MYSQL making query case insensitive
I know mysql queries are case sensitive. But in one of my DB it is working as case insensitive. Both of the below queries are giving same results Select username from auth_user where username='shivam' and Select username from auth_user where username='ShivaM' I have used this DB in my django project and I generally use icontains and iexact lookup for case insensitive queries but not able to figure out the reason for above behaviour -
ManyToManyField serializer
i'm new to django. The version i'm using is 1.12 I have a a schema like this. There are many "designs" and each design can have any number of "patterns". my design model is like below from django.db import models from products.models import Product class Design(models.Model): name = models.CharField(max_length=200) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.CharField(max_length=200) def __str__(self): return self.name My design serializer is like below from rest_framework import serializers from .models import Design from rest_framework import serializers from patterns.models import Pattern class DesignsSerializer(serializers.ModelSerializer): patterns = DesignPatternSerializer(read_only=True, many=True) class Meta: depth = 1 model = Design fields = ('id','name','patterns') read_only_fields = ('id','name','patterns') The view for designs is as below from django.shortcuts import render from .models import Design from .serializers import DesignsSerializer from rest_framework import generics, filters # Create your views here. class ListDesignsByProducId(generics.ListCreateAPIView): serializer_class = DesignsSerializer def get_queryset(self): return Design.objects.filter(product_id__exact = self.kwargs.get('product_id')) My pattern model is like below. from django.db import models from datetime import date from designs.models import Design class Pattern(models.Model): design_id = models.ManyToManyField(Design) name = models.CharField(max_length=200) def __str__(self): return self.name My pattern serializer is as below from rest_framework import serializers from .models import Pattern class PatternSerializer(serializers.ModelSerializer): class Meta: depth = 1 model = Pattern fields = ('id','design_id','name') read_only_fields … -
After I exit from the remote server(CentOS-7), the `python3 manage.py runserver` will not work
I use the python3 manage.py runserver run the APIs of my Django-Rest-Framework project in my remote server(CentOS-7). But after I exit from the remote server(CentOS-7), the APIs will not service. If I login again to the remote server, APIs still not work, but I list the runserver command, it is there. [root@www ~]# ps aux | grep runserver lll 26439 0.0 0.5 275884 41704 ? S 07:29 0:00 python3 manage.py runserver lll 26443 3.1 1.0 380044 83264 ? S 07:29 10:22 /home/lll/repo/Qit/venv_dist/bin/python3 manage.py runserver root 32575 0.0 0.0 112680 972 pts/1 S+ 12:56 0:00 grep --color=auto runserver My question is, when I login the remote server to runserver the django, the APIs works, but I logout the remote server, the APIs can not access now. -
How do you populate a Material UI Menu with JSON values for Menu Items?
I'm new to Material UI and everything in the examples is static. Is there something to see for a JSON example? -
Django Models: __str__ with Foreign object's name
So I have a Product and ProductImage models. Each Product can have multiple ProductImage models. In the Django admin page, I want the product images to display the name of the product it's related to. class Product(models.Model): name = models.CharField(max_length=150) price = models.DecimalField(max_digits=9, decimal_places=2) product_count = models.IntegerField(blank=True, default=0) description = models.TextField() class ProductImage(models.Model): image_addr = models.FileField(upload_to='products/') product_id = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): q = <*name of the product with the product_id*> If a product image is that of a phone, say iPhone X, the image should display so. Now, the product images column only shows ProductImage objects. How do I solve this? -
Django aggregate(sum error
I'm trying to sum a complete field after filtering objects using pk. Views.py def items(request, pk): current_user = request.user selected_itemz = get_object_or_404(ItemIn, pk=pk) all_cats = Category.objects.all() cat_count = all_cats.count() item_count = ItemIn.objects.values_list('item_name', flat=True).distinct().count() # returns a list of tuples.. #all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum'] ItemOut_table = ItemOut.objects.all().filter(item_name=selected_itemz) ItemOut_quantity = ItemOut_table.aggregate(Sum('item_quantity'))['item_quantity__sum'] context = { #'all_units': all_units, 'item_count': item_count, 'cat_count': cat_count, 'current_user': current_user, 'ItemOut_quantity': ItemOut_quantity, 'selected_itemz':selected_itemz, } return render(request, 'townoftech_warehouse/item_details.html', context) Then I used an extra filter that I created which is subtract in my HTML HTML <br> <br> <p align="right"> الكمية الموجودة: {{ selected_itemz.item_quantity|subtract:ItemOut_quantity }} </p> <br> <br> and here is the tempaltetags file from django import template register = template.Library() @register.filter def subtract(value, arg): return value - arg Now I get the error : TypeError at /item/1/ unsupported operand type(s) for -: 'int' and 'NoneType' -
Displaying django DateTimeRangeField() in form as separate inputs
I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=127) slot = DateTimeRangeField() and the form as: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name', 'slot',] The form renders with 2 inputs for the lower and upper bounds of the date range. How can I render them as 4 inputs in the template? (lower date, lower time, upper date, upper time). Is there a widget that can do this?