Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin list display only showing pagination but not the list
Hello I am using django 2.2 to display a list of coupon batches. However when I go to the admin the list display view does not show the data in the coupon batch table. Only pagination and stats count show up instead. Please note the data is fake data created from copying data from another table i.e INSERT INTO new_db.myapp_couponbatch SELECT * FROM old_db.myapp_couponbatch; Here is also my admin snippet @admin.register(CouponBatch) class CouponBatchAdmin(admin.ModelAdmin): # exclude = ('status',) readonly_fields = DEFAULT_READONLY_FIELDS + ('coupons', ) exclude = ("coupons", ) list_display = DEFAULT_LIST_DISPLAY + ('count', ) form = CouponBatchForm change_form_template = "coupon/change_form.html" actions = SoftAdminActions.actions def export(self, request, pk): obj = get_object_or_404(CouponBatch, pk=pk) output = io.BytesIO() fieldnames = ('coupon_code',) + DEFAULT_LIST_DISPLAY to_excel(obj._coupons(), fieldnames=fieldnames, filename=output) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report%s.xlsx' % ( uuid.uuid4()) response.write(output.getvalue()) return response def get_export_urls(self): info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^(?P<pk>[0-9]+)/export/$', self.admin_site.admin_view(self.export), name='%s_%s_export' % info), ] def get_urls(self): urls = self.get_export_urls() urls += super(CouponBatchAdmin, self).get_urls() return urls -
Mailing isn't working in Django AWS Lambda (Zappa) behind a VPC
I have an AWS lambda function (Django zappa) that is running inside a VPC thus I'm not able to send emails because Lambda isn't connected to the internet, I tried NAT Gatway but with no hope. I created a NAT Gatway using one public subnet of the VPC. Created another private subnet with a route table that routes 0.0.0.0/0 to the NAT Gateway. I would appreciate any help. -
How to add extra key value in django rest framework api view?
This is my models class NumberList(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) number = models.PositiveIntegerField() spam = models.BooleanField(default=False) def __str__(self): return str(self.number) This is my serializer class class FindNameSerializer(serializers.ModelSerializer): class Meta: model= NumberList fields = ('name','number') This is my views class FindName(ListAPIView): print("server error hai") serializer_class = FindNameSerializer def get_queryset(self, *args, **kwargs): number = self.kwargs.get("number") queryset = NumberList.objects.filter(number=number) return queryset which filter the number and return name and number on following url path('find/<slug:number>/',FindName.as_view(), name='number'), I am getting following result in my api [ { "name": "Saiful Hasan", "number": 8888888888 } ] However my target is also to return the total number of spam reported to the user in my API and final API should look like this [ { "name": "Saiful Hasan", "number": 8826478938 "spam": 3 } ] Number of spam can be calculated as spam=NumberList.objects.filter(spam=True).count() How should add spam in result queryset -
Django JsonResponse display in template using JavaScript without refreshing page
I have Django view that is using JsonResponse to send response to template without refreshing the template web page. I can see the response from the view in Chrome Developer Tools - Network - Response in format {"photo_id": 104}. My question is simply, does seeing the response here mean that it is also accessible in the template using JavaScript? -
CSRF verification failed in standart VS Django Project template
I have a CSRF verification failed error after login in standard VS2019 Django project template In standard Django project I have a login form <form action="." method="post" class="form-horizontal">{% csrf_token %} <h4>Use a local account to log in.</h4> <hr /> <div class="form-group"> <label for="id_username" class="col-md-2 control-label">User name</label> <div class="col-md-10">{{ form.username }} </div> </div> div class="form-group"> <label for="id_password" class="col-md-2 control-label">Password</label> <div class="col-md-10">{{ form.password }} </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="hidden" name="next" value="/" /> <input type="submit" value="Log in" class="btn btn-default" /> </div> </div> {% if form.errors %} <p class="validation-summary-errors">Please enter a correct user name and password.</p> {% endif %} </form> urls.py path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), and forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class BootstrapAuthenticationForm(AuthenticationForm): """Authentication form which uses boostrap CSS.""" username = forms.CharField(max_length=254, widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'User name'})) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput({ 'class': 'form-control', 'placeholder':'Password'})) After i try login i gave Forbidden (403) CSRF verification failed. Request aborted. Although the value of csrfmiddlewaretoken is sent. I also wonder where exactly BootstrapAuthenticationForm is embedded in login.html -
How do you install PyCurl with Python 3.7?
I'm using Python 3.7 on CentOS. I would like to install the pycurl library, but I'm having some trouble ... (venv) [myuser@server html]$ pip install pycurl 7.19.5 Collecting pycurl Using cached https://files.pythonhosted.org/packages/e8/e4/0dbb8735407189f00b33d84122b9be52c790c7c3b25286826f4e1bdb7bde/pycurl-7.43.0.2.tar.gz ERROR: Complete output from command python setup.py egg_info: ERROR: Traceback (most recent call last): File "/tmp/pip-install-3cmwrpw6/pycurl/setup.py", line 223, in configure_unix stdout=subprocess.PIPE, stderr=subprocess.PIPE) File "/usr/local/lib/python3.7/subprocess.py", line 756, in __init__ restore_signals, start_new_session) File "/usr/local/lib/python3.7/subprocess.py", line 1499, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'curl-config': 'curl-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-3cmwrpw6/pycurl/setup.py", line 913, in <module> ext = get_extension(sys.argv, split_extension_source=split_extension_source) File "/tmp/pip-install-3cmwrpw6/pycurl/setup.py", line 582, in get_extension ext_config = ExtensionConfiguration(argv) File "/tmp/pip-install-3cmwrpw6/pycurl/setup.py", line 99, in __init__ self.configure() File "/tmp/pip-install-3cmwrpw6/pycurl/setup.py", line 227, in configure_unix raise ConfigurationError(msg) __main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory: 'curl-config': 'curl-config' ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-3cmwrpw6/pycurl/ What version of PyCurl is compatible with Python 3.7? Is there something else I'm missing? -
Remove duplicates where content_id and ip_address are the same In python django module
I've got some code setup to count page clicks, the data is stored in ObjectViewed model every time a page is clicked. I'm currently counting how many times each page has been clicked but I would like to make it unique page clicks, so only show 1 click per page, per IP. I'm attempting to filter out where ip_address and content_object appear together ina row, more than once. class ObjectViewed(models.Model): object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) #where these are together i want to only count once below content_object = GenericForeignKey('content_type', 'object_id') ip_address = models.CharField(max_length=120, blank=True, null=True) def analytics(request): objects = ObjectViewed.objects.all() q = NewsPost.objects.values('id').distinct() dict = {} for object in q: dict.update({list(object.values())[0]: 0}) count = ObjectViewed.objects.values('object_id').annotate(c=Count('object_id')).order_by('-c') Tried a few things, but new to python and django so I'm not quite sure what the best way is. Any help/guidance would be appreciated, thanks! -
how to perform a nested reverse query set in django
I need to create double reverse queryset in Django, explained more in the code: The models class Book(models.Model): date = models.DateTimeField(auto_now=True) book_name = models.CharField(max_length=150) book_level = models.ForeignKey(Level, on_delete=CASCADE) book_subject = models.ForeignKey(Subject, on_delete=CASCADE) book_teacher = models.ForeignKey(Teacher, on_delete=CASCADE, null=True, blank=True) book_comission = models.DecimalField(max_digits=19, decimal_places=5, null=True, blank=True) book_black_papers = models.IntegerField() book_color_papers = models.IntegerField() book_paper_cost = models.DecimalField(max_digits=19, decimal_places=5) book_ink_cost = models.DecimalField(max_digits=19, decimal_places=5) book_color_ink_cost = models.DecimalField(max_digits=19, decimal_places=5) book_cover_cost = models.DecimalField(max_digits=19, decimal_places=5) supplier = models.ForeignKey(Supplier, on_delete=CASCADE, null=True, blank=True) book_total_cost = models.DecimalField(max_digits=19, decimal_places=5) book_sell_price = models.DecimalField(max_digits=19, decimal_places=5) viewed_by = models.ManyToManyField(User) is_double_pages = models.BooleanField(default=False) is_hidden = models.BooleanField(default=False) image1 = ProcessedImageField(upload_to='book_image', processors=[ResizeToFill(440, 262)], format='JPEG', options={'quality': 60}, blank=True, null=True) image2 = ProcessedImageField(upload_to='book_image', processors=[ResizeToFill(440, 262)], format='JPEG', options={'quality': 60}, blank=True, null=True) image3 = ProcessedImageField(upload_to='book_image', processors=[ResizeToFill(440, 262)], format='JPEG', options={'quality': 60}, blank=True, null=True) image4 = ProcessedImageField(upload_to='book_image', processors=[ResizeToFill(440, 262)], format='JPEG', options={'quality': 60}, blank=True, null=True) published_online = models.BooleanField(default=False) class VIPSellInvoice(models.Model): ordered = 'تحت التنفيذ' delivered = 'منتهية' canceled = 'ملغاة' invoice_choices = ( (ordered, 'تحت التنفيذ'), (delivered, 'منتهية'), (canceled, 'ملغاة'), ) date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=PROTECT) client = models.ForeignKey(VipClient, on_delete=PROTECT) total = models.DecimalField(max_digits=19, decimal_places=5, default=0) status = models.CharField(max_length=160, choices=invoice_choices) delivery = models.ForeignKey(Delivery, on_delete=PROTECT, null=True, blank=True) delivery_price = models.DecimalField(max_digits=19, decimal_places=5, default=0, null=True, blank=True) delivery_notes = models.CharField(max_length=500, null=True, blank=True) is_done = models.BooleanField(default=False) class VipPriceList(models.Model): book_name = … -
django.db.utils.ProgrammingError: relation "story_history" does not exist
I have a working app in my local machine but now a team member joined and wants to clone the up and run the migrations. It is failing with the above error. The simplest solution, as I see it, to backup the database and restore it in other apps but I didn't want to do that -- yet at least. Traceback (most recent call last): File "D:\dev\go\be\env\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "store_history" does not exist ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "D:\dev\go\be\env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "D:\dev\go\be\env\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "D:\dev\go\be\env\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\dev\go\be\env\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "D:\dev\go\be\env\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "D:\dev\go\be\env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\dev\go\be\env\agrigo\payment\models.py", line 29, in <module> class … -
How to group database result with the same value
I am trying to create a program in django that checks the database of Games to pick 10 winners if from 1 to 10 users have different scores they will take the price each but if 1 to like (example) 12 users get thesame score then the global price will be shared equally for each of them and if from 1 to 9 have different scores but (example)5 people have thesame score for number 10 position they will all share the price of number 10. Please i don't know the algorithm to use for this, thanks in advance. Here is my game Model class Game(models.Model): slip_token = models.CharField(max_length=50) user = models.OneToOneField(User, on_delete=models.CASCADE) score = models.IntegerField(default=0) amount_won = models.DecimalField(max_digits=17, decimal_places=2, default=0.00) game_fate = models.IntegerField(default=0) # 0 for not decided 1 for win, 2 for lose played_at = models.DateTimeField(default=timezone.now) -
How to get more information about why loaddata is failing with "TypeError: 'NoneType' object is not subscriptable"?
I'm trying to run a seed data command with my Django/Python 3.7 app. It dies with the error "TypeError: 'NoneType' object is not subscriptable", but I have no idea what it's complainig about ... [myuser@server html]$ cd /var/www/html; source /etc/profile; source venv/bin/activate; python manage.py loaddata myproject/fixtures/seed_data.yaml Traceback (most recent call last): File "/var/www/html/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 91, in Deserializer Model = _get_model(d["model"]) TypeError: 'NoneType' object is not subscriptable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/var/www/html/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label for obj in objects: File "/var/www/html/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 77, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/var/www/html/myproject/fixtures/seed_data.yaml': How do I figure out which of my seed rows is causing this error? -
reCAPTCHA not stopping users logging in
I am trying to use Google reCAPTCHA for my login form to prevent spam. After following the necessary steps to get it all working, users can still login. They can fill out there details and login with out ticking the checkbox which isn't correct. I think it might be the placement in the DOM so I tried moving it around and that didn't work. CODE: {% extends 'public/base.html' %} {% load staticfiles %} {% load crispy_forms_tags %} {% block head %} <link rel="stylesheet" type="text/css" href="{% static "public/css/auth.css" %}" /> {% endblock %} {% block content %} <div class="container mt-5 mb-5 login-container"> <form method="POST"> {% csrf_token %} <fieldset class="form-group mt-4"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} <script src="https://www.google.com/recaptcha/api.js" async defer></script> <div class="g-recaptcha" data-sitekey="################################ "></div> </fieldset> <div class="form-group"> <button class="btn btn-success" type="submit">Login</button> <small class="text-muted ml-2"> <a href="{% url 'password_reset' %}">Forgot Password?</a> </small> </div> </form> <div class="border-top pt-3 mb-4"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> </div> </div> {% endblock %}``` Thanks. -
Making a WYSIWYG form field in Django
I'm currently practicing making a blog in Django and I'd love to have WYSIWYG form field in Django but obviously it's not pre-built in Django and I know for a fact that I can create custom fields I just can't seem to find the right way to do it. Any tutorials or tips would be appreciated. I don't want to use a package I want to do it myself just for the sake of learning. -
GAE Python 3.7 Standard can't connect to Cloud SQL server
I'm following the tutorial for deploying a Django app on Google App Engine here. I'm able to run the app locally using cloud_sql_proxy, but when I deploy the app to GAE the app fails with the error: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") Checking the error output, it looks like django is trying to connect to the unix socket at /cloudsql/<project>:<region>:<instance> as expected, it's just failing for some reason. What could be causing this issue? -
Django and VueJS integration error. Error loading VueJS component to Django
I have created Django and VueJS integrated project using webpack_loader. Django runs at localhost 8000 and VueJS at 8080 port. But port 8000 gives me an error in console that GET http://0.0.0.0:8080/app.js net::ERR_ADDRESS_INVALID as I am learning to integrate this two framework together, I followed a tutorial as mention below for this project https://medium.com/@rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a Thanks in advance I have checked http://localhost:8080/app.js and it renders a large file, so how come port 8000 cannt connect with it ? -
Calculate time difference with previous object on django queryset with Window annotation
My model has a DateTimeField and a DurationField with the time elapsed from the last record inserted to the current one. I'm trying to remove the DurationField but I must be able to calculate the time elapsed "on the fly".. This question Difference with previous object in django queryset annotation is quite similar to my problem. The best answer suggests using the Django Window function introduced with the version 2.0. I found that the Lead function works only using integers, but I have a DateTimeField and not an IntegerField, so I tried to convert/cast my field to a timestamp. This is my Model: class Event(models.Model): date = models.DateTimeField() time_elapsed = models.DurationField() # TO BE REMOVED Here the actual queryset: Event.objects .annotate(ts=Cast(Extract('date','epoch'),IntegerField())) .annotate(next_val=Window( expression=Lead('ts', offset=1,default=0), order_by=F('date').asc()), difference=F('next_val')-F('ts')) It nearly works (it seems), but it takes the next object and does the difference, while I need the PREVIOUS object to subtract the current one. I can't find a solution for this. Many thanks! -
How to return two lists to chartjs from Django View
I am using chartjs to render a barchart. For this I need to pass two lists in the format like [1, 2, 3] & [3, 2, 1]. I am making an AJAX call to Django which returns the two lists (I have not added the code to get the data from the database yet). The graph works fine for one list but not sure how to pass the second list. I tried to pass the two lists as json and tried to use each of the lists in the success function of the ajax call but the graph does not render properly. With one list the graph is working fine below is the code for the ChartJs AJAX call $.ajax({ async: pasys, type: "GET", url: purl, data: pdata, contentType: "application/json; charset=utf-8", dataType: "json", success: function(ldata) { var barData = { labels: ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], datasets: [ { label: "DL1", backgroundColor: 'rgba(220, 220, 220, 0.5)', pointBorderColor: "#fff", data: ldata.data1 }, { label: "Non-DL1", backgroundColor: 'rgba(100, 200, 300, 0.5)', pointBorderColor: "#aaa", data: ldata.data2 } ] }; var barOptions = { responsive: true }; var ctx2 = document.getElementById("opendemandtrend").getContext("2d"); new Chart(ctx2, {type: 'bar', data: barData, … -
How to make a queryset order_by and after that, make another order maintaining the result of the first one?
I need to sort a queryset result with two columns. First, I need to order_by 'date'. Once a have my queries sorted, I need to sort the result, maintaining the first order with order_by 'status'. Example: date status 2019-06-10 15:23:39 20 2019-06-12 15:37:31 20 2019-06-10 15:18:53 10 2019-06-12 15:38:01 10 2019-06-12 15:47:09 10 2019-06-12 15:36:30 0 2019-06-10 16:35:11 0 I need the following result: date status 2019-06-12 15:37:31 20 2019-06-12 15:47:09 10 2019-06-12 15:38:01 10 2019-06-12 15:36:30 0 2019-06-10 15:23:39 20 2019-06-10 15:18:53 10 2019-06-10 16:35:11 0 Following the dkango docs https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by I'm doing a order_by pass two fields like order_by('-date', '-status') I'm trying the follow code Measurements.objects.filter(patient=230).order_by('-date', '-status') My result is: date status 2019-06-12 15:47:09 10 2019-06-12 15:38:01 10 2019-06-12 15:37:31 20 2019-06-12 15:36:30 0 2019-06-10 16:35:11 0 2019-06-10 15:23:39 20 2019-06-10 15:18:53 10 I need the following result: date status 2019-06-12 15:37:31 20 2019-06-12 15:47:09 10 2019-06-12 15:38:01 10 2019-06-12 15:36:30 0 2019-06-10 15:23:39 20 2019-06-10 15:18:53 10 2019-06-10 16:35:11 0 -
Django, use complex Q object query string on a record
We have a Q object string similar to filter_string1 = {'question__startswith':'Who'} filter_string2 = {'question__startswith':'What'} filter = Q(**filter_string1) | Q(**filter_string2) && Q(**filter_string1) This can be used as : Models.objects.filter(filter) Can we use this filter to check if a certain record (a single record, instance of a model) satisfy above conditions. -
Virtual Environment dosent work with python3.7
I need to upgrade Python from 3.6 to 3.7 on my Django production website. When I create a new venv with python3.7 -m venv venv and install Django in it everything works fine, I can start the Development server and even make requests from the server to it with no problems. But when I use apache2 with mod_python the log says that Django is not installed. I can swap the two venvs and with the Python3.6 one it works, so I dont think it is an apache configuration problem. When I create the Venv with Python3.7 it creates a symbolic link to /usr/bin/python3.7 but when I use python3.6 it creates a new executable. I think this could be th Problem but I found no way to prove it. The Venv creations: root@localhost:~# python3.7 -m venv venv root@localhost:~# ls -la venv/bin/ total 40 drwxr-xr-x 2 root root 4096 Jun 12 19:46 . drwxr-xr-x 6 root root 4096 Jun 12 19:46 .. -rw-r--r-- 1 root root 2186 Jun 12 19:46 activate -rw-r--r-- 1 root root 1242 Jun 12 19:46 activate.csh -rw-r--r-- 1 root root 2394 Jun 12 19:46 activate.fish -rwxr-xr-x 1 root root 242 Jun 12 19:46 easy_install -rwxr-xr-x 1 root root … -
'render' object has no attribute 'GET'
I'm working on a web application for a uni project using django and postgresql. This is my first time working with django forms and when trying to render any of them for a test run and to figure out the views the render fails with the above error message. I have worked with Django beforehand but this is my first time working with forms -previously, I'd done object creation and edits through API views. I can't find where my code is wrong, but I've tried rewording it, moving lines around to see if it helps (it hasn't,) and even avoiding inheritance and trying to word it as a straightforward form (hasn't helped either.) I have four different forms but they all provide the same error message, so I'm just gonna show one user model extension that I'm not too confident about for an example, in case there's more wrong than I've realized. This is the code I've got class JdTform(UserCreationForm): telefono = forms.IntegerField() class Meta(UserCreationForm.Meta): fields = [ 'telefono' ] labels = { 'telefono': 'teléfono' } widgets = { 'telefono': forms.NumberInput() } def jdt_form_view(request): if request.method == 'GET': form = JdTform() return render(request, 'personas/formu_jdt.html', {'form': form}) if request.method == 'POST': … -
How to create an annotation in Django that references two related models
I'm trying to add an annotation to a QuerySet that is True/False when the value of a field on one related object is less than the value of a field on a different related object. Here are some models for an example: class RobotManager(models.Manager): queryset = super(RobotManager, self).get_queryset() queryset = queryset.annotate(canteen_empty=UNKNOWN CODE) return queryset class Robot(models.Model): # Has some other unrelated stuff objects = RobotManager() class CanteenLevel(models.Model): time = models.DateTimeField() robot = models.ForeignKey("SomeApp.Robot") gallons = models.IntegerField() class RobotConfiguration(models.Model): time = models.DateTimeField() robot = models.ForeignKey("SomeApp.Robot") canteen_empty_level = models.IntegerField() With the above models, as the Robot's Configuration or CanteenLevel change, we create new records and save the historicals. What I would like to do is add an annotation to a Robot QuerySet that states if the Robot's Canteen is considered empty (Robot's latest CanteenLevel.gallons is less than the Robot's latest Configuration.canteen_empty_level). The aim is to allow for a statement like this using the annotation in the QuerySet: bad_robots = Robot.objects.filter(canteen_empty=True) I had tried something like this in the annotation: canteen_empty=ExpressionWrapper(CanteenLevel.objects.filter(robot=OuterRef('pk')).order_by('-time').values('gallons')[:1] <= RobotConfiguration.objects.filter(robot=OuterRef('robot')).order_by('-time').values('canteen_empty_level')[:1], output_field=models.BooleanField)) But obviously the "<=" operator isn't allowed. I also tried this: canteen_empty=Exists(CanteenLevel.objects.filter(robot=OuterRef('pk')).order_by('-time').values('gallons')[:1].filter(gallons__lte=Subquery(RobotConfiguration.objects.filter(robot=OuterRef('robot')).order_by('-time').values('canteen_empty_level')[:1])))) But you can't filter after taking a slice of a QuerySet. Any help would be appreciated! -
Django unit tests, custom permission and request.user.username
I need to restrict access to the APIs I have defined in my view. Here is my views.py: rom rest_framework import generics from rest_framework import permissions from .serializers import LocationSerializer, PartSerializer, PartLocationSerializer, SiteSerializer from .models import Location, Part, PartLocation, Site, SPIUser class SPIPermission(permissions.BasePermission): """ blah blah blah ... """ def has_permission(self, request, view): try: username = request.user.username SPIUser.objects.get(username=username) except SPIUser.DoesNotExist: return False if not request.user.is_authenticated: return False return True class LocationList(generics.ListCreateAPIView): # using get_queryset().order_by('id') prevents UnorderedObjectListWarning queryset = Location.objects.get_queryset().order_by('id') serializer_class = LocationSerializer permission_classes = (SPIPermission,) I want to demonstrate in my unit tests that your have to be an SPIUser to be able to access these api endpoints so I write a simple unit test like so: from .models import Location, Part, PartLocation, Site, SPIUser from .urls import urlpatterns from my.APITestCase import RemoteAuthenticatedTest from django.db.models import ProtectedError from django.test import TransactionTestCase from django.urls import reverse from rest_framework import status import django.db.utils import os class ViewTestCases(RemoteAuthenticatedTest): def test_spi_permission(self): url = reverse('spi:locationlist') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) SPIUser.objects.create(username=self.username) response = self.client.get(url) self.assertNotEquals(response.status_code, status.HTTP_403_FORBIDDEN) This test fails with the this error message: Failure Traceback (most recent call last): File "/apps/man/apman/spi/tests.py", line 21, in test_spi_permission self.assertNotEquals(response.status_code, status.HTTP_403_FORBIDDEN) AssertionError: 403 == 403 I noticed that … -
Running a background task involving a third-party service in Django
The use-case is this: we need to pull in data from a third-party service and update the database with fresh records, every week. The different ways I have been able to explore have been either creating a custom django-admin command or running a background task using Celery (and probably ELK for logging) I just want to know which way is more feasible and simpler? And if there's another way that I can explore. What I want is monitoring the task for the first few runs then just relying on the logs. -
Inventory System Using ManyToMany
I am building an app in Django for a class that provides the backend for an IT company, allowing them to track clients, inventory, work orders and more. I am able to enter in data and view it just fine. My issue, however, is that I would like for a couple fields to auto-populate- ideally, that when a work order is submitted, that 'work_orders.hours_worked' would populate 'client.used_hours' for the client in question, as well as 'work_order.items_used_quantity' would for populate 'inventory.item_quantity_sold' for the item in question. I have tried countless tutorials on using ManyToMany relationships including the documentation and just can't seem to wrap my head around applying it to the context of keeping counts like this. I know it involves intermediary tables but I haven't been able to make the relationships correctly. #Models class client(models.Model): client_name=models.CharField(max_length = 30) contact_name=models.CharField(max_length = 20) email=models.EmailField(max_length = 35) phone=models.CharField(max_length = 15) address=models.CharField(max_length=50) city=models.CharField(max_length = 30) state=models.CharField(max_length = 30) zipcode=models.PositiveSmallIntegerField() contract_plan_ID=models.ForeignKey(contract_plan,default=5) plan_hours=models.PositiveSmallIntegerField(default=0) used_hours=models.PositiveSmallIntegerField(default=0) start_date=models.DateField() class inventory(models.Model): item_name=models.CharField(max_length = 30) item_description=models.CharField(max_length = 100) item_quantity_sold=models.PositiveSmallIntegerField(default=0) item_price=models.DecimalField(decimal_places=2,max_digits=6) class work_order(models.Model): order_date=models.DateField() tech_ID=models.ForeignKey(technician) client_ID=models.ForeignKey(client) order_details=models.CharField(max_length = 1000) hours_worked=models.PositiveSmallIntegerField() order_signature=models.CharField(max_length = 30) item_used=models.ForeignKey(inventory) items_used_quantity=models.PositiveSmallIntegerField(default=0) Following the Django documentation of the Pizza example (https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships) I can never seem to get anything to …