Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AnonymousUser with django.test.client.login()
I'm testing login function. cls.pwd = '12345' # UserFactory is a package 'factory'to fill in with random data cls.user_1 = UserFactory(password=cls.pwd) cls.selenium = WebDriver() cls.client = Client() cls.client.login(username=cls.user_1.username, password=cls.pwd) So I can pass the login page, but then, when I do request.user to check the data for this user, it's an AnonymousUser -
Except database connection error in django
I am trying to write errors thrown by django into log files but instead of running except method django is trying to check database connection again and again. How to run except method after try in this case or is there any other method to write errors in log file when database connection is failed? settings.py import os, logging import mongoengine logger = logging.getLogger('__name__') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s') file_handler = logging.FileHandler('settings.log') file_handler.setLevel(logging.ERROR) file_handler.setFormatter(formatter) logger.addHandler(file_handler) try: mongoengine.connect( db="NewDataBaseV1", host="localhost", username='gsc-30310', ) except Exception as e: print('##########################################') logger.exception(e) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wizon&v8dk&5j!ml@ev9u3j5$ouc8m=*gnr2+2%dpx9t7)gpjh' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Celery 'celery', 'django_celery_beat', 'django_celery_results', # Apps 'UserAPI', # MongoUser # 'mongo_auth.MongoUser', # RestFrameWork 'rest_framework', ] AUTH_USER_MODEL = 'UserAPI.UserModel' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'RestUserAPI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
send click count to django view using ajax
I am trying to send click id of item to Django view on every click so that I can update count against every item. I achieved this by using ajax and javscript but there is some issue when id is sending id to Django view. what actually happening- when I click on any item(1)(first time) - nothing happen but when I click on any item(let suppose 2) - then it send 1 and 2 again when I click on item 3 - it send 1,2,3 I don't know why it is behaving like this. it should send only one item it which is clicked my code is- {% for solution in item %} <ul> <li >{{solution.solution_name}} <a href="#"><i value="{{solution.id}}" class="fa fa-download down" aria-hidden="true" onclick="count(document.getElementById('fname_{{solution.id}}').value)"> <input type="text" id="fname_{{solution.id}}" value="{{solution.id}}"></i></a> </li> </ul> {% endfor %} my ajax part- <script> function count(a) { var id = parseInt(a); $('.down').click(function(e){ console.log("clicked item id is") e.preventDefault(); console.log(id); $.ajax({ type:'POST', url: '/solutions/count', data: { 'id': id }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }) } </script> -
Django: Call function once on login
I implemented Segment.io in my Django application. Once the user logs in I have to call analytics.identify once. Currently, I call it every time on every page load as long {% if user.is_authenticated %} is the case. Do you have any idea how I can only call it once after the user logged in? <script type="text/javascript"> {% if user.is_authenticated %} analytics.identify('{{ user.email }}', { 'first_name': user.first_name, 'last_name': user.last_name, }); {% endif %} </script> -
Style form field in class-based view in Django
I am using class-based views to create a form on a website. The code below is working so far. But I need to add a custom CSS class (box-message) to the message field so it can be styled correctly. How can I do that? This is what I have accomplished so far. # view.py ---- from django.views.generic.edit import CreateView from .models import CandidateInfo class PostForm(forms.ModelForm): class Meta: model = CandidateInfo fields = ("name", "email", "message") class ContactView(CreateView): form_class = PostForm model = CandidateInfo template_name = "index_test.html" # models.py ---- from django.db import models from django.urls import reverse class CandidateInfo(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) message = models.TextField() def __str__(self): return self.name def get_absolute_url(self): return reverse("index_text") -
Memcached Local and Server Behaving Differently
Im using Memcache locally with the following config in my Django app, and everything is working fine with fragment caching like {% cache 864000 'stream' stream_id %} ... {% endcache %}. If I dont put data in cache tags, then it doesnt get cached. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } But the same fragment caching on remote Heroku server (using MemCachier) caches the entire view indefinitely, even if the data is outside of the cache tags. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } Why doesnt local and remote behave the same way? -
Django REST Framework: How to set default value with function?
I have my api form like this. Number 1: _____ Number 2: _____ Result : ______ I want to get the result with divide operation(num1/num2) when number 1 and number 2 is entered. Is it possible to set the default value with function and return the result? Or any others way to do this? What can I add in serializers.py? -
OperationalError at /new_schedule/4/
I get the error OperationalError at /new_schedule/4/ The exception value is no such table: zoo_animal_feeders_schedule Here is my 'new_schedule' view: @login_required def new_schedule(request, animal_id): """add a new schedule for the animal""" animal = Animal.objects.get(id=animal_id) animal_type = animal.animal_type if request.method != 'POST': #create 3 different checkboxes for the meals and if they check it, add that meal to their schedule form = ScheduleForm() else: #POST data submitted form = ScheduleForm(data=request.POST) if form.is_valid(): new_schedule = form.save(commit=False) new_schedule.animal = animal new_schedule.save() return HttpResponseRedirect(reverse('zoo_animal_feeders:animal', args=[animal_id])) context = {'animal':animal, 'animal_type':animal_type, 'form':form} return render(request, 'zoo_animal_feeders/new_schedule.html', context) Here is the new_schedule.html file: {% extends "zoo_animal_feeders/base.html" %} {% load bootstrap3 %} {% block header %} <h2><a href="{% url 'zoo_animal_feeders:animal' animal.id %}">{{ animal }}</a></h2> <h2>Add new schedule:</h2> {% endblock header %} {% block content %} <form action="{% url 'zoo_animal_feeders:new_schedule' animal.id %}" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name='submit'>add schedule</button> {% endbuttons %} </form> {% endblock content %} I'm not sure why its saying I don't have a table made. I have already tried all of the tricks with the manage.py migrate --run-syncdb and deleting migrations etc. Let me know if I need to include any more information. -
Django Model ImageField upload_to won't take a function as argument
I'm trying to rename my a image when its uploaded. I can't seem to get it to work. class Article(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to=photo_file_name, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() url = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.title def photo_file_name(self, filename): extension = filename.split('.')[-1] filename = 'cover_photo_{}.{}'.format(self.id, extension) return os.path.join('articles/media/articles/photos/coverphotos/', filename) None of the answers have been able to help me. I get a NameError: name 'photo_file_name' is not defined. Any help would be much appreciated. Thank you! -
How to implement time tracking in django
I'm developing an employee attendance app for my office. The general idea is similar to https://toggl.com. So, when the employee comes to the office, he can log in to the app, and hit "Start" button, so the system can record the time/hours he spends on the office. And before he back home (Let's say, after 8 hours of work), he should click "Stop" button, so the timer will stop and the system will save the recorded time to the database. How do I implement this? I'm aware there is a similar question like this ( How to implement countdown timer in django), but since I'm a newbie, so this not help me much. I expect a more detailed explanation/example. Thank you! -
Django:How to add divide operation to specific field at django admin site?
Is there any way to add the divide operation for a specific field? for example: Number 1:_________ Number 2:_________ Result : _________ My admin site form is something like this. I want the system automatically calculate the result when the user enters number 1 and number 2. Is there anything I should add in forms.py or models.py? forms.py class Form(ModelForm): class Meta: model = Number fields = ['id','num1','num2','result'] models.py class Number(models.Model): id = models.AutoField(primary_key=True) num1 = models.CharField(max_length=100) num2 = models.CharField(max_length=100) result= models.CharField(max_length=100) -
error rebuilding the index using django-elasticsearch-dsl
I am trying to connect to a existing index in my local elastic search engine. I am using django-elasticsearch-dsl package. I followed this tutorial to do that. https://github.com/sabricot/django-elasticsearch-dsl please note that,I already developed my django app[website] with mysql database. I have some unstructured text data indexed in elastic-search. I want to develop this 'advanced search' HTML page for users querying data frpm elasticsearch. I followed almost everything upto python manage.py search_index --rebuild but once I excute it it asked Are you sure you want to delete the 'website_data_discovery' indexes? [n/Y]: when I say n it will be aborted. when I say Y it gives a lengthy error saying django.db.utils.ProgrammingError: Table 'crdc.website_data_discovery' doesn't exist This is my file structure. crdc website ->__pycache__ -> media ->migrations ->static ->templates ->__init__.py ->admin.py ->apps.py ->documnets.py ->forms.py ->models.py ->tests.py ->urls.py ->views.py manage.py This is my settings.py/crdc. ###more codes here INSTALLED_APPS = [ 'website.apps.WebsiteConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_elasticsearch_dsl', ] ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } ###more codes here This is documents.py/website from django_elasticsearch_dsl import DocType, Index from .models import Data_Discovery data_discovery = Index('website_data_discovery') data_discovery.settings( number_of_shards = 5, number_of_replicas = 1,) @data_discovery.doc_type class Data_DiscoveryDocument(DocType): class Meta: model = Data_Discovery fields = ['extracted_text', 'source_type'] this … -
Django queryset (filter) based on user logged and foreign key other model
Here are my models: class Product(models.Model): name = models.CharField(max_length=200, db_index=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Order(models.Model): name = models.CharField(max_length=30) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) schedule = models.CharField(max_length=7) View: def order_list(request): orders = OrderItem.objects.filter(id__product=id, product_id=Product.objects.filter(created_by=request.user)) return render(request, 'orders/order/order_list.html', {'orders': orders}) I'm new in Django. I'd like to create view based on user who created the product. So when that user login to the web they can see the order item list. Thank you for your help. -
How to loop through crispy fields
How can I arrange my form in a table? I had a normal form and I was arranging it in my template like this. <table border="0" > {% for field in form %} <tr > <td> <label for="{{ field.label }}">{{ field.label_tag }} {% if field.field.required %}<span style="color:red"; class="special_class">*</span>{% endif %}</label> </td> <td> {{ field }} </td> </tr> {% endfor %} </table> Now I want to use crispy forms. but couldn't figure out how to display my form. of cause it has works with this. {% load crispy_forms_tags %} {% crispy form %} but that was not arranging my fields well, how can I access these fields by a loop? Any help would be greatly appreciated. -
Requests and Django, "Incorrect type. Expected pk value, received InMemoryUploadedFile" when uploading file
When making an API (Django 1.11) request with requests, I'm unable to make a successful POST request that contains both a file and a ForeignKey in the body. urls.py urlpatterns = [ .... url(r'^dataset/visual$', api_views.VisualList.as_view(), name='api-visual'), .... ] models.py class Visual(models.Model): class Meta: verbose_name_plural = "Visuals" name = models.CharField(max_length=30) description = models.CharField(max_length=75, blank=True, null=True) visual = models.FileField(upload_to='visuals/') uploaded_at = models.DateTimeField(auto_now_add=True) document = models.ForeignKey(Document) <--- LOOK HERE def __unicode__(self): return self.name views.py class VisualList(generics.ListCreateAPIView): parser_classes = (MultiPartParser, FormParser, FileUploadParser) queryset = Visual.objects.all() serializer_class = VisualSerializer class VisualDetail(generics.RetrieveUpdateDestroyAPIView): parser_classes = (MultiPartParser, FormParser) queryset = Visual.objects.all() serializer_class = VisualSerializer serializers.py class VisualSerializer(serializers.ModelSerializer): class Meta: model = Visual fields = '__all__' my_requests.py response = requests.request( 'POST', 'http://127.0.0.1/api/dataset/visual', files={'name': 'Hello World', 'description': 'from API', 'document': 5, 'visual': ('hello_world.html', open('HELLOWORLD.html', 'rb'))}) When I set document = models.ForeignKey(Document, null=True) in models.py, and I remove the document key from the files param, I am able to upload the file just fine. However, when I include document and make it a mandatory field, I get the error: "Incorrect type. Expected pk value, received InMemoryUploadedFile" It definitely looks like I'm passing the correct type for pk as an integer of a document that definitely exists. I have other models referencing … -
NoReverseMatch at /animal_types/10/
I get an error NoReverseMatch at /animal_types/10/ The exception value is: Reverse for 'animal' with arguments '('',)' not found. 1 pattern(s) tried: ['animal\\/(?P<animal_id>[0-9]+)\\/$'] Here is my views code for animal: @login_required def animal(request, animal_id): """shows a single animal and the schedule associated""" animal = Animal.objects.get(id=animal_id) schedule = animal.schedule_set.order_by('-date_added') context = {'animal':animal, 'schedule':schedule} return render(request, 'zoo_animal_feeders/animal.html', context) Any help is appreciated. Let me know if I need to include more information. Here are my main urls: urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('zoo_animal_feeders.urls')), ] Here is the app specific url that its trying to execute: #Page for accessing an animal path('animal/<int:animal_id>/', views.animal, name='animal'), It won't allow me to put in the traceback because it is too much code (its a very long traceback). -
Django REST Framework: creating user does not require password, and password is not saved when sent
I'm using DRF to create a simple signup/login application and I am having trouble requiring the password when creating a new user. I've lurked through SO and the documentation but haven't been able to figure this out. serializers.py from django.contrib.auth.models import User from rest_framework.serializers import HyperlinkedModelSerializer class UserSerializer(HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups', 'first_name', 'last_name', 'date_joined', 'last_login' ) write_only_fields = ('password',) views.py from django.contrib.auth.models import User, Group from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet from rest_framework.generics import CreateAPIView from .serializers import UserSerializer class UserReadOnlyViewSet(ReadOnlyModelViewSet): """ API endpoint that allows users to be viewed. """ authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class UserCreateView(CreateAPIView): """ API endpoint that allows users to be created. """ serializer_class = UserSerializer urls.py from django.urls import path, include from rest_framework import routers from .views import UserReadOnlyViewSet, UserCreateView router = routers.DefaultRouter() router.register(r'users', UserReadOnlyViewSet) urlpatterns = [ path('', include(router.urls)), path('signup/', UserCreateView.as_view()), ] I am able to list user(s) at the endpoint users/ | users/<pk>/, and I am able to create a user by posting to signup/, with the following JSON data: { "username": "new_user", "password": "12345678", "email": "fulano@dominio.com" } I am … -
ngrok in docker can not connect to http://localhost:8000 webserver
I am working on a localhost django webserver http://localhost:8000, which works fine. Meanwhile i need ngrok to do the port forwarding, ngrok http 8000, which works fine too. Then I want to put ngrok, postgres, redis, maildev, etc all in docker containers, all others works fine, except ngrok. ngrok failed to contain to localhost:8000. I understand why, i suppose because ngrok is running on a seperate 'server 'and the localhost on that server does not have web server running. I am wondering how i can fix it. I tried in my docker-compose file with network_mode: "host", it is not working (MacOS). I tried to use host.docker.internal, but as I am a free plan user, ngrok does not allow me to specify a hostname. any help is appreciated! Thanks. here is my docker-compose file: ngrok: image: wernight/ngrok ports: - '4040:4040' environment: - NGROK_PORT=8000 - NGROK_AUTH=${NGROK_AUTH_TOKEN} network_mode: "host" -
User sessions lost in Django
I'm running a site on Django that has been in operation for a few years. We use sessions with a Redis cache backend. After a reasonably minor update of Django to 1.11.16 from an earlier 1.11.* version, we're seeing that user sessions are being ended for no obvious reason. One dependable way to get a session to end is to navigate to a url that causes a history.replaceState() to replace the URL. As soon as that happens - the old sessions ends, the user is logged out, and a new session is started. Any clues would help. -
NoReverseMatch at /animal_types/9/
I get an error NoReverseMatch at /animal_types/9/ The exception value is: Reverse for 'animal' not found. 'animal' is not a valid view function or pattern name. Here is my views code for animal: @login_required def animal(request, animal_id): """shows a single animal and the schedule associated""" animal = Animal.objects.get(id=animal_id) schedule = animal.schedule_set.order_by('-date_added') context = {'animal':animal, 'schedule':schedule} return render(request, 'zoo_animal_feeders/animal.html', context) Any help is appreciated. Let me know if I need to include more information. -
Set the 'id' attribute using template tags
Is there a way to set the 'id' attribute in the template? let's say i pass my form as context in my view so when I render some field from my form like {{form.field1}} can I set the 'id' something like {{form.fiel1|attrib=('id':'id_forfieldone')}} I know that can be done in the form class definition, but I need to do it in the template. -
Errno 2 - Django - File Path
I am trying to write to a file named data.txt which is within my templates directory, but it is saying '[Errno 2] No such file or directory: 'schedule_app/text_files/data.txt''. Any suggestions? I am trying to update a text file based off of query strings. I was only using f.write('hello') to test if it was currently working. -
purchase of movie tickets
i have need to realize purcharing seating in cinema, but i dont know how to transmit chosed seating. class Seance(models.Model): class Meta: verbose_name = "Сеанс" verbose_name_plural = "Сеансы" unique_together = ('hall', 'time') film = models.ForeignKey('Film', on_delete=models.CASCADE) hall = models.ForeignKey('Hall', on_delete=models.CASCADE) time = models.DateTimeField() format_3D = models.BooleanField() price = models.PositiveIntegerField() class Tickets(models.Model): buy_time = models.DateTimeField(auto_now_add=True) seance = models.ForeignKey(to=Seance, on_delete=models.DO_NOTHING) row = models.PositiveIntegerField() place = models.PositiveIntegerField() class HallRow(models.Model): places = models.PositiveIntegerField(verbose_name='places') row = models.PositiveIntegerField(verbose_name='row') hall = models.ForeignKey('Hall', on_delete=models.CASCADE, verbose_name='hall') class Hall(models.Model): name = models.CharField(max_length=20, unique=True) So, how can i transmit in view needed seatings? -
Show attribute of foreign key in add_form in Django
Is it possible show an attribute of foreign key in add_form django? For example: #models.py class Test(models.Model): name = models.CharField(max_length=60, db_column='Name') # Field name made lowercase. product=models.ForeignKey(Product, on_delete=models.DO_NOTHING) class Product(models.Model): id = models.AutoField(db_column='Id', primary_key=True) description = models.CharField(max_length=60, db_column='Description') #admin.py class TestAdmin(admin.ModelAdmin): fields = ['name','product','product__description'] readonly_fields = ['product__description'] Naturally this code raise exception the ErrorFields in 'product__description'. But, does exist a way to show the 'product__description' when I insert an entry of model Test? Thanks -
'GenericForeignKey' object has no attribute 'choices'
when ever i run my django admin for posRecord i run into this error Exception Type: AttributeError Exception Value: 'GenericForeignKey' object has no attribute 'choices' Exception Location: /home/vagrant/.virtualenvs/venv/lib/python3.6/site-packages/django/contrib/admin/filters.py in <lambda>, line 292 not quite sure what GenericForeignKey object attribute choice its looking for. from django.contrib import admin from . import models @admin.register(models.POSRecord) class POSRecord(admin.ModelAdmin): list_display = ['pos_content_type', 'pos_id', 'pos', 'object_content_type', 'object_id', 'object', 'data'] list_filter = ['pos_content_type', 'pos_id', 'pos', 'object_content_type', 'object_id', 'object', 'data'] fields = ['pos_content_type', 'pos_id', 'pos', 'object_content_type', 'object_id', 'object', 'data'] and this is my pos record GenericForeignKey model. class POSRecord(models.Model): id = SmallUUIDField(default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID') # FK to a POS integration (e.g., SquareCredentials) pos_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_integration', on_delete=models.CASCADE) pos_id = models.CharField(max_length=100) pos = GenericForeignKey('pos_content_type', 'pos_id') # FK to anything in our system (e.g., Item, ModifierList, Location) object_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_object', on_delete=models.CASCADE) object_id = models.CharField(max_length=100) object = GenericForeignKey('object_content_type', 'object_id') # Raw JSON data from the POS api data = JSONField() class Meta: indexes = [ models.Index(fields=('pos_content_type', 'pos_id')), models.Index(fields=('object_content_type', 'object_id')), ] unique_together = [ ('pos_content_type', 'pos_id', 'object_content_type', 'object_id'), ]