Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cron is not running using crontab
I have made a file named updatefield.py content is from FrontEnd.views import UpdateField def my_scheduler(): # add logic UpdateField() I have put it inside my project root with manage.py file And my settings.py file is like CRONJOBS = [ ('* * * * *', 'Ravi.updatefield.my_scheduler') ] Installed apps 'django_cron', 'django_crontab', After executing command python manage.py crontab add I got adding cronjob: (33083f0c14f7cccdc5851431976adcbb) -> ('* * * * *', 'Ravi.updatefield.my_scheduler') But its not running Right now . And noting is appearing on my terminal my function is this def UpdateField(request): print('hi') return HttpResponse('hello world') -
Nginx configuration file is not working due to server_names_hash_bucket_size
I am trying to make nginx, gunicorn and supervisord work on Ubuntu and django project for AWS EC2. Currently using this tutorial: https://www.youtube.com/watch?v=u0oEIqQV_-E Nginx in terminal is not working and I receive the message below: nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 64 nginx: configuration file /etc/nginx/nginx.conf test failed My question is: Is the right way to insert and solve the problem below? Am I using the server_names_hash_bucket_size: 64 used at the right line? if not please help me identify what line to use it. server { listen 80; server_name XXX; ***** server_names_hash_bucket_size: 64; **** I TRIED HERE location / { include proxy_params: proxy_pass http://unix:/home/ubuntu/PROJECT_NAME/app,sock; } } -
Conditioning the records to be related in a recursive relation
I have a model as the below that have a recursive relation with it self: class Unit(models.Model): unit_name = models.CharField(max_length=200, blank=False, unique=True) is_main_unit = models.BooleanField(blank=False, default=False) main_unit = models.ForeignKey('self', on_delete=models.CASCADE,blank=True,null=True) def __str__(self): return self.unit_name This one is working as I want except by that I need that ONLY objects (records in the table) that are "main" (is_main_unit=True) have related others units. In other words -and functionality talking- in the admin screen- when I am adding an non main unit, I need that only main units will displayed in the list box to be selected and related to the no main unit that is doing created. I am trying to use the 'related_name' and 'related_query_name' attributes but I can't found the way to reach the expected behavior. I tried and play with the bellow code, but I don't know how to define the condition "is_main_unit=True" in the relation definition: class Unit(models.Model): ... main_unit = models.ForeignKey('self', on_delete=models.CASCADE,blank=True,null=True,related_name='unidades_asociadas',related_query_name='unidades_principales') ... Regards and thanks in advance ... Homero Matus. -
Trying to drop table using cursor in django
I am trying to drop a table using the cursor but, it always says syntax error although I used it before and worked but not to drop table def check_TempTableNames(tableName): print(tableName) with connections['DataAdmin'].cursor() as cursor: print("Check Done") cursor.execute("DROP TABLE %s",[tableName]) def preStepBtn2(request): #empty=Rfde2003Syd0827.objects.using('DataAdmin').all() sourcePE = request.GET.get('sourcePE') targetPE =request.GET.get('targetPE') dropdownConnType =request.GET.get('dropdownConnType') sourceInterFace =request.GET.get('sourceInterFace') targetInterFace =request.GET.get('targetInterFace') temp_looback = "sop_ce_loopback_interface_" + sourcePE + "_" + targetPE TEMP_ROUTER_STATUS = "sop_ce_router_status_" + sourcePE + "_" + targetPE Temp_virtual_int = "sop_ce_virtual_interface_" + sourcePE + "_" + targetPE print(temp_looback) check_TempTableNames(temp_looback) check_TempTableNames(TEMP_ROUTER_STATUS) check_TempTableNames(Temp_virtual_int) My databases: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Fileade', 'HOST': '10.238.76.53', 'USER': 'SDS_dataflow', 'PASSWORD': 'SDS_dataflow', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } , 'DataAdmin': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Data_Admin', 'HOST': '10.238.76.53', 'USER': 'SDS_dataflow', 'PASSWORD': 'SDS_dataflow', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } } Traceback (most recent call last): File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\College\Orange Training\MassiveMigrationPortalTool\posts\views.py", line 170, in preStepBtn2 check_TempTableNames(temp_looback) File "D:\College\Orange Training\MassiveMigrationPortalTool\posts\views.py", line 147, in check_TempTableNames cursor.execute("DROP TABLE %s;",[tableName]) File "C:\Users\Mohammed\Envs\TestEnv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) … -
Unable to login with signup loginuser and password?
I'm new to django i created singnup from then data will be save in the data base at the time of login it showing :Please enter a correct username and password. Note that both fields may be case-sensitive. views.py -------- def register(request): registered = False if request.method == 'POST': form = signupform(request.POST,request.FILES) if form.is_valid(): form.save() if 'photo' in request.FILES: form.picture = request.FILES['photo'] form.save() return redirect("/accounts/login") registered = True else: print(form.errors) else: form=signupform() return render(request,'testApp/singup.html',{'registered': registered,'form':form}) def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/home/') else: return HttpResponse("Your 3010 account is disabled.") else: print("Invalid login details: {0}, {1}".format(username,password)) return HttpResponse("Invalid login details supplied.") else: return render(request, 'testapp/login.html', {}) -
Why is Docker able to save files to the source-directory?
I don't really know if this even classifies as a problem, but it somehow surprised me, since I thought that Docker containers run in sandboxed enviroments. I have a running docker-container that includes a django-rest server. When making the appropiate requests from the frontend (that's also served through a seperate NGINX-container in the same docker network) the request successfully triggers the response of the django server that includes writing the contents of the requests to a text-file. Now, the path to the text file points to a subdirectory in the folder where the script itself is located. But now the problem: the file is saved in the directory on the host-machine itself and (to my knowledge) not in the container. Now is that something that docker is capable of doing or am I just not aware that django itself (which is running in the WSGI development server mind you) writes the file to the host machine. now = datetime.now() timestamp = datetime.timestamp(now) polygon = json.loads(data['polygon']) string = '' for key in polygon: string += f'{key}={polygon[key]}\r\n' with open(f"./path/to/images/image_{timestamp}.txt", "w+") as f: f.write(string) return 200 Is there something I am missing or something I do not understand about docker or django yet? -
django unitest multiple class instance
How can I create django unitest from multiple instances? I want to fetch all objects that was created in another unitest class. I doing this because class TestClassA and TestClassB also instanced from BaseTestAuth. from app_account.views.tests.test_auth import BaseTestAuth class TestClassA(BaseTestAuth): def setUp(self): super().setUp() self.foo = Foo.objects.first() class TestClassB(BaseTestAuth): def setUp(self): super().setUp() self.bar = Bar.objects.first() class TestCombine(TestClassA, TestClassB): def setUp(self): super().setUp() self.baz = Baz.objects.first() def test_post(self): # self.bar => doesn't exist # it replaced with `TestClassA.setUp` print(self.foo, self.bar, self.baz) self.client.post(...) -
Real-Time Data with Jinja
I was using Django to display some data from my database, Jinja was so easy to use to place every string where i wanted on my css template. i was looking on the internet how to make it liveStream or real-time data display and everywhere i look there is only javascript. i dont know anything about javascript and was looking for help someone to send me to the right direction how i can make this happen as easy is possible this is a code example from my project: {% load django_template_maths %} {% block content %} <ul class="listitems"> {% for s in stats %} {% if s.0 == "37" and s.1 == "00" %} <li data-position="0"> {% else %} <li data-position="{{ s.0 }}.{{ s.1 }}"> {% endif %} -
Adding multiple bokeh html files to a django template
I created some plots with bokeh and exported them as html files. I now try to add these plots in a django template. The first plot works just fine, but if I want to add a second one it is not displayed. Here i have the python file that creates the bokeh html: from bokeh.plotting import figure, output_file, show output_file("test2.html",title="test2") p = figure(plot_width=400, plot_height=400) p.circle([1, 5, 7, 2, 5], [6, 7, 2, 5, 5], size=20, color="navy", alpha=0.5) show(p) This is the second plot, the first one is saved as test.html, the title is test and some of the point coordinates are different. And here is my django template: {% extends "MainPage/PageBase.html" %} {% block content %} <div class="container"> <div class="card"> <div class="card-header"> <font size="3">plot1</font> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p><div class="basic"> {% include "GPanalysis\WorkingData\test.html" %} </div></p> </blockquote> </div> </div> <div class="card"> <div class="card-header"> <font size="3">plot2</font> </div> <div class="card-body"> <blockquote class="blockquote mb-0"> <p><div class="basic"> {% include "GPanalysis\WorkingData\test2.html" %} </div></p> </blockquote> </div> </div> </div> {% endblock %} In the first box appears a graph but the second one is empty. I switched the position of two plots, but only the one that comes first in the html script will be displayed. … -
Error: "there is no unique constraint matching given keys for referenced table" although primary key is included
I am trying to make a comments app for a Django project whereby each record can have a number of comments attached to it. However, when I try to migrate my model, I get the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "user_info" What am I doing wrong? Currently my models look like this: users/models.py class UserInfo(models.Model): id = models.CharField(max_length=25, blank=False, null=False, primary_key=True) dob = models.DateField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) #Includes a number of other fields def __str__(self): return self.id class Meta: managed = False db_table = 'user_info' ordering = ['id'] comments/models.py from users.models import UserInfo class Comments(models.Model): patient_record = models.ForeignKey(UserInfo, on_delete=models.CASCADE, null=True, blank=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) -
Parsing JSON With Requests library In Django
I'm trying to fetch json data from a website and update my sqlite database in Django to show on the localhost. I am really stuck here. Please help me and could you please suggest me any website to take help? Thank you I am not able to parse the json correctly. I am using requests library to parse. I am getting the whole json on my local host but not able to parse individual items. this is my header of json on my local host. [{'id': 1, 'video_url':'https://storage.googleapis.com/makelocal/upload/nurs.......use',{'id': 2, 'video_url': 'https://storage.googleapis.com/......duction (short_version ver 2)'}] my views.py file from django.shortcuts import render def home(request): import requests import json api_request = requests.get('https://us-c..../content_all/json') try: api = json.loads(api_request.content) except Exception as e: api = "Error" return render(request, 'home.html', {'api':api}) this is my home.html file {% extends 'base.html' %} {% block content %} {{ api }} {% endblock %} when I am trying only api in home.html it is showing the whole json but when I am trying this<br/> {{ api.company_name }} #company_name is key in my json A blank page is coming. Could you please help me. -
Django data from database don't show in site
Problem with show data in site in django from model I try send the data from database, but nothing happend. Data don't show in site and console. views.py from django.shortcuts import render, render_to_response from .models import People def Peoples(request): data = People.objects.all() peo = { "peo_login": data } print(peo) return render_to_response("templates/login.html", peo) models.py class People(models.Model): peo_login = models.CharField(db_column='PEO_LOGIN', primary_key=True, max_length=50) peo_name = models.CharField(db_column='PEO_IMIE', max_length=255, blank=True, null=True) login.html {% for Peopl in peo %} <p>{{ Peoples.peo_login }}</p> {% endfor %} urls.py urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^login/$',auth_views.LoginView.as_view(template_name='login.html'), name='login'), I am newbie in Python, please help -
Can't add attribute to ModelForm field at __init__
I have the following model which returns the values in a ManyToMany field (approvers) as choices in an Integerfield (step): from django.utils.functional import lazy class Task(models.Model): step = models.IntegerField(null=True) approvers = models.ManyToManyField( get_user_model(), ) @property def get_step_choices(self): CHOICES = [] if self.approvers: CHOICES = [(a.id, a.email) for a in self.approvers.all()] return CHOICES def __init__(self, *args, **kwargs): super(Task, self).__init__(*args, **kwargs) self._meta.get_field('status')._choices = lazy( self.get_step_choices, list )() However, the syntax I have used under init does not appear to render the choices attr to step. Where am I going wrong? -
how can I serve my django app using http/2
I have a Django application that is deployed on AWS elastic beanstalk, when I ran the audits in my browser it recommends the use of http/2 over http/1 how to accomplish this. I know that usually you configure it using apache but here I am not using apache instead I have elastic beanstalk which has a load balancer and the Django app. how can I serve my app using http/2 ?? -
How to create a single field multiple image upload with two models?
I have a model called Product that needs multiple image upload capabilities. I have thus created a separate model called Images to link back to Product with a ForeignKey relationship. I need some help to write a function that can loop over each uploaded image and create the foreign key relationship back to Product. What follows is a simplified model: class Product(models.Model): title = models.Charfield() description = models.TextField() ... ...and the Images model: class Images(model.Model): image = models.ImageField() product = models.ForeignKey(Product) Simple forms for them both (Images omitted but it's the same idea: class ProductCreateForm(ModelForm): class Meta: model = Product fields = '__all__' Also, the template includes enctype="multipart/form-data" to allow multiple upload selection. I would like to know create a view function to loop over the uploads and create the ForeignKey relationship. Something like this: def CreateProduct(request): if request.method = 'POST' ... (now this is where I just have no idea how to write this. I'm very new to Django and programming/scripting in general.) -
How to track steps in a linear workflow
I have a model for a Task in a workflow. The task has a ManyToMany field that allows users to add approvers who can approve each step in the task. class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) I am using an OrderedModel as an intermediary model to keep track of the order of each approval, with the intention to pass the Task linearly from one approver to the next as they sign off the Task: class TaskStep(OrderedModel): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL ) task = models.ForeignKey(FlowTask, null=True, on_delete=models.SET_NULL) order_with_respect_to = 'task' status = models.BooleanField() What's the simplest way to keep track of which TaskStep the Task approval is on? -
Got AttributeError when attempting to get a value for field when using values_list
I have encountered the error which I cannot solve after I read the django doc and django-rest-framework doc,even I read all the related question on stackoverflow,I still cannot solve it. the full error message is as following: AttributeError at /api/v1/task/target/subdomain/get_by_target/ Got AttributeError when attempting to get a value for field `target_id` on serializer `TargetSubdomainSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance. Original exception text was: 'tuple' object has no attribute 'target_id'. I want to get the distinct result on my table, so I use django filter and distinct, when I just use the filter, the code runs correctly, but when I use filter and values_list at the same time, it runs into error. the TargetSubdomain model is as following: class TargetSubdomain(models.Model): target_id = models.IntegerField(help_text='目标ID') domain = models.CharField(max_length=200, help_text='域名') source = models.CharField(max_length=20, help_text='子域名来源') created_at = models.BigIntegerField(default=0, help_text='创建时间') updated_at = models.BigIntegerField(default=0, help_text='更新时间') def save(self, **kwargs): if not self.id: self.created_at = int(time.time()) self.updated_at = int(time.time()) super(TargetSubdomain, self).save() class Meta: db_table = 'nw_target_subdomain' the TargetSubdomainSerializer is as following: class TargetSubdomainSerializer(serializers.ModelSerializer): class Meta: model = TargetSubdomain fields = '__all__' the TargetSubdomainViewSet is as following: class TargetSubdomainViewSet(viewsets.ModelViewSet): queryset = TargetSubdomain.objects.all().order_by('-id') serializer_class = TargetSubdomainSerializer @action(methods=['GET'], detail=False, … -
Django annotate a queryset with objects
I have models named Product, Material, and Tag. Each product has many materials, each material has many tags. Each product has tags, the tags are all distinct tags of the product's materials. I would like to pass Product queryset with tags attribute to django rest serializer without N+1 problem. I used subquery, but it only return a row and a column. I tried to operate it at python level, but it produces N+1 problem, and even if I somehow manage to avoid N+1 problem it will be slower than using ORM because it's python. I tried to add tags column to Product, and update it everytime the material and/or material's tags changed, it works, but adding more complexities to my code for something that could be so simple class Product(models.Model): name = models.CharField(max_length=255) class Material(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, related_name='materials', on_delete=models.CASCADE) class Tag(models.Model): name = models.CharField(max_length=255) material = models.ForeignKey(Material, related_name='tags', on_delete=models.CASCADE) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ProductSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = Product fields = '__all__' I expect to have queryset that can be passed to ProductSerializer without N+1 problem and without using signals. -
How to automatically update view once the database is updated in django?
I have a problem in which I have to show data entered into a database without having to press any button or doing anything. I am creating an app for a hospital, it has two views, one for a doctor and one for a patient. I want as soon as the patient enters his symptoms, it shows up on doctor immediately without having to press any button. I have no idea how to do this. Any help would be appreciated. Thanks in advance -
Django - Model property methods vs signals for field calculation
I have a model that does some basic aggregation of some values on a m2m field. I can achieve this by doing the calculation in a Model method, in which case the results would be stored in a model attribute. Or I can do the calculation in a pre_save signal function, and then the result would be stored in a model field. I want to know are there are any cons to using signals? or in which cases it would be better to use a model property method? I understand that the calculations will run at different times, with the signal function running when save() is called, and the model method running automatically. class CartItem(models.Model): name = models.CharField(max_length=100) total_price = models.DecimalField(max_digits=10, decimal_places=2) ##Model Method Approach @property def price(self): return self.extras.all().aggregate(Sum('price'))['price__sum'] ##Signal Approach def set_total_price(sender, instance, **kwargs): instance.total_price= instance.extras.all().aggregate(Sum('price'))['price__sum'] pre_save.connect(set_total_price, sender=CartItem) The signal approach has the benefit of resulting in a model field rather than a model attribute, which makes it easier use in Parent or related models for aggregation. So why would one ever use a Model method over a model signal? -
How to display data from mysql 8 in django 2.1.5?
I am trying to display some data from mysql 8 in Django 2.1. I created a database db1 and inserted some data into it and tested. All works perfectly. Then I add this piece of code into views.py: @login_required def population_list(request): names = Population.objects.all() return render_to_response('images/image/list.html', {'names': names}) inside models.py I have: class Population(models.Model): name = models.CharField(max_length=20) population = models.BigIntegerField() year = models.DateField() inside list.html I add this code: <div id="population-list"> <h3>Names here... </h3> <tbody> <tr> {% for name in names %} <td>{{ name.name }}</td> {% endfor %} </tr> </tbody> However I only see: "Names here..." text, nothing else. What is my mistake? Why I don't see the database content? How can I debug it? -
Slow server response times from Django app on Heroku
Ive grown quite stuck trying to figure out why my production Django application (E-commerce) has trouble with slow server response times on certain pages. The pages affected has quite some database requests on it because of complicated relationships between Cars and Products i.e some chargers only work with some cars and some chargers span multiple categories etc etc. The application is hosted on Heroku with a “Hobby Basic Postgres database” and "1 Professional Standard-1X dyno”. For some reason the server takes between 7-10 seconds to respond to a request on the live server. Locally everything works super smooth and fast with responses of maximum 0.5s on all pages. Has anyone had this trouble before and has any idea of how to fix it? Ive tried scaling the database and dynos without the response being any quicker.. I’ll attach som screenshots of logs and speed tests. And affected code Models, Views and Template. Heroku Metrics: https://screenshot.net/z7r4jid Heroku Logs: https://screenshot.net/ndv7ot8 Console Debugger: https://screenshot.net/m4310t3 Template: https://dpaste.de/tjEi View: https://dpaste.de/Bdut Models: https://dpaste.de/fNQY The page is: https://www.evify.se The pages with slow server response is all the car detail pages. Example: https://www.evify.se/laddboxar/jaguar-i-pace/ Would be extremely grateful if anyone has any idea, I’ve looked everywhere without finding any … -
How to convert duration into '%H:%M:%S.%f' time format, not in days
I need to convert days to hours, minutes, seconds def get_working_hours(self, obj): return datetime.strptime(str(obj.working_hours), '%H:%M:%S.%f').time() ValueError: time data '1 day, 7:06:38.340741' does not match format '%H:%M:%S.%f' -
How to set a dynamic choices tuple based on other model field values
I have a model with 2 fields: A ManyToMany field that contains a number of users who can approve a task (approvers); and An IntegerField that contains a choices tuple to return the current step of the task (step). class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) step = IntegerField( choices=STEP_CHOICES ) I want to allow users to define the number of approvers, but also dynamically create a choice for each approver in step. How can I programmatically define the choices in my tuple to cover the number of users in the ManyToMany field? For example, if there are 3 approvers, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), ) If there were 5 users, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), (4, 'Step 4'), (5, 'Step 5'), ) -
Getting InvalidRequestError in stripe
I get following error: File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\stripe\api_requestor.py", line 151, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_jQhnYD0I72zs8l: No such customer: cus_Fi7AiNV2Cpdkdi My code: def payment_method_create_view(request): print("Ajax payment") if request.method == "POST" and request.is_ajax(): billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if not billing_profile: return HttpResponse({"message": "Cannot find this user "}, status=401) token = request.POST.get("token") print("token is:", token) if token is not None: new_card_obj = Card.objects.add_new(billing_profile, token) print(new_card_obj) return JsonResponse({"message": "Your card was added."}) return HttpResponse("error", status=401) class CardManager(models.Manager): def all(self, *args, **kwargs): return self.get_queryset().filter(active=True) def add_new(self, billing_profile, token): if token: customer = stripe.Customer.retrieve(billing_profile.customer_id) stripe_card_response = customer.sources.create(source=token) new_card = self.model( billing_profile = billing_profile, stripe_id = stripe_card_response.id, brand = stripe_card_response.brand, country = stripe_card_response.country, exp_month = stripe_card_response.exp_month, exp_year = stripe_card_response.exp_year, last4 = stripe_card_response.last4 ) new_card.save() return new_card return None class Card(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) brand = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=20, null=True, blank=True) exp_month = models.IntegerField(null=True, blank=True) exp_year = models.IntegerField(null=True, blank=True) last4 = models.CharField(max_length=4, null=True, blank=True) default = models.BooleanField(default=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CardManager()