Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable text input in datepicker in Django
I'm building a bus reservation project in django1.10. I want to disable user input in the date field. I'm using this date-picker: https://bootstrap-datepicker.readthedocs.io/en/latest/ I want to disable text input. How can I do so? There seems to be no such option in documentation. <script type="text/javascript" src="{% static 'javascript/jquery-1.11.3.min.js' %}"></script> <script type="text/javascript" src="{% static 'javascript/bootstrap-datepicker.min.js' %}"></script> <script> $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body"; date_input.datepicker({ format: 'dd/mm/yyyy', container: container, todayHighlight: true, orientation: "bottom right", autoclose: true, maxViewMode: 0, startDate: "0d", endDate: "+31d", }) }) </script> Let me know if you need any more information. -
Take list of ids in view
I use django-reversion app in my project. I have modal "Product" with ManyToMany field "comments". I have page with reversions list. And it shows me in comments field id of comments. What the best way to take that id-s in view? I mean I want to show in template the comment information (author, text, created) not only id. Is it possible? I am little bit comfused. models.py: @reversion.register() class Product(models.Model): comments = models.ManyToManyField("Comment") class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) views.py: def product_reversions(request, product_code): product = get_object_or_404(Product, pk=product_code) versions = Version.objects.get_for_object(product) for version in versions: comments = ??? (list of comment ids) -
Why different records in the model?
I have this abstract models. class Abstract_Detail(models.Model): """ Abstract models for detail in subassembly """ name = models.CharField(max_length=50, blank=True, null=True) mark = models.CharField(max_length=50) weight_end = models.FloatField(blank=True, null=True, default=0) class Meta: abstract = True unique_together = ('name', 'makr') And Details model. class Detail(Abstract_Detail): """ Detail """ auto_area = models.FloatField(blank=True, null=True, default=0.0) size_workpiece = models.CharField(max_length=10, blank=True, null=True) weight = models.FloatField(blank=True, null=True, default=0) product = models.ManyToManyField(Products, through='Structure_production') subassembly = models.ManyToManyField(Subassembly, through='Structure_production') material = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True, blank=True) assortament = models.ForeignKey(Sortment, on_delete=models.SET_NULL, null=True, blank=True) class Meta(): unique_together = ('name', 'makr') What is the problem: in some cases, when you change weight_end in admin Detail, when executing the below code, a new record is created with a combination of the name and mark, which is already in the model. detail, sost = Detail.objects.get_or_create( name=name, makr=makr, defaults={'size_workpiece': size, 'material': material, 'assortament': sortament}) Is there an explanation? Read the documentation fully, the answer is not found. -
model forms fiels not displayed in views in django
The problem is that the first_name, last_name and email fields are not displayed in browser. The command prompt is showing no error and server is running smoothly. I cant figure out whats the problem.Here is my code.I am using django 1.11 and python 3.6 models.py from django.db import models # Create your models here. class signup(models.Model): first_name=models.CharField(max_length=120,null=True,blank=True) last_name=models.CharField(max_length=120,null=True,blank=True) email=models.EmailField() timestamp=models.DateTimeField(auto_now_add=True,auto_now=False) updated=models.DateTimeField(auto_now_add=False,auto_now=True) def __str__(self): return self.email forms.py from django import forms from .models import signup class sign_up_form(forms.ModelForm): class Meta: model = signup fields='__all__' views.py from django.shortcuts import render,render_to_response from django.template import RequestContext from .forms import sign_up_form # Create your views here. def home(request): form = sign_up_form() return render(request,'signup.html',) signup.html <!DOCTYPE html> <html> <head> </head> <body> <h1>join now</h1> <form method="POST" action="">{% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </body> </html> -
Django: Insert multiple charts
I found this link https://code.djangoproject.com/wiki/Charts to create charts in Django. I am pretty new to Django, can you please show how I can insert the gif generated by this code in a html page. My requirement is that I have to insert multiple charts in same page, is it possible to achieve that? It would be helpful if I can get a template html page? or a django project that I can use for displaying charts. -
Django signals permissions with db.models
I encounter the following problem when I try to create a app_B/model_B using signals.post_save sent by a creation of app_A/model_A: app_B/models.py: from django.db import models from django.db.models import signals from app_A.models import model_A class model_B(models.Model): item = models.OneToOneField(model_A, on_delete=models.CASCADE, primary_key=True) def create_model_B(sender, instance, created, **kwargs): if created: model_B.objects.create(item=instance) signals.post_save.connect(create_model_B, sender=model_A, weak=False, dispatch_uid='models.create_model_B') As simple as that, in my template the model_A form works perfectly, and the post_save creates automatically model B as well when I'm logged as a staff user. As non-staff user (but not anonymous), it does not work: model_A and model_B are not created. It returns the HttpResponseRedirect of the model_A view, whatever the permissions are setup right for those apps. I don't know how to debug that either ... -
CSS not loading on gcloud app engine?
So, I'm trying to host a website on the google cloud app engine, but css and other static files are not showing up. Here is the relevant directory structure: myapp -app.yaml -manage.py subapp -apps.py -models.py -urls.py -views.py static -style.css And the relevant portion of app.yaml: runtime: python env: flex api_version: 1 threadsafe: yes handlers: - url: /static static_dir: static - url: .* script: myapp.wsgi.application I would expect that when I go to https://myapp.appspot.com/static/style.css, they see the style.css file, but instead I get the 404 page not found error, and I see that gcloud compares the 'static/style.css' against the list of urls found in urls.py instead of the static directory specified in app.yaml. What could be going wrong? -
Appropriate filesystem permission for apache2 + django(mod_wsgi) on OS X
I'm getting tons and tons of the following in my apache error.log: Current thread 0x00007fff730d2000 (most recent call first): [Sat Apr 08 19:49:59.958559 2017] [core:notice] [pid 38953] AH00052: child pid 38968 exit signal Abort trap (6) [Sat Apr 08 19:49:59.960853 2017] [wsgi:warn] [pid 38969] (13)Permission denied: mod_wsgi (pid=38969): Unable to stat Python home /Users/user/Documents/VirtualEnvs/securedash. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: unable to load the file system codec ImportError: No module named 'encodings' I've tried countless filesystem permission and ownership combinations per the various suggestions found googling, but nothing has worked so far. I'd rather not open up my entire home directory with a chmod -R 777 ~/ to get this working. What permissions does apache need for 1. My virtualenv and 2. The django project itself? Are there any other areas that I need to grant access to apache that I'm missing? Thanks! -
NSQ/PYNSQ consume several messages at once
I am very new to NSQ and Async code in python. Any help i would appreciate Have a Topic(Records) of messages (say 1000) each containing uuid of a record stored in Database (using Django ORM). There are 10 records with distinctive uuids, so some messages have same uuid class Record(models.Model): uuid = models.CharField(max_length=225) count = models.IntegerField(null=False, blank=False) objects = BulkUpdateManager() In most simple case. When consume a message, i want to increment the count of that record(with the corresponding uuid) by 1 in database What i want to achieve is for message that currently has count of uuid < 10, update the count right away for message that has current count of uuid >= 10, wait for a bulk update So i defined a consumer to consume this initial Queue, update the record count if it is less than 10. Produce it the second Queue(Topic)-large if current count is bigger than 10 @gen.coroutine def write_message(topic, data, writer): response = yield gen.Task(writer.pub, topic, data) def differ_number(message, writer): message.enable_async() data = json.loads(message.body) record = Record.objects.get(uuid=data['video_id']) if video.count < 10: video.count += 1 video.save() message.finish() else: topic = "large" output_message = json.dumps(data) write_message(topic, output_message, writer) message.finish() def main(): writer = nsq.Writer(['127.0.0.1:4150']) handler = … -
'A server error occurred. Please contact the administrator.' at django 1.8.11
I updated my django from 1.7 to 1.8 and my server isn't running anymore. What I did: Tried to install python 3.6: nothing happened after I run the installer. Uninstalled Django 1.7 and installed 1.9. Unfortunately this version brings me trouble (server didn't even starts). Uninstalled 1.9 and installed 1.8. Now it's getting this error. I'm on a macOS Sierra. 10.12.3. My python version is 2.7. I need version 1.8 in order to use the 'from rest_framwork.view import APIView' Can someone help me? Here's the log: System check identified no issues (0 silenced). April 09, 2017 - 01:35:43 Django version 1.8.18, using settings 'connectedin.settings' Starting development server at http://192.168.0.101:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/core/handlers/base.py", line 207, in get_response return debug.technical_500_response(request, *sys.exc_info(), status_code=400) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/views/debug.py", line 97, in technical_500_response html = reporter.get_traceback_html() File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/views/debug.py", line 384, in get_traceback_html return t.render(c) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/template/base.py", line 210, in render return self._render(context) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/template/base.py", line 202, in _render return self.nodelist.render(context) File "/Library/Python/2.7/site-packages/Django-1.8.18-py2.7.egg/django/template/base.py", line 905, in render bit = self.render_node(node, context) … -
Django: redis-cache does't work?
I use django-redis-cache(https://github.com/sebleier/django-redis-cache) for my cache framework. This is part of settings.py: CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'redis://localhost:6379/0', 'TIMEOUT': None, }, } But when I use cache in viewside, cache type is django.core.cache.DefaultCacheProxy, not Redis one!. from django.core.cache import cache . . print(type(cache)) cache.set('data', matr) cache.set('titles', titles) . . What should I do to use redis cache? -
Adding data into the database with django by pressing enter
I do not see what I am doing wrong when trying to add data into the database. When I am pressing the button Submit, nothing is entered in the database. The same happens when pressing the key enter. Here is my html file. <script> $(document).keypress(function(event) { if (event.keyCode == 13 || event.which == 13) { alert('enter key is pressed'); event.preventDefault(); } }); </script> <div class="col-md-6 col-md-offset-3"> <form method="POST" action=""> <p> {% csrf_token %} <input type="hidden" value="{{post.id}}" /> <div class="col-xs-16" style="margin: 0; 0;padding: 3%;"> <label for="inputsm">Oracle</label> <input class="form-control input-md" type="text" value="{{ post }}"> <input type="submit" value="Submit" style="display: none" /> {{ form.body }} <button type="submit" value="Submit" class="btn btn-success">Submit</button> </p> </div> </form> </div> Here is the views.py def post_list(request): posts = Post.objects.all() category = Category.objects.all() context = { 'posts':posts, 'cat':category, } return render(request, 'journal/post_list.html', context) def add_post(request): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_details', pk=post.pk) return render(request, 'journal/post_list.html', {'post': post}) else: form = CommentForm() context = { "form": form, } return render_to_response('journal/post_list.html', context) -
sed Replace django user with something else
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database', 'USER': 'user', # I wanna replace <-- this with 'USER': 'anotheruser' 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Using Fabric, I'm doing this: local(sed('./{}/settings.py'.format(PROJECT_NAME), "\'USER\': \'user\'", "\'USER\': \'anotheruser\'")) I then get the error: run: sed -i.bak -r -e 's/\'USER\':\'user\'/\'USER\':\'anotheruser\'/g' "$(echo ./PackagetoMe/settings.py)" out: bash: -c: line 0: unexpected EOF while looking for matching `'' out: bash: -c: line 1: syntax error: unexpected end of file I've also tried without the backslashes and same error local(sed('./{}/settings.py'.format(PROJECT_NAME), "'USER': 'user'", "'USER': 'anotheruser'")) How can I do it properly? -
ProgrammingError: (1146, "Table clearinghouse.control_experiment doesn't exist")
I have to tables in models.py: class GeniUser(DjangoUser): usable_vessel_port = models.IntegerField("GeniUser's vessel port") affiliation = models.CharField("Affiliation", max_length=200) user_pubkey = models.CharField("GeniUser's public key", max_length=2048) user_privkey = models.CharField("GeniUser's private key [!]", max_length=4096, null=True) api_key = models.CharField("API key", max_length=100, db_index=True) donor_pubkey = models.CharField("Donor public Key", max_length=2048) free_vessel_credits = models.IntegerField("Free (gratis) vessel credits", db_index=True) date_created = models.DateTimeField("Date added to DB", auto_now_add=True, db_index=True) date_modified = models.DateTimeField("Date modified in DB", auto_now=True, db_index=True) class Experiment(models.Model): expe_name = models.CharField(max_length=30) geni_user = models.ForeignKey(GeniUser, db_index=True) researcher_name = models.CharField(max_length=30) researcher_institution_name = models.CharField(max_length=30) researcher_email = models.EmailField() researcher_address = models.CharField(max_length=64) irb_officer_email = models.EmailField() goal = models.CharField(max_length=256) Then, once the user is registered, I have a form to register an experiment. In forms.py: class RegisterExperimentForm(forms.ModelForm): class Meta: model = Experiment exclude = ['geni_user'] expe_name = forms.CharField(label="Experiment name", error_messages={'required': 'Enter a experiment name'}, required = True) researcher_name = forms.CharField(label="Researcher name", error_messages={'required': 'Enter a researcher name'}, required = True) researcher_address = forms.CharField(label="Name and address of researcher's home institution", error_messages={'required': 'Enter a Name and address of researchers home institution'}, required = True) researcher_email = forms.CharField(label="Researcher's email address", widget=forms.EmailInput(attrs={'class': 'form-control','pattern': "(?!(^[.-].*|[^@]*[.-]@|.*\.{2,}.*)|^.{254}.)([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+@)(?!-.*|.*-\.)([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,15}"}), error_messages={'required': 'Enter an E-mail Address'}, required = True) researcher_institution_name = forms.CharField(label="Name of home institution's IRB officer or contact person", error_messages={'required': 'Name of home institutions IRB officer or … -
Django registration test script not running
I'm trying to write unit a test for a custom registration form on my Django website, but having an error when I run the python manage.py test. I'm trying to run the following test: def test_registration_valid_view(self): ''' ''' pass user_count = User.objects.count() form_data = {'username': 'test@example.com', 'first_name': 'Test', 'last_name': 'Person', 'password1': 'admin123', 'password2': 'admin123'} response = self.client.post("/sign-up/", form_data) self.assertEqual(response.status_code, 200) self.assertEqual(User.objects.count(), user_count+1) But I'm getting the following error: ====================================================================== ERROR: test_registration_valid_view (accounts.tests.RegistrationTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/haldunanil/Desktop/cashonly/accounts/tests.py", line 59, in test_registration_valid_view form_data) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/test/client.py", line 541, in post secure=secure, **extra) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/test/client.py", line 343, in post secure=secure, **extra) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/test/client.py", line 494, in request six.reraise(*exc_info) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/utils/six.py", line 686, in reraise raise value File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/haldunanil/Desktop/cashonly/accounts/decorators.py", line 27, in wrap return function(request, *args, **kwargs) File "/Users/haldunanil/Desktop/cashonly/accounts/views.py", line 16, in registration form.save() File "/Users/haldunanil/Desktop/cashonly/accounts/forms.py", line 32, in save group = Group.objects.get(name='Consumers') File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/haldunanil/anaconda/envs/ebenv/lib/python3.6/site-packages/django/db/models/query.py", line 385, in get self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Group matching … -
What is the different between celery.utils.log.get_*_logger and logging.get_logger, which to use, and why?
I have been trying to figure out the difference between the python logger and the celery logger, specifically the difference between the commands below, but cannot find a good answer. I am using celery v3, with django 1.10. from celery.utils.log import get_task_logger logger = get_logger(__name__) ... from celery.utils.log import get_task_logger logger = get_task_logger(__name__) ... import logging logger = logging.get_logger(__name__) The celery documentation (latest, v3.1) is very lacking on this topic. I have looked at similar questions just as this one, but it still it not clear which to use, why to use that one, and specifically what the differences are. I am looking for a clear, concise answer. I am also using sentry in my production environment. How does this choice affect your sentry logs (for example with these common settings). -
Django reverse accessor clashing
I am getting an error about a reverse accessor clash with the following model in django (Linux Mint - Python 2.7.6 - django.VERSION (1, 11, 0, u'final', 1)): class Equipment(models.Model): YES_NO = ( ('Y', 'Yes'), ('N', 'No'), ) Serial = models.CharField(max_length = 50) Name = models.CharField(max_length = 200) # This can probably be dropped based on max length of IPv6 address ManagementIP = models.CharField(max_length = 100) is_active = models.CharField(max_length = 1, choices = YES_NO) EquipModel = models.ForeignKey(EquipmentModel) # I don't understand why a related name is required here. location = models.ForeignKey(Location, #related_name='equipment_location_related' ) Giving me the following error: ERRORS: KMZ.Equipment.location: (fields.E304) Reverse accessor for 'Equipment.location' clashes with reverse accessor for 'Equipment.Location'. HINT: Add or change a related_name argument to the definition for 'Equipment.location' or 'Equipment.Location'. netmgr.Equipment.Location: (fields.E304) Reverse accessor for 'Equipment.Location' clashes with reverse accessor for 'Equipment.location'. HINT: Add or change a related_name argument to the definition for 'Equipment.Location' or 'Equipment.location'. Looking online this is common if accessing the same model multiple times from a single model, I am not doing that here. The error goes away if I uncomment the related_name line but what I'm not understanding where the other reference is coming from (location was originally Location which … -
Attach file to form on previous page in django?
I have a method that creates a csv file from a serialized model and writes the file to a data folder. I'd like to automate the step of uploading that same file to the UploadFile model in another app within the same project. So a user would create a Group, submit it which writes it to the data folder, and then -<(magic happens)>- the Group.name, Group.label, and Group.data are applied to the UploadFileForm which uploads it to the UploadFile model. I have searched google for something like this and found nothing -- which makes me think I am forming the question incorrectly. Any help is appreciated. I'll post my code if need be, but a general solution would be helpful enough. -
Django Tastypie field showing empty array
I'm at a loss and hoping someone can help me with this problem. A field in my Tastypie API keeps showing as a blank array. Just so the connections are understood, this is how it works User (has a) UserProfile (which contains that User's) Interests (which have inside) data I need. So this user profile should contain a list of "Interests" which are Django models that have data in them. However I am having this problem where my interests field always comes up as an empty array: {"id": 6, "interests": [], "resource_uri": "/api/v1/user_profile/6/", "user": "/api/v1/user/11/"} I want it to be populated with a list of URIs of the associated Interests. What is odd is that if I try to access these interests belonging to a user profile in a Django template using Django tags, it works. For example this will successfully return these interests inside a user profile: {% for u_interest in user.profile.interests.all %} This is my UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') interests = models.ManyToManyField(Interest) def __str__(self): return 'Profile of user: {}'.format(self.user.username) This is my Interest model: class Interest(models.Model): title = models.CharField(max_length=50) keywords = models.CharField(max_length=100) pub_date = models.DateTimeField() last_refreshed = models.DateTimeField(default=timezone.now()) num_of_imports = models.IntegerField(default=1) creator = … -
How do I correctly write this django model relationship?
class A: a = models.CharField() class B: aa = models.ForeignKey(A) # refering A.a b = models.CharField() class C: c = models.CharField() aa = models.ForeignKey(B) # refering B.aa bb = models.ForeignKey(B) # refering B.b To make things simple, let us say A contains three entries: u, v and w and B contains: (u, x), (u, y), (u,z), (v,x), (v, k) and (w,y). Now I want the admin to be able to be able to create instances of C where first he enters value for field c and the select any one of (u, v, w) for field aa. After selecting u -> x, y, z should appear for selection for bb, After selecting v -> x and k should appear for selection for bb, After selecting w -> only x should appear for selection for bb, Unfortunately, after many tries I am not able to correctly write the Foreign key relationship that does exactly what I intend to do. -
django FileNotFoundError when using with open() function
Im creating a new thread to ask this question because i have tried every solution i found but non seems to be working for me. I want to output pdf files stored in media sub directory. @Compadre suggested some links that really helped me understand how the file system works in python but so solutions provided in the threads are not working. i want to output files in the following directory structure: media/QuestionPapers/filename.pdf view function for outputting the file is: def Display(request, file_name): File_Name = file_name.replace('_', ' ') file_path = os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name) with open(file_path,'rb') as pdf: response = HttpResponse(pdf.read(), content_type = 'application/pdf') response['Content-Disposition'] = 'attachment; filename=some_file.pdf' return response when i do return HttpResponse(os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name)) it returns the absolute path to the file i like to out put but i when use the path in my code as shown above i get the is Errors: [Errno 2] No such file or directory: 'C:\Users\majmaj\projects\qbank\Scripts\QuestionBank\media\QuestionPapers\filename.pdf' the directory and file does exist because when i do http://127.0.0.1:8000/media/QuestionPapers/myfile.pdf, the file is opened but i don't know why the open() is not working even when the path to the file is correctly so one should please look into this and tell me what I'm doing wrong, … -
Django rest auth user_logged_in signal
I have a django rest app using django rest auth. I'm trying to log something everytime a user log in using signals. I've searched on the web on who to use signals and I haven't found interesting material on how to make it work. I think the problem may be with allauth signals. Is there any problem with the following configuration? signals.py import logging from allauth.account.signals import user_logged_in from django.dispatch import receiver logger = logging.getLogger(__name__) @receiver(user_logged_in) def login_logger(request, user, **kwargs): logger.info("{} logged in with {}".format(user.email, request)) apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals init.py default_app_config = 'users.apps.UsersConfig' -
Return all values of queryset
With this code all of the values are specified to return a QuerySet import json posts = (Post.objects.filter(owner=authenticated_user) .values('id', 'title', 'summary')) json_posts = json.dumps(list(posts)) Is there a way to avoid specifying all of the values for the QuerySet ('id', 'title', and 'summary')? For example posts = (Post.objects.filter(owner=authenticated_user) .values(ALL VALUES)) -
Confused by Django's ImageField width and height
I have added the image width and height fields to an ImageField-based model: class Photo(models.Model): height = models.IntegerField() width = models.IntegerField() image = models.ImageField( upload_to=settings.PHOTO_UPLOAD_TO, height_field='height', width_field='width' ) When I do manage.py makemigrations, I am asked for the default value for existing rows. I already have many photos in the database (it's a running site), therefore I chose to add default=0 to width and height. height = models.IntegerField(default=0) width = models.IntegerField(default=0) Now for all existing photos the two columns are populated with zeros, as expected. What I didn't expect however was that Photo.width and .height now return the correct non-zero values. Why? I couldn't find anything about such behaviour in documentation. -
save to django database
Im trying too save info to an ArrayField by using append. According to this post it should be passible but i cant get it to work. Im not creating a new object, it already exists i just need to append additional info to the ArrayField Code snippet: def isInDatabase(catInfo): cat = catagories.objects catName = str(catInfo) iban = catInfo.getIban() try: cat.get(Naam = catName) except ObjectDoesNotExist: print catName, 'is not in database' # NOTE: create catagory p = cat.create(Naam = catName, Rekening = [iban]) print catName, 'Has been stored in the database with', iban else: ibanList = cat.get(Naam = catName).Rekening editCat = cat.get(Naam = catName) print catName,'is in db, the following ibans are stored:\n\n', ibanList,'\n\n' if iban in ibanList: print iban,'is already in the list\n' else: ibanList.append(iban) editCat.save() print 'Updated list for',catName,'with -->',iban,'\nlist is now -->', ibanList,'\n' models.py class catagories(models.Model): Naam = models.CharField(max_length=10) Rekening = ArrayField(models.CharField(max_length = 34), blank = True) def __str__(self): return self.Naam So what modifications do i need to make to get it to save it to the database. I don't get any error, so the script runs fine but it doesn't save to the database.