Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting one-to-many relationship data both ways in Django REST Framework
I'm using Django REST Framework to create the following endpoints: /tenants/ ➞ lists all tenants and includes in the json response the attributes of the Building model they live in. /buildings/ ➞ lists all buildings and includes in the json response the attributes of the Tenants that live in them. My models are: class Building(models.Model): address = models.CharField(max_length = 200) zipcode = models.IntegerField() city = models.CharField(max_length = 100) class Tenant(models.Model): fname = models.CharField(max_length = 200) lname = models.CharField(max_length = 200) building = models.ForeignKey(Building, related_name = 'tenants', on_delete = models.CASCADE) My serializers look like so: class BuildingSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['id', 'address', 'zipcode', 'city'] class TenantSerializer(serializers.HyperlinkedModelSerializer): building = BuildingSerializer() class Meta: model = Tenant fields = ['id', 'fname', 'lname', 'building'] The /tenants/ endpoint works just fine, but I have no idea on how to include the tenants' data in the /buildings/ response. Could anyone give me a clue on this? -
Shared File Lock Python
Is there a way to implement a "Shared File Lock"? Let me explain the concept: A file lock called: GroupOfFeatures, within this lock I want a group of features to be able to run in parallel. So at the same exact time: CPU-1: Locks. Do the work. Unlocks. CPU-2 Locks. Do the work. Unlocks. The problem with a normal file lock is that on the case of CPU-2 before it unlocks it will be already unlocked by CPU-1. Here is the specific real world example. On a microservices architecture, I have 3 services: Costs, Sales and Administration. Costs - keep track of costs. Sales - keep track of sales. Administration - receives both by queues messaging and saves everything in one model/table. The problem that I have is that if I save costs and sales at the same time, it blocks the DB/deadlocks/etc. If I queue them in a single thread and process one first and the other after, then it is too slow. So the solution would be to allow N threads to import either costs or sales into administration, but not both at the same time. Something like this would happen: 10:00am - Receive costs for 1 account … -
I'm trying to deploy an open source app on kubernetes, but the authentication doesn't work when deployed on google cloud
I'm a total beginner, I haven't done anything like this before, so I'm sorry if this is a stupid question, but I couldn't find anything related. I'm trying to deploy a voting app on google cloud on kubernetes. The problem is that the app has almost non-existent documentation, so I don't know if I'm doing something wrong. When I host the app locally, everything works as expected, but when I deployed it on kubernetes when I try to log in, the server throws a 403. Does anyone know what could cause it? Here's the screenshot of the log 1 -
How to write a python calendar function that calls only one week instead of a whole month
I have a question if I am able to write a function that instead of displaying days for a given month would display only a particular week in the month i have something like this in my utils.py file def formatweek(self, theweek, events, ): week= '' for d, weekday in theweek: week += self.formatday(d, events, ) print() return f'<tr> {week} </tr>' def formatmonth(self, withyear=True, ): for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events, )}\n' return cal I would appreciate any hints -
How to save excel / csv / dataframe for Django use?
I have a django model with relevant code as follows (question below the code): class Equity(models.Model): equity_name = models.CharField(max_length=255) geography_choices = [('Africa', 'Africa'), ('Asia', 'Asia'), ('Australia', 'Australia'), ('Europe', 'Europe'), ('North America', 'North America'), ('South America', 'South America')] geography = models.CharField(max_length=255, choices=geography_choices, default='North America') sector_choices = [('Communication Services', 'Communication Services'), ('Consumer Discretionary', 'Consumer Discretionary'), ('Consumer Staples', 'Consumer Staples'), ('Energy', 'Energy'), ('Financials', 'Financials'), ('Health Care', 'Health Care'), ('Industrials', 'Industrials'), ('Information Technology', 'Information Technology'), ('Materials', 'Materials'), ('Real Estate', 'Real Estate'), ('Utilities', 'Utilities')] sector = models.CharField(max_length=255, choices=sector_choices, default='Communication Services') def fundamental_list(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) return l_fund class Article(models.Model): ticker = models.CharField(max_length=5, null=True) source = models.CharField(max_length=50, choices=source_choices, default='Argus') score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] fundamental_score = models.FloatField(choices=score_choices, default=0) sentiment_score = models.FloatField(choices=score_choices, default=0) #Fields for the read-through effect of a news item on related companies. read_through_choices = [(-1, 'Competitive'), (0, 'No Effect'), (1, 'Industry-Wide')] read_through = models.IntegerField(choices=read_through_choices, default=0) #here we attempt the foreign key method for equities possibly??? equity = models.ForeignKey(Equity, … -
Display a nice Django Crispy Forms Validation Error Message
I am trying to get this tutorial to working, but didn't manage to do so yet. My views.py def BlogCreateView(request): context = {} if request.method == 'POST': # create a form instance and populate it with data from the request: form = MessageForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: form.save() context['form']= form return render(request, 'post_new.html', context) else: form = MessageForm() return render(request, 'post_new.html', {'form': form}) My forms.py from django import forms from .models import Post from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column class MessageForm(forms.Form): title = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = True super().__init__(*args, **kwargs) self.helper.form_method = 'POST' self.helper.layout = Layout( Row('title', css_class='form-control-lg'), ) My post_edit.html {% extends 'base.html' %} {% block content %} <h1>Edit Post</h1> <form class="blau" action="" method="post">{% csrf_token %} {{ form.title }} <input type="submit" name="" value="Update"> </form> {% endblock content %} The form seems to work, but I cannot modify/overwrite the pop-up alert which reminds the user to enter the correcht input. Is this even the right way to achieve this? I am open for any help. Thank you a … -
TemplateDoesNotExist at /en/user/login/ when tried to visit the login url in Django 2.2
I am upgrading a Django application from 1.11 to to 2.2. I have completed all the migrations and everything but I am facing this error constantly django.template.exceptions.TemplateDoesNotExist: registration/login.html. I am still currently learning Django apologies in advance if I am missing something stupidly simple. I have attached the error message picture here and the files that might be relevant to this error message. Just for clarification in my settings.py I have the following under TEMPLATES: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages", "django.template.context_processors.request", ] } } ] Here are the othert files that might help debugging: urls.py from django.conf.urls import url, include from django.urls import reverse_lazy from userApp import views from django.contrib.auth import views as django_contrib_auth_views from django.contrib.auth.views import LoginView urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.profile, name='profile'), url(r'^login/$', views.rate_limit_login, name='login'), url(r'^rate_limited/$', views.rate_limited, name='rate_limited'), url(r'^logout/$', django_contrib_auth_views.LogoutView, {'template_name': 'userApp/logged_out.html', 'next_page': '/'}, name='logout'), url(r'^password_change/$', django_contrib_auth_views.PasswordChangeView, {'template_name': 'userApp/password_change_form.html', 'post_change_redirect': reverse_lazy('userApp:password_change_done')}, name='password_change'), url(r'^password_change/done/$', django_contrib_auth_views.PasswordChangeDoneView, {'template_name': 'userApp/password_change_done.html'}, name='password_change_done'), url(r'^password_reset/$', django_contrib_auth_views.PasswordResetView, {'template_name': 'userApp/password_reset_form.html', 'email_template_name': 'userApp/password_reset_email.html', 'post_reset_redirect': reverse_lazy('userApp:password_reset_done')}, name='password_reset'), url(r'^password_reset/done/$', django_contrib_auth_views.PasswordResetDoneView, {'template_name': 'userApp/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', django_contrib_auth_views.PasswordResetConfirmView, { 'template_name': 'userApp/password_reset_confirm.html', 'post_reset_redirect': reverse_lazy('userApp:password_reset_complete')}, name='password_reset_confirm'), url(r'^reset/done/$', django_contrib_auth_views.PasswordResetCompleteView, {'template_name': 'userApp/password_reset_complete.html'}, name='password_reset_complete'), views.py from … -
Django admin prepopulate field based on the value from an save override in models
This problem has been frustrating me because I feel like I have all the pieces but just can't put it together. I'm pretty new to Django and web dev in general and so far it's mostly been pretty smooth. I'm building a simple form app where every form is going to have a unique URL via a randomly generated slug, and each form expires after about a week. Model Token has two fields, 1) tokenid, which is the random slug as well as the pk, and 2) a url field that is created using that slug. I also overrode the save method to get admin to spit out a new slug every time Add gets clicked. My goal was to have the URL field in Django admin to be prepopulated so it's easy for the person generating the form to be able to click, copy and paste. These forms are only going to be sent out after a face-to-face process so I'm not concerned about scalability. I'm aware that once the fields are saved to db, the full URL will appear in the URL field, but it seems like an extra step for managers to make mistakes. #Models.py def get_random_string(): … -
webscoket fails to connect after few successful connections in react application
I am using django channels to implement real time updates to react frontend. But the problem is after few successful connections from frontend with websocket, the connection drops and gives two different kind of error in firefox (can't establish connection to ws://url) and chrome (failed to connect due to unknown reason). But the connection works for the first few times but with time this error occurs. Below is the socket connection code in client-side. export default function Comment(props) { const socket = new WebSocket(`${WEBSOCKETURLCOMMENT}${props.reqID}/`); const socketLike = new WebSocket(`${WEBSOCKETURLLIKE}${props.reqID}/`); ........... const socketOpen = () => { console.log('Socket opened', 'mrlog'); } const syncWebsocketData = (e) => { try { let recData = JSON.parse(e.data); if (recData?.c) { setComm(recData.c[props.index].comments) setLoading(false) } } catch (error) { console.log('Error to parse'); } } useEffect(() => { socket.addEventListener('open', socketOpen) socketLike.addEventListener('open', socketOpen) socketLike.addEventListener('message', syncWebsocketData) socket.addEventListener('message', syncWebsocketData) return function cleanup(){ socketLike.removeEventListener('open', socketOpen) socket.removeEventListener('open', socketOpen) socketLike.removeEventListener('message', syncWebsocketData) socket.removeEventListener('message', syncWebsocketData) socket.close() socketLike.close() } }, []) ....... It works fine at first but after some udpates it can' connect anymore. -
Django query on event list: finding most recent events
I have a django model that collects events. It looks roughly like this: class Events(models.Model): class EventType(models.TextChoices): OPEN = ... CLOSE = ... OTHER = ... READ = ... user = models.ForeignKey(User, on_delete=models.CASCADE) box = models.ForeignKey(Box, on_delete=models.CASCADE) event_timestamp = models.DateTimeField(default=django.utils.timezone.now) event_type = models.CharField(max_length=6, choices=EventType.choices) Events occur when users do things with boxes. I have four very related queries I want to do, and I'm not at all sure how to do this without resorting to SQL, which usually isn't the right solution with django. For box B and user U, is the user most recently open or closed for this box? For Box B, how many users are in an open state? For Box B, I'd like to plot day by day how many users are open, so I'd like to get a grouped array of users who opened and closed on each day. I'd like a table over all boxes of how many users are in an open state. For example, in SQL these would have forms something like this (not tested code, I'm hoping it's easier to use django's query language): -- 1 SELECT event_type FROM Events WHERE event_type in ('OPEN', 'CLOSE') AND user = U HAVING max(event_timestamp); … -
Why does COUNT(*) in my SQL query return several values? How to get one single value for total rows found?
I have a Django class getting some order data from a PostreSQL database. I need to get the number of rows found in a query. Trying to get the found rows count from the following query with COUNT(*): sql = """SELECT COUNT(*) FROM mbraindb.sysmanufacturingorders o LEFT JOIN mbraindb.sysmanufacturingorderrows r ON o.manufacturingorderID = r.manufacturingorderID AND r.Enabled <> 0 left join ( select si.salesitemid, si.externalsalesid, p.productarticlenumber, p.productname from mbarticlemanagement.syssalesitems si join mbarticlemanagement.syssalesitemproducts ip on si.salesitemid = ip.salesitemid join mbarticlemanagement.sysproducts p on ip.tableid = p.productid group by si.salesitemid, si.externalsalesid, p.productarticlenumber, p.productname ) as salesitems on r.salesitemid = salesitems.salesitemid left join ( select r.manufacturingorderid, r.quantity, p.productarticlenumber, p.productname from mbraindb.sysmanufacturingorderrows r join mbarticlemanagement.sysproducts p on r.productid = p.productid group by r.manufacturingorderrowid, r.manufacturingorderid, r.quantity, p.productarticlenumber, p.productname order by r.manufacturingorderrowid asc ) as products on o.manufacturingorderid = products.manufacturingorderid %s GROUP BY o.manufacturingorderID, o.manufacturingorderCustomer, o.manufacturingorderOrgOrderID, o.Enabled, o.manufacturingorderDate, o.manufacturingorderFinishdate, o.manufacturingorderStatus, o.manufacturingorderIdentifier, coalesce(salesitems.externalsalesid, ''), coalesce(salesitems.salesitemid, 0) ORDER BY o.manufacturingorderFinishdate ASC, o.manufacturingorderOrgOrderID ASC, o.manufacturingorderID ASC;""" % (sqlwhere) When I print the result from the query above, I get a lot of data: [RealDictRow([('count', 256)]), RealDictRow([('count', 4)]), RealDictRow([('count', 32)]), RealDictRow([('count', 2)]), RealDictRow([('count', 32)]), RealDictRow([('count', 2)]), RealDictRow([('count', 9)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 1)]), RealDictRow([('count', 4)]), RealDictRow([('count', 4)]), RealDictRow([('count', 4)]), RealDictRow([('count', … -
Django get min and max value from PostgreSQL specific ArrayField holding IntegerField(s)
I have an ArrayField in my model holding IntegerFields. I'm looking for the best way in which I can extract the smallest and the biggest integer out of this array. The Django documentation doesn't give examples of something similar and I wonder if the right way would be finding out how and if I can use aggregation function on this ArrayField or if I can cast this to normal python list of integers somehow and use the build in min, max functions? Any suggestions for performing this would be helpful. Examples even more. -
How to handle Django model objects being saved concurrently?
Given I have the following Django model: class Details(models.Model): id = models.BigAutoField(primary_key=True) data = models.TextField() more_data = models.TextField() Now I have a celery task which is Updating data field of the model and rest API calls updating more_data field. Currently I have written within celery functions as: model_obj.data = data model_obj.save() and function called from API call as: model_obj.more_data = more_data model_obj.save() Now since the both functions can execute simultaneously for given id, it is possible that data might not be saved correctly. So, if I update above functions to : model_obj.data = data model_obj.save(update_fields=[data]) and model_obj.more_data = more_data model_obj.save(update_fields=[more_data]) will it work fine ? -
Retrieve Auth Code From URL Python \ Django
Devs, Im working with the SmartSheet API and it requires me to go out and pull a authroization code to establish a token for a session. Im able to to redirect to their link, than be redirected to my app in Django with the AUTH code in the URL. Here is my setup so far. Here is my View @login_required def SmartSheetAPI(request): record = APIInformation.objects.filter(api_name="SmartSheet").first() if record == None: print('Authorization Token Doesn't Exist In DB, Fetching New Token!') return redirect("https://app.smartsheet.com/b/authorize?response_type=code&client_id={}&scope=READ_SHEETS%20WRITE_SHEETS&state=MY_STATE".format(client_id)) So If you visit the following page on my app, it checks if a auth token exists in the database, if it doesnt exist than go out to the redirect and authorize it. I get dumped back to my app with the URL code in the URL to this view. The example is this on the return http://127.0.0.1:8000/api/smartsheet/smartsheetapiauth?code=123456789&expires_in=599905&state=MY_STATE I need to extract code. def SmartSheetAPIAuth(request): return render(request, 'smartsheetapiauth.html') -
DRF - How to pass model object instance from view to my serializer data?
I'd like to append an object field to my serialized data in internal value . How can I reference that object directly? In my view, I use get_object_or_404 , I tried passing the kwargs, args to my serializer but that didn't work. serializer.py class StringArrayField(serializers.ListField): def to_representation(self, obj): obj = super().to_representation(obj) return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") return super().to_internal_value(data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) view.py class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer queryset = Bucket.objects.all() def get_object(self, queryset=queryset, **kwargs): item = self.kwargs.get('slug') return get_object_or_404(Bucket, slug=item) -
I have a problem connecting Django and SQL Server
Error - "django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3'" enter image description here -
Django objects.filter returning nothing but objects.get working
I have a simple Django project which is going to be used as an employment website. I want to render the logged-in user skills to their user profile by filtering. The objects.filter code wont return data but the objects.get returns the correct data. I want to iterate so .get is not suitable. Models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) email = models.EmailField(max_length=200, blank=True) phone_number = models.CharField(max_length=200, blank=True) tag = models.TextField(max_length=200, blank=True) sector = models.CharField(max_length=200, blank=True) avatar = models.ImageField(default='avatar.jpg', upload_to='avatar_pics') county = models.CharField(max_length=200, blank=True) slug = models.SlugField(unique=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=200, blank=True) def __str__(self): return f"{self.user.username}-{self.created}" views.py @login_required def my_employee_view(request): employee = Employee.objects.get(user=request.user) skills = Skill.objects.filter(user=request.user) form = EmployeeModelForm(request.POST or None, request.FILES or None, instance=employee) confirm = False if request.method == 'POST': if form.is_valid(): form.save() confirm = True context = { 'employee': employee, 'form': form, 'confirm': confirm, 'skills': skills, } return render(request, 'account/employee.html', context) HTML <table class="table table-sm"> <tr> <th>Skill</th> <th>Level</th> <th>Years of Experience</th> </tr> {% for skill in skills %} <tr> <td>{{skills.tag}}</td> <td>{{skills.level}}</td> <td>{{skills.years_of}}</td> </tr> {% endfor %} -
How to visualize values in parent fields when adding new child in Django admin? [Django]
I have two models, GlobalRule and LocalRule. When I am adding a new LocalRule in Django admin I want to visualize the values of some of the fields in the corresponding GlobalRule object. The user needs this information in order to define the local rule. Is there a way for me to display the value of global_rule.event_a, global_rule.event_b,global_rule.rule_a_b_man, global_rule.a_man, global_rule.b_man as readable but not editable fields when adding a new LocalRule in Django admin? models.py from django.db import models event_choices= ['Sales order created','PO Sent','PO created','Goods Issue','STO Packing complete','Proof of delivery','Shipment ended','Delivery (Stock Transfer)','Sales order released','Goods Receipt','Goods Issue for Stock Transfer','Invoice Receipt','Order Packing complete','Delivery created','Shipment created','Sales order item created','STO created'] # Create your models here. class GlobalRule(models.Model): event_choices_l = [(str(i), event_choices[i-1]) for i in range(1,len(event_choices))] rule_choices = [('1','No Rule'),('2','Rule'),('3','Anti-Rule')] event_a = models.CharField('Event A',max_length = 200,db_column='Event A') event_b = models.CharField('Event B',max_length = 200,db_column='Event B') rule_a_b_man = models.CharField('Manual A -> B | AnB',max_length = 200,db_column='Manual A -> B | AnB',null=True) rule_a_man = models.CharField('Manual A -> B | A',max_length = 200,db_column='Manual A -> B | A',null=True) rule_b_man = models.CharField('Manual A -> B | B',max_length = 200,db_column='Manual A -> B | B',null=True) validated = models.CharField('Validated as',max_length = 200,db_column='Validated Rule',null=True) rule_a_b_gen = models.CharField('Generated A -> B … -
Radio input type in Django forms
I am making a quiz app and I'm trying to make 4 answers to choose from but it doesn't even get rendered in html or show error so maybe you can tell me what should I fix or maybe suggest a different approach. forms: class AnswerForm(forms.Form): CHOICES = [('1', 'First Answer'), ('2', ('Second answer')), ('3', ('Third answer')), ('4', ('Fourth answer')), ] answer = forms.CharField(label='Choose the correct answer:', widget=forms.RadioSelect(choices=CHOICES)) views: def answers(request): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = form.cleaned_data['answer'] else: form = AnswerForm() return render(request, 'pages/questions.html', {'form': form}) html: {% block content %} {% for Questions in question_list %} <h1>{{ Questions.title }}</h1> <form method="post" action=""> {% csrf_token %} {{ form }} </form> {% endfor %} {% endblock content %} -
Django + nginx + uwsgi = 504 Gateway Time-out
Below is my configuration for Nginx, and uwsgi. uWSGI works fine, I can access it directly on port 8080 but from Nginx it is not able to access the upstream - times out with 504. I am trying to run on TLS 443. How can I solve this issue? 504 Gateway Time-out nginx/1.14.0 (Ubuntu) nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; # SSL Settings ## ssl_protocols TLSv1.2; ssl_prefer_server_ciphers on; upstream uwsgicluster { server 0.0.0.0:8080; } ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } mywebsite.com conf file server { # listen 80; # listen [::]:80; listen 443; listen [::]:443; ssl on; ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; # root /data/mywebsite.com/www; # index index.html index.htm index.nginx-debian.html; server_name mywebsite.com; location / { include uwsgi_params; uwsgi_pass uwsgicluster; # uwsgi_param UWSGI_SCRIPT django_wsgi; # proxy_redirect off; # proxy_set_header Host $host; # proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header X-Forwarded-Host $server_name; try_files $uri $uri/ =404; } } uwsgi ini [uwsgi] master … -
Django queryset how to get one result using slicing
I have to fetch the usernames of my authors' posts Here the code: def counter(request): authors = Post.objects.values_list('author', 'title') authors_id = Post.objects.values_list('author') authors_name = User.objects.get(id=authors_id) context = {'authors':authors, 'authors_name':authors_name} return render(request, 'account/counter.html', {'authors': authors}) Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using slicing. How can I slice the queryset's list? -
Would it be a bad idea to use Django template tags to add context to a template? (Trying to imitate ease of Vue components)
One of the problems I have with Django (at least how I've learned to use it so far) is that there's not a great way to build components like in Vue. In my templates I have been using {% include %} statements to include more modular pieces of template code/components. the problem, though, is that if I use a piece of data in the component then it needs to be passed to every single view that I use it in. For example, suppose I have this template: <p>I'm a template!</p> {% include './components/weather.html' %} and then in ./components/weather.html: <p>The weather is {{ weather.status }} today.</p> Now, in any view that I want to use weather.html in, I will need to pass in 'weather' as a context variable. It would be better if I could just include a template in another template and know that it will automatically make the database requests needed to populate the context it needs. Is there any reason I can't use a tag for this? Like instead of {{ weather.status }} use {% weather %} and then in template tags something like: @register.simple_tag def weather(): return weather.get_status() Is this going to open up some vulnerability I … -
Syntax error when writing {% load static %} when trying to load an image
Hello so im doing a little project with reactjs and django and I need to load a static image from a component, and what I'm trying to do is in the render method add {% load static %}, but it is giving me an error and I cant figure out why because I have it written in my main index.html and it gives me no errors!! Here is the code: import React, { Component } from 'react'; export default class TopBar extends Component { constructor(props) { super(props); } register(){ var x = document.getElementById("login"); var y = document.getElementById("register"); var z = document.getElementById("joinBtn"); x.style.left = "-400px"; y.style.left = "50px"; z.style.left = "110px"; } login(){ console.log('I was triggered during render') var x = document.getElementById("login"); var y = document.getElementById("register"); var z = document.getElementById("joinBtn"); x.style.left = "50px"; y.style.left = "450px"; z.style.left = "0px"; } render(){ return ( <div class="hero"> <div class="form-box"> <div class="button-box"> <div id="joinBtn"></div> <button type="button" class="toggle-btn" onClick={this.login}>Log In</button> <button type="button" class="toggle-btn" onClick={this.register}>Register</button> </div> <div class="social-icons"> {% load static %} <img src="{% static 'images/fb.png' %}" alt ="fb"/> <img src="{% static 'images/google.png' %}" alt ="gg"/> <img src="{% static 'images/tt.png' %}" alt ="tt"/> </div> <form id = "login" class="input-group"> <input type="e-mail" class="input-field" placeholder="E-mail" required/> <input type="password" … -
Using Django for communication between APIS?
I am new in the world of programming. I know a little python and i am learning Django. I understand that Django is very useful for webpages backend. But I don't just want a website or an webapp. What I want is to centralize all the operations of my company by communicating through APIS different applications such as CRM (costumer relationship management), SQL database, bulk mail software, etc. For example, I want that when I perform an action in my CRM software (sales), it activates a scrapy script that I am creating, which scrapes certain pages, and then stores information in my SQL database. Can I centralize all of this through Django as if it were a central base that connects all my scripts and the communications between APIS? -
Group By in Query Django, Sum Value for a field, by the group field
I would like to get a Query in django, grouping by a field1, and sum a field2 integer, with the register that have coincidence with field2. fields_list = Whatever.objects.filter(whatever=whatever).order_by('field1').annotate(field1).agregate(Sum(field2)) And the list that I want to get is: [ {'field1':samevaluefield1,'field2':sum(Sum of field2 with value samevaluefield1)}, {'field1':othervaluefield1,'field2':sum(Sum of field2 with value othervaluefield1)}, {'field1':other2valuefield1,'field2':sum(Sum of field2 with value other2valuefield1)} ]