Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Django app with multitenancy on localhost
I am developing a Django app that works with multitenancy through the django-tenant-schemas library. We bind subdomains to our tenants. I need to test a data migration locally before I run it on production but the problem I'm running into is that I cannot access all the tenants. What I need to do is use the application, click buttons and see if everything still works, posing as multiple of our clients. We currently have it set up so that the public schema is bound to 127.0.0.1 on my local machine and our own tenant to localhost. On our staging / production it would be client.ourdomain.com, but as I understand -and tested- it you cannot work with subdomains on localhost, so I'm lost on how to get access to the other tenant schemas. I have tried to edit my /etc/hosts file to bind the following 2 but those don't work: localhost client.localhost 127.0.0.1 client.localhost This seems like it would be a problem many people run into but I cannot seem to find good info on how to do this both in the official docs or elsewhere, although the second link looks to be what I need but they suggest what I … -
How can i enter value into select/option from django model?
this is my first question here. I've a model that looks like this; class Fund(models.Model): name = models.CharField(max_length=500, null=False, blank=False) code = models.CharField(max_length=5, null=False, blank=False) management_price = models.CharField(max_length=15, null=True, blank=True) performance_price = models.CharField(max_length=15, null=True, blank=True) explanation = models.TextField(max_length=1000, null=True, blank=True) And i want to show all Fund names in a select area in the template here; <div class="form-group col-md-12"> <label>Fon*</label> <select id="fundIdSelect" class="form-control select2"> <option value="0">Lütfen Fon Seçiniz</option> </select> </div> And this my relevant views.py; def privacy(request): fund_list = Fund.objects.all() return render(request, 'privacy.html', context={'fund_list': fund_list}) -
At which point does a model object converts its values to the data type of it's backend database?
For example in this model: class Invoice(models.Model): req_date = models.DateField(null = True, blank = True) def save(self, request_user = None, date = None, change_type = None, comment = None, old_obj = None, *args, **kwargs): super().save(*args, **kwargs) print(self.req_date) If i run the save() method, it prints '2020-09-28' (string), however, if i call the model instance right after the save() method (ex: print(invoice.req_date)) it gives me datetime.date(2020, 9, 28). So, at which point does the string become a datetime? I need to catch the "correct value" of the req_date (datetime object) inside the save() method. Is that possible? -
Error when trying to open a repository in Ubuntu 20.04
I coded a Todo App with Django on WSL2 and had it comitted to my github repository. On trying to clone it to my desktop with Ubuntu and running pip3 install -r requirements.txt It gave me the error: ERROR: Could not find a version that satisfies the requirement cloud-init==20.2 (from -r requirements.txt (line 9)) (from versions: none) ERROR: No matching distribution found for cloud-init==20.2 (from -r requirements.txt (line 9)) May I know how to sort out this error? -
Problem with my magnifying glass in Django
I'm trying to build a magnifying glass for my webpage in Django. I'm using a library called AnythingZoomer to magnify text: https://css-tricks.github.io/AnythingZoomer/text.html. The problem is that after adding the Scripts and the CSS that the give you in their project the magnifying effect doesn't work. I added the ids and the code needed in the HTML but it also won't work. Magnifying script (It's in base.html): <script> $(function() { // clone the small area, the css will define the dimensions // default class name for the large area is "large" $("#zoom").anythingZoomer({ clone: true }); // zoom in $('button').click(function(){ $(this).addClass('selected').siblings().removeClass('selected'); // .small p { font-size: 8px; width: 300px; } var origW = 300, origSz = 8, // get multiple multiple = parseInt( $(this).text() ); $('.large p').css({ width: origW * multiple, fontSize: origSz * multiple }); // update anythingZoomer window, // but first turn off clone since cloning the small area again will remove our changes $('#zoom').getAnythingZoomer().options.clone = false; $('#zoom').anythingZoomer(); }); }); </script> <link rel="stylesheet" href="{% static 'css/anythingzoomer.css' %}"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="{% static 'js/jquery.anythingzoomer.js' %}"></script> The text I'm trying to magnify (It's in index.html): <div id="zoom" class="row" class="zoom"> <div class="col-md-12"> <p>La memoria es una de las principales facultades humanas, nos define … -
Sending An Email Attachment In Django (Production)
I am wanting to add an attachment to an email. I am running this on a production server (I can do this in development). I have successfully stored my static files in static_files using whitenoise and they display correctly on the page. I am trying to send one of these static files in this email. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') if form.is_valid(): # have also tried '\\attachment\\test.pdf' file_path = os.path.join(settings.STATIC_ROOT+'/attachment/test.pdf') try: msg = EmailMessage('subject', 'body', '#@#.#', '#@#.#') with open(file_path, 'rb') as attach_file: data = attach_file.read() msg.add_attachment('test.pdf', data, 'application/pdf') msg.send() This throws a 500 error. Thank you. -
Introducing custom user model when auth.User FK fields already exist
We're looking to have email confirmation in our site and I started setting up django-simple-email-confirmation. This requires having a custom user model mixin which has built-in email confirmation and various utilities and wrappers: class User(SimpleEmailConfirmationUserMixin, AbstractUser): pass And then you need to change the appropriate settings: AUTH_USER_MODEL = 'appanme.User' Now the problem is that every instance of code were we used auth.User or auth.UserManager the code fails because it's using the wrong active user model. Sovling this appears to be as simple as changing User with get_user_model() (actually not sure how to go about UserManager, maybe get_user_model()._default_manager?) but now I'm concerned about all ForeignKey fields using the auth.User model will be affected or wiped since the model will change. Is this cause for concern? How should I go about using the new custom user model? -
Host Django application in the Lightsail's built in Apache server
I want to have a production ready Django app with Lighsail and for that I'm following two tutorials to achieve this Deploy Django-based application onto Amazon Lightsail Deploy A Django Project From the Bitnami article can see that the AWS documentation follows its Approach B: Self-Contained Bitnami Installations. According to: AWS's documentation, my blocker appears in 5. Host the application using Apache, step g. Bitnami's documentation, where it says On Linux, you can run the application with mod_wsgi in daemon mode. Add the following code in /opt/bitnami/apps/django/django_projects/PROJECT/conf/httpd-app.conf: The blocker relates to the code I'm being asked to add, in particular the final part that has Alias /tutorial/static "/opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.2.9-py3.7.egg/django/contrib/admin/static" WSGIScriptAlias /tutorial '/opt/bitnami/apps/django/django_projects/tutorial/tutorial/wsgi.py' More specifically, /opt/bitnami/apps/django/. In /opt/bitnami/ can only see the following folders . bitnami_application_password . bitnami_credentials . htdocs . stack and from them the one that most likely resembles /opt/bitnami/apps/ is /opt/bitnami/stack/. Thing is, inside of that particular folder, there's no django folder - at least as far as I can tell (already checked inside some of its folders, like the python one). The workaround for me at this particular stage is to move to a different approach, Approach A: Bitnami Installations Using System Packages (which I'm not entirely sure … -
I want to create a list of lists
I know there is quite a number of similar questions on stackoverflow but they don't seem to be solving my problem. If you look at my code below, you can see that I am creating a temp list of ads called "tempAdList" and when the if condition evaluate true I am creating a list of lists called "ad_list". I am appending to "ad_list" so I am expecting that everytime the "if statement" evaluates true a new list of 4 ads is appended to "ad_list" but for whatever reason I am getting below output which is not what i am looking for. what am I doing wrong here? ads = Advert.objects.all() counter = 1 tempAdList = [] ad_list = [] for i, ad in enumerate(ads): tempAdList.append(ad) if counter == 4: # print(tempAdList) ad_list.append(tempAdList) print(ad_list) tempAdList.clear() counter = 0 counter += 1 adsNum = len(ads) # print("i = {} and adsNum = {}".format(i, adsNum)) if i == adsNum -1 and adsNum % 4 != 0: ad_list.append(tempAdList) output: -
Choices makemigration error: There are some values Django cannot serialize into migration files
I have error Cannot serialize for this: MY_CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) It works, but how critical is it and how to fix it? In general, I'm trying to make a MultipleChoiceField where the values will be from the current model class, but I have no idea how to get "self" in models.py. So I did something like this: my forms.py class UpdatePrintDocForm(ModelForm): CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) the_choices = forms.MultipleChoiceField( choices=CHOICES, widget=forms.CheckboxSelectMultiple() ) class Meta: model = Student fields = ("the_choices",) my models.py class Student(models.Model): MY_CHOICES = ((c.pk, c.course) for c in CourseInstance.objects.all()) the_choices = MultiSelectField(choices=MY_CHOICES, blank=True) my views.py def UpdatePrintDoc(request, pk): student_inst = get_object_or_404(Student, pk=pk) redirect_to = request.GET.get("next", "") if request.method == "POST": form = UpdatePrintDocForm(request.POST) if form.is_valid(): student_inst.the_choices = form.cleaned_data.get("the_choices") student_inst.save() return HttpResponseRedirect(redirect_to) else: initial_data = {"the_choices": student_inst.the_choices} form = UpdatePrintDocForm(initial=initial_data) return render( request, "spacestud/doc_update.html", {"form": form, "studentinst": student_inst}, ) my doc_update.html <form action="" method="post" enctype = "multipart/form-data"> {% csrf_token %} <table> {% for field in form %} <div class="row"> <div class="col-md-2"> {{ field.label_tag }} {% if field.help_text %} <sup>{{ field.help_text }}</sup> {% endif %} {{ field.errors }} </div> <div class="col-md-10 pull-left"> <ul id="id_the_choices"> {% for course in studentinst.course.all %} {% … -
Django user authentication and login problem
I created a signup and signin form. when I create a user using signup it is working perfectly and creates user. but when i try to login with same user it is not able to login. It actually go to else block and show the wrong credential messages. whenever I try to login with my existing user it shows wrong credential. can anyone help me how can I solve this issue. Thank you else block error msg even after correct user users I createdlogin window view.py file from django.shortcuts import render, HttpResponse, redirect from .models import Contact from django.contrib import messages from blog.models import Post from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def handleSignUp(request): if request.method == 'POST': username = request.POST.get('username') fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') pass1 = request.POST.get('pass1') pass2 = request.POST.get('pass2') #check verify sign field if len(username) > 10: messages.error(request, 'User name must not more than 10 characters') return redirect('/') if not username.isalnum(): messages.error(request, 'User name must contain alpha numeric characters') return redirect('/') if pass1 != pass2: messages.error(request, 'Password did not match') return redirect('/') #create user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.save() messages.success(request, 'You account has … -
not able to get the driver version pyodbc
Unable to start Django application due to pyodbc error django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') i have tried printing the driver used but do net get any driver info import pyodbc print(pyodbc.drivers()) this is the result of the above ['SQL Server'] any ideas? -
Run Django tests on Heroku CI with postgres extensions
Overview I have an app that is deployed on Heroku and uses Heroku Postgres add-on as the default database. I use PostGIS and Hstore extensions to store geographic and Hstore(key-value pair) data. Problem Statement I am configuring Heroku CI to run the test-cases. As the Django application creates a test database during the test run, I need to provision one for it. But I know that the Heroku's in-dyno database does not support postgis and hstore extension. So I provisioned a free-tier hobby-dev heroku postgres add-on for it. Now I get the following error: Got an error creating the test database: permission denied to create database Below is my app.json config: { "environments": { "test": { "scripts": { "test-setup": "pip install -r requirements.txt", "test": "python manage.py test -v 2 --noinput" }, "addons": [ "heroku-postgresql:hobby-dev", "heroku-redis:in-dyno" ], "buildpacks": [ { "url": "heroku/python" }, { "url": "https://github.com/heroku/heroku-geo-buildpack" } ] } } } The key questions here are: Is it advised to use in-dyno Postgres or provide it as an add-on? If in-dyno Postgres, how do I install the extensions? If as an add-on, how do I run the Django tests using the provisioned database? (as it doesn't allow me to create a … -
Send Dynamic js value stored in variable to the django python backend
Adding popup and displying the selected value from the drop down. when submit button is clicked sending data to the django python backend view to save in mysql db. currently storing the value in a variable i.e OS Value Submit Cancel <script> $('#submit_add').click(function(){ var osvalue = $('#id_os_make option:selected').text(); alert(osvalue); var data2 = $('#id_host_protocol option:selected').text(); var reason = $('#textbox').val(); alert(reason); var confirmBox = $('.confirm-box'); confirmBox.css('display', 'none'); }); -
Django tabularinline from different app models
I am new with Django. My question is how to showing the data as Tabularinline in DetailView in django from two different apps,. I have a Team model in users app and Project and Client in projects app. I want to show all the projects that belong to a specific team in team delailview. my issue is how to show the results in the template form, the results are shown in the django admin but i cant show them in the html code i wrote, here is the codes: 1st App: CustomeUser class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) memberOf = models.ManyToManyField("Team", blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) second app Project class Client(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="client_team") title = models.CharField(max_length=150, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) client=models.ForeignKey(Client,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) purchase_number= models.CharField(max_length=50, null=True, blank=True) PO_date = models.DateTimeField( blank=True, null=True) completion_date = models.DateTimeField( … -
Does slug url with id is accepted by Google in django
Does slug url with id is accepted by Google? I mean when I add website and pages to Google search console for example example.com/url-1 ? i mean www.example.com/pubg-mobile-4 is that valid URL and accepted by Google? -
Django migration sqlmigrate
I have created a migration file to alter unique key constraint of a model, previously it had 4 fields in unique key , now its has 5 , after running migrate command its worked fine. but now i am unable to generate sql query using sqlmigrate. Error is "ValueError: Found wrong number (0) of constraints for rule_set(business_function_id, business_process_id, process_state, status)" In My DB right now constraint is :- UNIQUE KEY rule_set_business_function_id_bus_6bda6da3_uniq (business_function_id,business_process_id,process_state,rule_set_name,status), What did i do wrong? -
'Request' object has no attribute 'pop' in Django Rest Framework?
I have a Post model which has Foreign key with User model. So when I created Post object I need to pass user instance by overriding the create method inside ModelViewSet but it failed. here is what I have tried: models.py class Post(models.Model): author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() serializers.py class PostSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="api:posts-detail") author = UserSerializer() class Meta: model = models.Post fields = ['url', 'id', 'author', 'title', 'content'] views.py class PostViewSet(viewsets.ModelViewSet): serializer_class = serializers.PostSerializer def get_queryset(self, *args, **kwargs): user = self.request.user return models.Post.objects.all().filter(author=user) permission_classes_by_action = { 'create': [permissions.IsAuthenticated], 'list': [permissions.IsAuthenticated], # other permissions.. } def create(self, validated_data): author = validated_data.pop('author_id') print(author) post = models.Post.objects.create(author=author, **validated_data) return post def list(self, request, *args, **kwargs): return super(PostViewSet, self).list(request, *args, **kwargs) # other methods def get_permissions(self): try: # return permission_classes depending on `action` return [permission() for permission in self.permission_classes_by_action[self.action]] except KeyError: # action is not set return default permission_classes return [permission() for permission in self.permission_classes] the whole error I got Traceback (most recent call last): File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/django-api/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", … -
From PHP to Python [closed]
I kindly request for a refactoring of this PHP code to Python. <?php $response_data = file_get_contents("php://input"); $logFile = "response.json"; $log = fopen($logFile, "a"); fwrite($log, $response_data); fclose($log); ?> -
Aggregate result in django rest framework
In my posgresql I have a model "words": class Words(models.Model): word = models.CharField(db_index=True, max_length=50) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) time_stamp = models.TimeField(auto_now=False, auto_now_add=False) In my view, after a query, I search for words that icontains the query itself A lot of words are duplicated and i need to aggregate them in the result My goal is to respond with a json file that collects the various words and lists their timestamps Something like this: [ { "word": "foo", "list": [ { "id": 10416, "lesson": 11, "time_stamp": "00:02:49.100000" }, { "id": 10702, "lesson": 12, "time_stamp": "00:27:31.300000" }, ... ] }, { "word": "too", "list": [ { "id": 10416, "lesson": 11, "time_stamp": "00:02:49.100000" }, { "id": 10702, "lesson": 12, "time_stamp": "00:27:31.300000" }, ... ] }, ] Is there a smart way to do this? -
How to make a function not included in a rollback?
Let's say I have 3 functions A, B, C. Function B calls Function A and Function C calls Function B. def function_A(): # do something here @transaction.atomic def function_B(): # some code function_A() # calls function A @transaction.atomic def function_C(): try: SomeModel.objects.get(id=id) except SomeModel.DoesNotExist: pass # calls function B function_B() # I don't want this to rollback when something fails here # code that fails and rollsback everything When something fails in functionC it seems that it also rollsback function A, is it possible to make sure function A doesn't get rolledback when function C fails? If so how do I that? -
Update auto_now field in bulk_update
I'm using Django 2.2 and I have a model with auto_now "modification_datetime" field and I need to update it during/after a bulk_update execution only for the affected registries that were really updated. Is it possible to update auto_now datetime model field only on the affected records by bulk_update execution? -
DjangoRestFramework: How to pass value in url?
I've created a simple api using DjangoRestFramework, which adds 3 number: @api_view(["GET"]) def calcDistance(request): a = request.query_params.get('a') b = request.query_params.get('b') c = request.query_params.get('c') r = int(a) + int(b) + int(c) return JsonResponse({"Print": "r={}".format(r)}, status=status.HTTP_200_OK) API call: http://127.0.0.1:8000/calcDistance/?a=2&b=3&c=5 Output: {"Print": "r=10"} Now I want to call API without passing variable names(a,b and c) in url: e.g.: http://127.0.0.1:8000/calcDistance/?2&3&5 Can someone help me to achieve this? -
django (rest framework) serializer usage for incoming and outgoing data
I am new to Django and have a question regarding the serializers. Is a serializer about INCOMING data (from the body) or also about returned data? For example if I have a request with an incoming body of {"test":1} and it returns data like {"new_test": True}, how would I describe this in a serializer? -
django mail with attachment and body text issue
In django i am not able to send body html with attachment . what i am doing wron here i dont know can any one please help me related this ? my code is given below. def mail_booking_invoice(request): result = {} if request.method == 'POST' and request.is_ajax(): try: boking_id = request.POST.get('id') config = EmailConfiguration.objects.filter(pk=1).first() connection = get_connection( host=config.host, port=config.port, username=config.from_email, password=config.password, use_tls=config.tls, ) bookingObj = Booking.objects.get(id = boking_id) email_to = '' if bookingObj.patient_email and bookingObj.contact_person_email == '': email_to = bookingObj.patient_email else: email_to = bookingObj.contact_person_email config = EmailConfiguration.objects.filter(pk=1).first() if email_to!='' and config: all_objects = Booking.objects.filter(id=boking_id) data = serializers.serialize('json', all_objects) json_objects = json.loads(data) customObj = [] for index in range(len(json_objects)): json_objects[index]['fields']['id'] = all_objects[index].id bookingStops = BookingStop.objects.filter( booking_id=all_objects[index].id) bookingStatus = BookingStatus.objects.get( booking_id=all_objects[index].id, status=3) json_objects[index]['fields']['stops'] = bookingStops json_objects[index]['fields']['price'] = bookingStatus.price json_objects[index]['fields']['vehicle_no'] = bookingStatus.vehicle.vehicle_no json_objects[index]['fields']['driver_name'] = bookingStatus.driver.first_name + \ ' ' + bookingStatus.driver.last_name json_objects[index]['fields']['booking_date__format'] = all_objects[index].pickup_date.strftime( "%m/%d/%Y") customObj.append(json_objects[index]['fields']) from django.core.mail import send_mail from django.core import mail from django.core.mail import EmailMessage html = render_to_string('admin/booking/invoice.html',{'result': customObj}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=invoice' + '.pdf' pdf = weasyprint.HTML(string=html,).write_pdf(stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) subject = "Booking invoice" htmls = "Hello Neha,<p> Please find your Booking Invoice in attachement</p>Thanks & Regards Hirbuu.com'" mail.send_mail('subject', 'plain_message', config.from_email, [email_to], html_message=htmls,connection=connection) # EmailMessage.attach("invoice" + '.pdf', …