Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin select fields
I have 2 models class Person(models.Model): group = models.ForeignKey(Group) some fields in model... class Group(models.Model): title = models.CharField(max_length=100) some fields in model... I want to show in admin panel 2 select fields: with groups with persons for active(selected) group in first select field How to do this fields? How to show persons related with active group? -
Django Best Practice: Where should I put model creation logic?
I'm reading Two Scoops of Django 1.11. At 7th chapter it introduces "fat models". It says that best practice is to put a big part of logic into the model and keep views as thin as possible, but then it doesn't go deep into the argument. So, I was thinking, supposing models like these: class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField(decimal_places=2, max_digits=4) categories = models.ForeignKey(Category, on_delete=models.CASCADE) sold_quantity = models.PositiveIntegerField(default=0) stock_quantity = models.PositiveIntegerField(default=0) class Receipt(models.Model): is_paid = models.BooleanField(default=False) total = models.DecimalField(decimal_places=2, max_digits=4, default=0) def update_total(self, amount): self.total += amount class ReceiptItem(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) receipt = models.ForeignKey(Receipt, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() When a ReceiptItem is created: ReceiptItem receipt field should point to the last Receipt whose is_paid value is False. If this Receipt doesn't exists, then create it and point to it. After this, related receipt.update_total(amount) should be called with product.price * quantity value as amount to sync the amount of the receipt. Product sold_quantity field should be increased by ReceiptItem istance quantity value. Product stock_quantity should be decreased by ReceiptItem istance quantity value. Where should I put this logic? I think it should go into ReceiptItem model, but in this case, how can I achieve in "non … -
Django FormValidation on ListView
my forms.py class RewardForm(forms.ModelForm): .... def clean_value(self): value = self.cleaned_data.get("value") if value > 800: raise forms.ValidationError("Maximum Reward is 800") return value myviews.py class RewardListView(ListView): context_object_name = 'Rewards' model = models.Reward def get_context_data(self, **kwargs): context = super(RewardListView, self).get_context_data(**kwargs) context['form'] = RewardForm() return context class RewardCreateView(CreateView): form_class = RewardForm model = models.Reward my listview_template.html #someListView {{ form.as_p}} I have listView that have a form that need to validate, but the problem is when click submit form on my ListView the error apear on CreateView Since my form action is CreateView. But, i need when user click submit and its not valid ( value more than maximum ) it show error on my ListView not an CreateView mean page will not change. -
django rest framework custom exception handling doesn't return expected error code
I am trying to implement a custom error handling in a project using django rest framework, and I want it to return a json when attempting to create a new user but the email is already used (I am enforcing the uniqueness of the email). I want to return an error code 400 and the resulting json to be like this: { "email": [ "eMAil already in use." ] } I implemented a solution proposed in https://medium.com/@mwhitt.w/restful-error-messages-with-django-537047892dff, but I get a 500 error code and no json back. This is my customexception.py class BaseCustomException(Exception): status_code = None error_message = None is_an_error_response = True def __init__(self, error_message): Exception.__init__(self, error_message) self.error_message = error_message def to_dict(self): return {'errorMessage':self.error_message} class ExistingEmailException(BaseCustomException): status_code = 400 def __init__(self): BaseCustomException.__init__(self, 'eMail already in use') This is my middleware.py: import traceback from django.http import JsonResponse def is_registered(exception): try: return exception.is_an_error_response except AttributeError: return False class RequestExceptionHandler: def process_exception(self, request, exception): if is_registered(exception): status = exception.status_code exception_dict = exception.to_dict() else: status = 500 exception_dict = {'errorMessage':'Unexpected Error!'} error_message = exception_dict['errorMessage'] traceback.print_exc() return JsonResponse(exception_dict, status=status) This is my serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password') def create(self, validated_data): try: user = … -
Django web application deployed on Heroku using Gunicorn - Half of the requests fail randomly (error code 500)
I deployed a Django web application on Heroku using gunicorn wsgi server. Everything works fine in local. That's my procfile web: gunicorn traineau.wsgi To keep it simple when I push one of the buttons in the app it's supposed to simply do Prod1=Prod1+1. in Python and then returns it to JS using return HttpResponse(json.dumps(raw_dict), content_type="application/json") and display the updated Prod value in the app. Prod1 is a global variable since I need it in other functions. When I run my app and click that button a couple times, half the requests I make fail with error code 500 (Internal Server Error) but randomly. ex: 1ok, 3fail, 2ok, 5fail. At the end with a big enough sample it's pretty close the 50% fail. I know Gunicorn is a prefork worker model and heroku sets per default 2 WEB_CONCURRENCY. I set the WEB_CONCURRENCY to 1 in the CONFIG_VAR of Heroku and it doesn't help. If I restart the application a couple times without restarting the dyno, instead of the error code 500, it will eventualy alternate between 2 ranges of values. Example 1-2-3-4-20-21-5-6-7-22-23, etc. If I restart the dyno, we're back with 50% fails. I use the free Dyno. I tried to … -
Is it possible for Django to use the same link and a database for each client?
Is it possible for Django to use the same link and a database for each client? Hello, I'm new to Django and I have a question. I'm bringing a PHP system to Django where all clients use the same link to access the system, but each with its database with users, access groups, etc. In the custom login screen they inform their client id, user and password to authenticate, where always the client id is the name of the database. I made the following code to change the database connection that is probably wrong: def change_db (self): connections ['default']. settings_dict ['NAME'] = self.db return True The code even exchanges the database I want to access, but testing on my local machine using the runserver, if another client is accessing simultaneously for example in another browser, it displaces the other client. Has anyone had it or does it have an idea to solve? I searched the routers, I do not know if I would solve my problem, or if there was the same problem of switching the connection and removing the other client. Grateful. -
Image source from django variable
I am looking for a way different possible image source in my html code, depending on result of a python function. Exemple if: state = isOnline() is a function that can say if a device is online or not, it returns: True then I would obtain IMG_URL = imgSource(state) would return the source for online image static 'project\img\true.jpg' which I would then through my views.py used as: def device(request): return render(request, 'device.html', {'IMG_URL': IMG_URL}) and then I could use this variable in my html code. <img src="{% IMG_URL %}" alt="Post"> I hope you guys will be capable to help me, thanks ! -
Django not saving object in login view after upgrade to 1.10 or 1.11
I have a custom login view. When a user tries to login I record it in a table whether it was successful or not. It seems to be working correctly in production, but I just noticed today that in my dev environment it only records successful logins and never unsuccessful logins. Obviously I don't unsuccessfully log into my dev environment very often so the last unsuccessfully log recording is from when I was on Django 1.9.13 . I'm currently on 1.11.13 and it's not working. I turned on logging for the database and can confirm that it's issuing an INSERT but the entry isn't there. I can only assume it's due to no commit being issued, but there's no error that occurs and the view responds with a 200. I tried saving the object in another unauthenticated view and that works correctly. I'm using ATOMIC_REQUESTS on my database to handle transactions. -
Static does not loads static files in Django
This is my directory structure app_web _init_.py settings.py urls.py wsgi.py upload_app migrations/ static/ js/ alert.js templates/ upload.html _init_.py admin.py apps.py models.py tests.py views.py db.sqlite3 manage.py In settings.py , my STATIC_URL = '/static/' and in my upload.html {% load staticfiles %} <script type="text/javascript" src="{% static "js/alert.js" %}"></script> It does not works and throws 404 error everytime. I even tried load static but it still cannot load anything from static folder and throws 404 error. I am using Windows 10 machine. -
Django django.db.backends logger and debugging
I am trying to profile a part of my code to reduce the number of queries run against the database, so I configured the following logger which supposedly logs every single raw SQL query that is executed against the database: LOGGING = { 'version': 1, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'] } } } I am debugging said block of code line by line, to slowly inspect the queries that are being logged. The problem is that PyCharm's debugger is evaluating the involved QuerySets, therefore running queries against the database and skewing my analysis. Is there any way I can configure the debugger so it doesn't automatically evaluate variables? Or essentially any other way I can analyze what raw queries each line of code produces? -
Total likes on all posts of a user
How can I count the total likes on all the posts of a particular user in django ? models.py class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='posts') slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title def get_like_url(self): return reverse("like-toggle", kwargs={"slug" :self.slug}) def get_api_like_url(self): return reverse("like-api-toggle", kwargs={"slug" :self.slug}) -
Django Validation with clean not working
my forms.py class AccountForm(forms.ModelForm): foo = forms.ModelDecimalField() bar = forms.ModelDateField() def clean_foo(self): foo_passed = self.cleaned_data.get("foo") if foo_passed > 1000: raise forms.ValidationError("Sorry, Maximum is 1000.") return foo_passed my template.html {{form.as_p}} on my code above, iam trying to validate the input, if value higher than 1000 will raise error. But its not working, what i miss. -
Django dropdown selection is not working when submit button is pressed
I have a dropdown selection and 'submit' button in the page. Some fields disappears upon specific dropdown selection. I can hide/show all other fields but except password field. Whenever I hide the password field with a jquery the submit button doesnot work. following are my code files. HTML template django < script > $(document).ready(function() { $('#type').change(function(eventObject) { if ($(this).val() == 'sercomm') { $('.sample').show(); $('.sample_netip').show(); $('.sample_password').show(); $('.sample_username').hide(); } else { $('.sample').show(); $('.sample_password').show(); $('.sample_netip').hide(); } }).change(); }); < /script> <form class="form-horizontal" method="post" role="form">{% csrf_token %} {# dropdown#} <div class="form-group"> <label class="col-sm-3 control-label">{% trans "Mode" %}</label> <div class="col-sm-6"> <select name="type" class="form-control" id="type"> <option value="ex1" selected>{% trans "ex1" %}</option> <option value="ex2">{% trans "ex2" %}</option> </select> </div> </div> {# end of dropdown#} <div class="form-group sample"> <label class="col-sm-3 control-label">{% trans "Name" %}</label> <div class="col-sm-6"> <input type="text" class="form-control" name="name" placeholder="{% trans " Name " %}" maxlength="20" id="name" required pattern="[a-zA-Z0-9\.\-_]+"> </div> </div> <div class="form-group sample"> <label class="col-sm-3 control-label">{% trans "Management Network IP Address" %}</label> <div class="col-sm-6"> <input type="text" class="form-control" name="ipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$"> </div> </div> <div class="form-group sample_netip"> <label class="col-sm-3 control-label">{% trans "Radio Network IP Address" %}</label> <div class="col-sm-6"> <input type="text" class="form-control" name="netipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$"> </div> </div> <div class="form-group sample_username"> <label class="col-sm-3 control-label">{% trans "User … -
Daphne issue in Otree
I'm running an Otree application, there are a total of twenty clients. The problem is that in some clients I get the following error. 503 Service Unavailable Request queue full. Daphne Can someone get me a idea about how to fix that error? -
Get the current value on click in my ModelAdmin (Django)
I want to get the current value on click from Django Admin. I created a function in the admin.ModelAdmin. This function displays a button. Currently, I get all the values on click then I will only want the value on which the click has occurred. class: class SchedulejoursAdmin(admin.ModelAdmin): list_display = ('go_url','user_id','date') def go_url(self, obj): print(obj.pk, ' obj.pk') print(obj.date, ' obj.date') return format_html(u'<a href="https://www.w3schools.com">Visit W3Schools</a>') go_url.allow_tags = True go_url.short_description = 'Go to site' admin.site.register(Schedulejour,SchedulejoursAdmin) Thank -
Django : how to use pattern searching?
Does someone of you know how the django's pattern searching is developed ? using : python manage.py test --pattern=test* My tests are launched. But when i try : python manage.py test --pattern=[test] I've no match If you could enlight me :) -
JQuery event not firing on Django dynamic content
I am developing Django application where i wanted to do lazy load. I followed this tutorial https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html. All working fine except when i tried to add a script below, $(".infinite-item").on("click", function () { alert("click"); }); Only first 20 div are firing click event. Why click event is not firing for rest of div's ? -
Django - Upload a file to a network shared storage
I'm using Django v1.7 and my app uploads files to a local storage. The thing is, I have a load balancer and 2 front end machines server the django app. Therefore I need to run a task periodically to sync the content of both local storages from the front end servers.... Is there any way to upload to a remote location, like a network storage? (e.g. may I uploaded it to remote IP or something?) I'm sorry, but I haven't found a solution for this yet :( Cheers, -
413 Request Entity Too Large uploading files with Django Admin and Nginx Configuration
Whenever I upload a small file, such as an image, the data is saved successfully. However, when I upload an audio file I get this error: 413 Request Entity Too Large. The file sizes are around 8MB. The confusing part is that uploading these files in development process easily but now that the website is live, it doesn't work. I read that you can change the limit of the upload size but can't seem to figure it out. Another thing I read is that you should have files uploaded to a server, and you can use Nginx. I think I configured it; I typed the command scp -r * root@[my ip address] /usr/share/nginx/html and the files from my media folder were uploaded there. Now with that the files are not automatically put there, instead they are sent to the project's media folder. Shouldn't it automatically upload to the Nginx server? -
Set Windows Django Project Folder To OS-X/Linux Style
In when adding a Django project to Bitnami on OS-X, the path to the projects is "*installdir*\apps\django\django_projects" ( in the install directory) When in windows it is "C:\Users\*USER*\Bitnami DjangoStack Projects" (outside the install directory) I'm on windows 7 and would like to configure Bitnami to use the OS-X style folder where it is all contained within the install directory rather than being in a separate folder. If this is a possibility, how would I go about doing this? -
How convert files im memory with moviepy?
I am using moviepy to converter videos. I use this follow instruction to load the movie file and converter: clip = VideoFileClip('/home/developer/Pictures/aa.mov') clip.write_videofile('/home/developer/Pictures/aa.mp4') This works fine but in my system i dont receive a file via file path. Instead i receive this file via Django. type(request.data['file']) [1] <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> If i made this also not works: arq = open('/home/developer/Pictures/aa.mov','rw').read() clip = VideoFileClip(arq) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-23-9976dbcf241a> in <module>() ----> 1 teste= VideoClip(arquivo) /home/developer/.virtualenv/movie/local/lib/python2.7/site-packages/moviepy/video/VideoClip.pyc in __init__(self, make_frame, ismask, duration, has_constant_size) 84 if make_frame is not None: 85 self.make_frame = make_frame ---> 86 self.size = self.get_frame(0).shape[:2][::-1] 87 self.ismask = ismask 88 self.has_constant_size=has_constant_size <decorator-gen-123> in get_frame(self, t) /home/developer/.virtualenv/movie/local/lib/python2.7/site-packages /moviepy/decorators.pyc in wrapper(f, *a, **kw) 87 new_kw = {k: fun(v) if k in varnames else v 88 for (k,v) in kw.items()} ---> 89 return f(*new_a, **new_kw) 90 return decorator.decorator(wrapper) 91 /home/developer/.virtualenv/movie/local/lib/python2.7/site-packages/moviepy/Clip.pyc in get_frame(self, t) 92 return frame 93 else: ---> 94 return self.make_frame(t) 95 96 def fl(self, fun, apply_to=None, keep_duration=True): TypeError: 'str' object is not callable Is there a way to load the file without using path, just receiving the file in bytes? -
Django subquery throws "more than one row returned by a subquery used as an expression"
I have recently upgraded to django 1.11 and I want to use the newly released, Subquery exrpession feature. There are two models as follows class Project(models.Model): title = models.CharField(_("Project Name"), max_length=128) class PrivateDonation(models.Model): project = models.ForeignKey(Project) value = models.DecimalField(_("value"),max_digits=19, decimal_places=2) ............ I want to get a queryset of Project objects annotated with sum of the private donation values for each project. I know, there are other ways to accomplish this and I already have a working solution for my app but since I am learning this feature so I tried the following queries private_donations = PrivateDonation.objects.filter(project=OuterRef('pk')).values('value') private_donations_sum = private_donations.annotate(s=Sum('value')).values('s') Project.objects.annotate(pd_sum=Subquery(queryset=private_donations_sum)) But the above query throws an exception django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression The only query that successfully runs is the one below. private_donations = PrivateDonation.objects.filter(project=OuterRef('pk')).order_by().values('project') private_donations_count = private_donations.annotate(c=Count('*')).values('c') projects = Project.objects.annotate(space_count=Subquery(queryset=private_donations_count)) But if I choose anything other than the 'project' attribute in 'private_donations' query it throws the same error And here is the stack-trace The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "/Users/sajidur/Coding/socialfunders/sf/venv3/lib/python3.5/site-packages/django/db/models/query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/sajidur/Coding/socialfunders/sf/venv3/lib/python3.5/site-packages/django/db/models/query.py", line 250, in … -
Celery 4 + Django 2.0 - CELERY_BROKER_TRANSPORT_OPTIONS is ignored
I'm using Django 2.0 with Celery 4 & SQS as a broker. I used CELERY_BROKER_TRANSPORT_OPTIONS to set a prefix for the queue names and the region of the SQS. like this: {'queue_name_prefix': 'qa-', 'region': 'eu-west-1'} I have a dedicated worker running using celery -A <app_name> worker -Q <queue_name> And a Django web service that calls a task with .delay(). The issue is that the worker is able to read the broker_transport_options, and it created a queue with the correct prefix in the correct region as I stated in the settings, but when the web service calls the task, it ignores these settings and search for the queue name without prefix and not in the correct environment. Does anyone know what is the case here? Thanks, Dar -
Specific loading of related manytomany field in queryset
I'm using intermediate model with extra fields on many-to-many relationships like this: class A(models.Model): name = models.CharField(max_length=128) class B(models.Model): name = models.CharField(max_length=128) a = models.ManyToManyField(A, through='AB') class AB(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) number = models.IntegerField(default=0) date = models.DateTimeField() By default, AB.date is NULL in database. I retrieve all my B instances with something like this B.objects.all(). Then, for each instance of B, I can get a set of AB like this, b_instance.ab_set.all(). How to load only ab_set elements where date is null ? In SQL it would have looked like this : SELECT * FROM B INNER JOIN AB ON AB.id = B.ab_id AND AB.date IS NULL -
How to update the serializer field for m2m relationship
I am trying to update submitted data by implementing the update() method on the a SerializerClass. However i do not know how to get access to the current ingredient of the current instance and also i do not know how to iterate through the validated data such that i can assign the key and values correctly. any advice would be appreciated! My Serializer class RecipeSerializer(ModelSerializer): ingredients = IngredientSerializer(many=True) owner = ReadOnlyField(source='owner.username') class Meta: fields = ['owner', 'name', 'description', 'image', 'ingredients'] model = Recipe def create(self, validated_data): ingredient_datas = validated_data.pop('ingredients') recipe = Recipe.objects.create(**validated_data) for ingredient_data in ingredient_datas: recipe.ingredients.create(**ingredient_data) return recipe def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.image = validated_data.get('image', instance.image) for ingredient in validated_data.get('ingredients'): for key, value in ingredient.items(): print(key, value) instance.ingredient.name = value instance.ingredient.amount = value instance.save() return instance My Models class Recipe(models.Model): owner = models.ForeignKey('auth.User', related_name='recipes', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField(max_length=200, blank=True) image = models.CharField(max_length=100, blank=True) ingredients = models.ManyToManyField(Ingredient, related_name='recipes') class Ingredient(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=1) Some window shell ouputs print(validated_data) {'name': 'bedddef', 'description': 'gdddoot', 'image': 'httpdddlo', 'ingredients': [OrderedDict([('name', 'tomatoes'), ('amount', 2)]), OrderedDict([('name', 'bread'), ('amount', 3)])]} print(key, value) name tomatoes amount 2 name bread amount 3