Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query Set: all devices at location: location has a Foreign Key to Devices
I want to run a query that returns all of the devices for each location. models.py class Devices(models.Model): device_hostname = models.CharField(max_length=30) device_ip = models.CharField(max_length=35) device_type = models.CharField(max_length=40) device_serial_number = models.CharField(max_length=35, ) device_service_tag = models.CharField(max_length=35, default=None) device_model = models.CharField(max_length=35, default=None) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) locations = models.ForeignKey(Locations, on_delete=models.CASCADE) maintenance = models.ForeignKey(Maintenance,on_delete=models.CASCADE, null=True, blank=True) def __str__(self): # returns string return self.device_hostname def __unicode__(self): return self.device_hostname and for Locations class Locations(models.Model): location_name = models.CharField(max_length=20) location_address = models.TextField(max_length=15) location_city = models.CharField(max_length=35) location_state = models.CharField(max_length=30) location_zip = models.CharField(max_length=15) location_country = models.CharField(max_length=30) def __str__(self): # returns string return self.location_name def __unicode__(self): return self.location_name My search_device_list.html reads as follows: <h2 align="center">Search Page</h2> {% if dev_loc %} <table> <tr> <td><b>Locations:</b></td> <td><b>Device</b></td> {% csrf_token %} {% for locations in dev_loc%} </tr> <tr> <td id="location_name"> {{device.locations.location_name}} &nbsp;<br>}</td> <td = "dev_loc_search">{{device.device_hostname}} </tr> {% endfor %} </table> {% endif %} <br> when my views.py reads as follows: def search_device_list(request): locations = Locations.objects.all() dev_loc= Devices.objects.filter(locations__in= locations) context = {"dev_loc": dev_loc} return render(request, 'inventory/search_device_list.html', context) I don't get an error message, but I don't get a rendering Locations and Devices without data When my code for views.py reads as follows: def search_device_list(request): locations = Locations.objects.all() dev_loc= Devices.objects.filter(locations = locations) context = {"dev_loc": dev_loc} return … -
Datetime fields. How to add validation end_date is higher than start_date with DJANGO in python model class?
Can someone help me with this? I try to add a validation like the following: start_date < end_date These variables are datetime type. I hope someone already did this validation. date_start = models.DateTimeField( verbose_name=_("start date") ) date_end = models.DateTimeField( blank=True, null=True, verbose_name=_("end date") ) -
How to change a queryset for xhtml2pdf via ajax
im trying to build a function where by the user is able to select the items he wishes to render to pdf. In order to do this, i first did some code to store the PK of the items the user selected. (javascript) var arr = [] function selector(clicked_id){ var a = clicked_id if (arr.includes(a) === false){ arr.push(a) document.getElementById(a).classList.add('bg-light'); } else { const index = arr.indexOf(a) arr.splice(index, 1) document.getElementById(a).classList.remove('bg-light') } console.log(arr) console.log(a) }; (html) {%for trial in trials %} <td style="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000" align="center" valign=middle bgcolor="#CCFFFF" id={{trial.trial_id}} onClick="return selector(this.id);"><b><font face="Arial" size=1> </td> {%endfor%} As such , clicking onto the table cell will change the color of the cell and save the pk into an array. When the user clicks the button to generate the pdf , i wil pass the list of pk through into an ajax function as such : function ajaxsender(clicked_id){ $.ajax({ url : "{% url 'bom-pdf'%}", method : "POST", data : { 'csrfmiddlewaretoken' : "{{ csrf_token }}", 'arr' : arr }, success : function(result) { console.log(arr) } })}; (HTML) {% for product in product %} <a {% url 'bom-create' product.formulation_id %} id = {{product.formulation_id}} … -
what is related_name and related_query_name in django?
i have an issue with the code in django framework regarding to related_name and related_query_name in django. please django expert explain the related_name in django, the code is below: related_name='+' -
In Django which version is now stable in 2020?
I want to know what version is stable to use with python 3.I am currently using 2.2.7 , and like to know if am going correct on it. -
Django migration non existent parent node after moving to production server
I'm trying to deploy my app on PythonAnywhere and when i go to apply the migrations i get an error that a migration dependency does not exist. I've completely reset the migrations by deleting them from the migrations folder, dropping the database and re-creating it, and running makemigrations. I only have my one initial migration now and everything works on my local machine. workflow goes like this: 1 - clone the current version I'm using to PythonAnywhere. 2 - run ./manage migrate to initialize the database (the very first time) and get error: (rwe) 17:00 ~/rwe (develop)$ ./manage.py migrate asyncio DEBUG Using selector: EpollSelector Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/IAMCB/.virtualenvs/rwe-Cn2YEGYr/lib/python3.7/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File … -
Django views as_view()
Example views.py: from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') Example urls.py: from django.urls import path from myapp.views import MyView urlpatterns = [ path('mine/', MyView.as_view(), name='my-view'), ] classmethod as_view(**initkwargs)¶ What happens when a request from the user is received? Is the view returned from ClassView.as_view() called? Or is an instance of Class View created? -
freeze_time `ignore` doesn't seem to work in more complicated setup (Django + S3 / boto)
I am using Django with S3 as the file storage (which uses boto3/botocore libs). I have a "management" command which creates some Django instances - I use freezegun, so these instances appear to be created in the past. However some of these models contain files, that are being saved to S3 - which raises some exceptions: ... File "/home/rado/.virtualenvs/twisto/lib/python3.6/site-packages/botocore/client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/rado/.virtualenvs/twisto/lib/python3.6/site-packages/botocore/client.py", line 612, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (RequestTimeTooSkewed) when calling the ListObjectsV2 operation: The difference between the request time and the current time is too large. this is due to some authentication code in botocore.auth module, that checks for time differences. I tried to solve this issue using ignore parameter (freeze_time(datetime_in_past, ignore=['botocore'])), but it didn't help, botocore.auth still used the FakeDatetime (I used debugger with breakpoints to pinpoint the issue). I tried to recreate the issue with a simple reproducible example, so I came up with following: # test.py from freezegun import freeze_time from datetime import datetime import stuff_in_between import test_time # <-- note this unused import with freeze_time(datetime(2019, 1, 1, 1, 1, 1, 1), ignore=['test_time']): print(f'frozen time: {datetime.now()}') stuff_in_between.call_test_time() # stuff_in_between.py def call_test_time(): import test_time test_time.test_time() # … -
how to show if no result given date range and 0 result with django annotate?
With results showing correctly but if no results how to show date and 0 result pre_days = datetime.datetime.today() - timedelta(days=6) today_now = datetime.datetime.today() enquiry_chart = All_enquiries.objects.filter(enquired_at__range=[pre_days, today_now]).values('enquired_at__date').annotate(enquired=Count('id')) example -
I have problems with templates
https://repl.it/@DEADDYNASTYDYNA/YellowFriendlyIrc When i added second app in my project templates are bagged. I have TemplateDoesNotExist problem -
Why Error django error TemplateDoesNotExist?
I am new to Django. I use Pycharm. When I go to my : 127.0.0.1:8000/polls/ I got this error: TemplateDoesNotExist at /polls/ I already searched a lot about similar problems, I did what people said but still not working. Thanks you for helping me. Been looking around about this for a couple days. -mysite -mysite __init__.py asgi.py settings.py urls.py wsgi.py -polls - migrations __init__.py __init__.py - template form.html admin.py models.py tests.py views.py forms.py apps.py urls.py db.sqlite3 manage.py templates/form.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {{ form }} </body> </html> mysite/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')) ] polls/views.py from django.shortcuts import render from .forms import ContactForm from django.http import HttpResponse def contact(request): form = ContactForm() return render(request, 'form.html', {'form': form}) polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.contact) ] and click run and visit localhost:8080, here are results: TemplateDoesNotExist at /polls/ form.html Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 3.0.3 Exception Type: TemplateDoesNotExist Exception Value: form.html Exception Location: C:\Users\tiber\PycharmProjects\django_project1\venv\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\tiber\PycharmProjects\django_project1\venv\Scripts\python.exe Python Version: 3.8.0 … -
Deploying my application result to frustration
I am highly frustrated in deploying my application using the pythonanywhere and github.Being a beginner,I have followed the instruction in the book of "django girls tutorial and other link someone sent to on this platform. All my effort proved abortive. I don't know which book I should use or any other simple step of deploying it. I do not want to quit this. -
How can I improve my database schema for an events management social network (similar to eventbrite)?
I have created a basic layout of the database here - https://dbdiagram.io/d/5e3d48489e76504e0ef12a2b. I'm making it in django, not that I'm sure that's relevant, but it could be. The concept is an events management site similar to eventbrite but with a larger social feel. Users will have followers etc and when signing up they'll select interests, which will be used to show them events they may be interested in. The events can be free or not and can be private or not. Users can create and attend events and post photos to the events, which will be displayed in the events page and on both the hosts page (as photos of events hosted) and on the user who posted thems page (apologies about the grammar there). If anything else isn't about why I've structured it the way I have then please ask. I'm just wanting to know of any alterations you'd make and why. -
Refer to my app's url namespace in Django
I want to write a reusable Django application. I tell my users to add the following to their urls.py path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'), And in my urls.py I want to have a view login_callback. Now in my view, I need to get a value of slack_integration:login_callback. I can trust the user that he/she will integrate it with slack_integration prefix and use it. But is this the best practise? Can I somehow get the name of the namespace for the app if user chooses a different name for it? Thanks a lot! -
One product under two cotegories
I'm trying to have the ability to have my products appear under multiple categories. I've been using ManyToManyField rather than 'ForeignKey'. However I'm facing two problems: When I go to a category detail page it's giving me an error when it iterates over the products. It's not getting the category slug but it is getting the product slug. So when I navigate to 127.0.0.1:8000/products/cars/ I get: Reverse for 'model_detail_view' with arguments '('', 'blue-car')' not found. 1 pattern(s) tried: ['products/(?P<category_slug>[^/]+)/(?P<model_slug>[^/]+)/$'] It should be having a slug of 127.0.0.1:8000/products/cars/blue-car Also my product model has a `BooleanField' that can feature the product on the homepage. How does if decide which category to use if it is under several categories? -
Cannot assign must be a "" instance
i'm working on my first django project and i got this error (Cannot assign "'433245675'": "Lockers.locker_id" must be a "Renters" instance.) anyone here can help me pleas. the views: def adding_renter(request): form_data = forms.AddingRenter(request.POST or None) msg = '' if form_data.is_valid(): renters = models.Renters() renters.renter_id = form_data.cleaned_data['renter_id'] renters.renter_name = form_data.cleaned_data['renter_name'] renters.renter_email = form_data.cleaned_data['renter_email'] renters.renter_phone_number = form_data.cleaned_data['renter_phone_number'] renters.renting_start_date = form_data.cleaned_data['renting_start_date'] renters.renting_end_date = form_data.cleaned_data['renting_end_date'] renters.save() msg = 'Renter has been added successfully' context = { 'form': form_data, 'msg': msg } return render(request, 'addingrenter.html', context) def adding_locker(request): form_data = forms.AddingLocker(request.POST or None) msg = '' if form_data.is_valid(): lockers = models.Lockers() lockers.locker_id = form_data.cleaned_data['locker_id'] lockers.locker_number = form_data.cleaned_data['locker_number'] lockers.locker_information = form_data.cleaned_data['locker_information'] lockers.locker_status = form_data.cleaned_data['locker_status'] lockers.locker_notes = form_data.cleaned_data['locker_notes'] lockers.save() msg = 'Locker has been added successfully' context = { 'form': form_data, 'msg': msg } return render(request, 'addinglocker.html', context) -
How to create an eml file as outlook draft email with django EmailMessage?
I'm looking for an email as a draft. I would like to double click on later draft and send it via outlook. Currently, I am able to create the eml file and open it in outlook on double click. However, I cannot send it. Can you help me please, I spent a week above but without success. Here is the code: from django.core.mail import EmailMessage @login_required def Envoi_Mail(request): date_now = datetime.datetime.now().strftime("%Y-%m-%d") id_path = request.GET.get('id_path') dossier_media = str(settings.MEDIA_ROOT) msg = EmailMessage( 'Bonjour', 'Test test tes', 'from@abc.com', ['to@abc.com'], ) content_text = msg.message().as_bytes() file_name = dossier_media + "/" + str(date_now) + ".eml" with open(file_name, "wb") as outfile: outfile.write(content_text) return redirect(id_path) Here is what I get: Here is what I would like to have: -
How to run a python script based on pip installation in docker?
My docker file design is as follows: #Use python 3.6 image FROM python:3.6 ENV PYTHONUNBUFFERED 1 #install required packages RUN apt-get update RUN apt-get install libsasl2-dev libldap2-dev libssl-dev python3-dev psmisc -y #install a pip package #Note: This pip package has a completely configured django project in it RUN pip install <pip-packge> #add a configuration file required for setup ADD appAdd.json / #Run a script #Note: Here appmanage.py is a file inside the pip installed location, but it will be accesible directly without cd to the folder RUN appmanage.py appAdd.json #The <pip-packge> installed comes with a built in django package, so running it with following CMD #Note: Here manage.py is present inside the pip package folder but it is accesible directly CMD ["manage.py","runserver","0.0.0.0:8000"] When i run : sudo docker build -t test-app . The error is as follows: The command '/bin/sh -c appmanage.py appAdd.json' returned a non-zero code: 137 I think its treating it as shell script rather than python script. How can i overcome this and run the django project sucessfully? Note: In local environment I could execute the steps in my machine and successfully setup.So no issues with the code of the django project which comes with pip package -
Is there a way to retry with pyppeteer after a TimeoutError?
I created a browser that scrapes several pages (I open a new page and close it each time). Around the 40th page, I get a timeout error (It's sort of random between page 38-42). When this happens, I would like to retry (catch the timeout exception and rerun) but if I create a new page, my code just hangs so it obviously put my browser object in a bad state. Do I have to kill that browser instance and start again or is there some sort of retry mechanism? -
Django and Angular redirection issue
I am stuck with a problem related to an application in Django. I have defined my urls in url.py file like: path('', include('app1.urls')), path('auth/', include('auth.urls', namespace='auth')), url(r'^.*', TemplateView.as_view(template_name="index.html"), name="home") I have defined app1.urls as: path('endpoint1', views.method1, name="display1"), path('endpoint2', views.method2, name="display2"), and auth.urls as: path('login', views.login, name='login'), path('auth', views.auth, name='auth'), In my template folder I have the index file which I am using for the home page. In my static folder I have the angular code for front end. I am doing authentication based on single sign on. The application work flow is like: Hit the host URL, let say https://example.com It will do the authentication and redirect to home page. I can browse the application fine. But, if I delete the cookies and do refresh on some page other then https://example.com, I am seeing authentication errors. If I delete the cookies and do refresh on https://example.com page the application will work fine again. After inspecting the authentication error, Authentication team says I am doing a full page redirect when I do refresh from https://example.com page but when done on any other pages it is not a full page redirect The authentication team does not know about Django and angular, so … -
How to display backward referenced model instances in Django admin interface?
I've ManyToMany references between 2 models, comparable to Django's Many-To-Many example: from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline In the default Django admin interface I see for every article which publications it is linked to. But I don't see for a single publication which article it is linked to. How can I add this information to the admin interface? -
How change queryset of select field dynamically in a formset?
I have the following scenario, I have a coin selection field and an inline contract formset where one of the fields is a contract selection, and I want to show only the contracts that belong to the selected currency. Is there any way to change the queryset of the field dynamically? -
Django migrations always fail
when I make the migrations using python manage.py migrate manage (yes it's Django 1.8 and I can't change it :/), the migrations (every single one I tested) always fail with the same error : django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK Here is the code from the migration file : class Migration(SchemaMigration): def forwards(self, orm): # Check expiry keys in Organization for org in Organization.objects.all(): self.checkExpiryDate(org) # Check expiry keys in UserProfileRoleInOrganization for uprio in UserProfileRoleInOrganization.objects.all(): self.checkExpiryDate(uprio) def checkExpiryDate(self, entity): # Check if expiry_date is consistent with apikey and fix it if necessary if not entity.date_has_changed: return date_in_key = entity.getExpiryDateInKey() if not date_in_key: return y = int(date_in_key[:4]) m = int(date_in_key[4:-2]) d = int(date_in_key[-2:]) entity.expiry_date = datetime.datetime(y,m,d) entity.save() def backwards(self, orm): pass I've seen some answers to other similar questions but no, I don't have any @commit.... decorator in my code. May somebody help me please ? -
How can to test Facebook auth in Django?
I have following logic serializers from rest_auth.registration.serializers import SocialLoginSerializer as RestAuthSocialLoginSerializer class LoginStatusSerializerMixin: def validate(self, attrs): attrs = super().validate(attrs) user = attrs['user'] statuses = self.context.get('statuses', (User.ACTIVE, User.DEACTIVATED)) if user.status not in statuses: raise ValidationError('Unable to log in with provided credentials.') return attrs class SocialLoginSerializer(LoginStatusSerializerMixin, RestAuthSocialLoginSerializer): pass views class FacebookLoginView(SocialLoginView): adapter_class = FacebookOAuth2Adapter serializer_class = SocialLoginSerializer def login(self): self.user = self.serializer.validated_data["user"] if self.user.status == self.user.ACTIVE: super().login() def get_response(self): if self.user.status == self.user.DEACTIVATED: return Response( {"detail": "User has been deactivated"}, status=status.HTTP_403_FORBIDDEN, ) return super().get_response() How can to test it? I need to use mock? How? -
Django.: How can I save direct to ManytoMany field?
I'd like to make if payer is not in the dutch_payer, I'd like to same payer name user checked in dutch_payer. So payer is always checked in dutch_payer as a default. But the problem is dutch_payer is m2m and it is getting error like : Direct assignment to the forward side of a many-to-many set is prohibited. Use dutch_payer.set() instead. how can overcome this problem? class UpdateMoneylogForm(forms.ModelForm): class Meta: model = models.Moneylog fields = ( "pay_day", "payer", "dutch_payer", "price", "category", "memo", ) widgets = { "pay_day": forms.DateTimeInput(attrs={"style": "width:100%"}), "dutch_payer": forms.CheckboxSelectMultiple, "memo": forms.Textarea(attrs={"rows": 3, "style": "width:100%"}) } def save(self, *args, **kwargs): payer = self.cleaned_data.get("payer") dutch_payer = self.cleaned_data.get( "dutch_payer").filter(name=payer) if dutch_payer.count()==0: # some code in here moneylog = super().save(commit=False) return moneylog Moneylog>models.py class Moneylog(core_models.TimeStampedModel): ... payer = models.ForeignKey( tempfriend_models.Tempfriend, on_delete=models.CASCADE, related_name="payer") dutch_payer = models.ManyToManyField( tempfriend_models.Tempfriend, related_name="dutch_payer", blank=True)