Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgresql - "ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252""
So I was querying on my Heroku server with this query // Command to get into postgres heroku pg:psql // Query SELECT * FROM cheers_post; then I get this error ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252" I don't know what character 0xf0 0x9f 0x98 0x84 is in UTF8. This error isn't super explicit so I'm not really sure what the issue is or how to fix it. Anyone experience this? Something interesting is when I query the cheers_post table via a Django API endpoint it returns Post.DoesNotExist error. -
Django & Celery: no such table
I am attempting to create a couple tasks with Celery that post data to a Django model, I have everything functioning except for some reason the Celery tasks are not able to see the table even though it exists in the DB and Django can post data to it. This is happening with PostgreSQL, it works when using SQLite3. Has anyone encountered this type of issue and how were you able to solve it? tasks.py -------- # tasks from __future__ import absolute_import, unicode_literals from celery import Celery from celery import app, shared_task # scraping import requests from bs4 import BeautifulSoup import json from datetime import datetime import lxml from rss_feed_scraper.models import PressReleases # logging from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @shared_task(serializer='json') def save_function(article_list): for article in article_list: try: PressReleases.objects.create( title=article['title'], description=article['description'], link=article['link'], image_url=article['image_url'], published=article['published'], source=article['source'] ) except Exception as e: print('failed at inserting article') print(e) break @shared_task def prnewswire_rss(): article_list = [] try: print('Starting the scraping tool') r = requests.get('https://www.prnewswire.com/rss/all-news-releases-from-PR-newswire-news.rss') soup = BeautifulSoup(r.content, features='lxml') articles = soup.findAll('item') for a in articles: title = a.find('title').text description = a.find('description').text # Get Link link = str(a) i = link.find("<link/>") j = link.find("<guid") media_content = a.find('media:content') image_url = None if media_content: image_url = … -
Iterable list in Django HTML?
I want to use bootstrap to make a carousel using D.R.Y. methods. my idea (and it may not even be feasible) is to have a list or dictionary and cycle through image locations. Here's what I've written so far. <div class="carousel-inner"> {% with images = ['gyro.jpeg', 'pizza.jpeg', 'soup.jpeg', 'brocpizza.jpeg' ,'dessert.jpeg'] %} {% for image in images %} <div class="carousel-item active" data-bs-interval="10000" style="background-image:url({%static {image}%})"> <div class='container'> <section class='time'> <h3><strong>HOURS</strong></h3> <h3><strong>Monday - Saturday</strong></h3> <h3><strong>11 a.m. - 9 p.m.</strong></h3> </section> <div class='headline'> <h1>Title</h1> <h2>Menu</h2> </div> <section class='address'> <h3> <strong>NAME</strong> </h3> <h4>Phone</h4> <h4>Address</h4> <h4>City</h4> </section> </div> </div> {% endfor %} {% endwith %}``` -
Getting a 400 Bad Request Error After GCP App Engine Deployment of Django App
So I have a Django App which has its views connect to a BigQuery where it would pull data from. I want to deploy the web app to a GCP App Engine and have followed the instructions that are stated on GCP App Engine Website. I have successfully created the SQL instances and can run the web app locally. I deploy the app using gcloud app deploy, it says that it is successfully deployed. When I try to open the web app on the browser gcloud app browse, it just returns me a 400 Bad Request Error. I'm kinda lost as I don't know what I'm missing during deployment plus I don't know which part of my code I should be putting on here so do comment below what I need to be posting in order to guide you to help me and I will update the post. Another thing is that, since I'm pulling data from the BigQuery, locally I have this JSON file which has all the credentials needed for the BigQuery API and I access it in the settings.py as such: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/Users/user/Documents/website/bq-api.json' The thing is I'm wondering if I should be including this inside the … -
Django Filters 'str' object has no attribute '_meta'
I am creating an page that allows the user to filter a dataset, hit search, and see the results update below. I am getting the following attribute error: 'str' object has no attribute '_meta' and I cannot figure out why this is happening. Any help is appreciated views.py: def week(request): #orders = Pick.objects.get(id=pk_test) orders = Pick.objects.all() #orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'myFilter':myFilter} return render(request, 'app/filter_list.html',context) pick_list.html: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <ul> <table class="table table-hover" id="table-ajax" style="background-color: white;"> <thead style="background-color: #de5246; color:white; border-bottom:white"> <tr> {% comment %} <th></th> {% endcomment %} <th style="width: 50px; text-align: center;"></th> <th>{{ object_list|verbose_name:'field:name' }}</th> <th>{{ object_list|verbose_name:'field:hometown' }}</th> <th>{{ object_list|verbose_name:'field:occupation' }}</th> <th>{{ object_list|verbose_name:'field:age' }}</th> <th>Progress</th> <th style="width: 160px; text-align: center;">Rank</th> </tr> </thead> <tbody class="order" data-url="{% url 'cms:reorder' … -
Processing Tiff and saving to Django ImageField
The program I'm trying to write takes in a multipage Tif file/stack and processes it by: Changing tiffile to numpy arrays Taking numpy arrays and turns them into tensors Processes tensors and turns them back to numpy arrays Finally takes said numpy arrays and turns it back into a tiff stack. My Code: models.py : from django.db import models import numpy as np import tensorflow as tf from PIL import Image from django.core.files.base import ContentFile from django.core.files.uploadedfile import InMemoryUploadedFile # Create your models here. class TiffModel(models.Model): name = models.CharField(max_length=450) image = models.ImageField(blank = True, null = True) def __str__(self): return self.name def img (self): return self.image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) images = [] tensors = [] processedArrays = [] tiffStack = [] # Read tif, convert each page into arrays in images[] for i in range(img.n_frames): img.seek(i) images.append(np.array(img)) # Read every numpy array, convert to tensorflow, process by dividing by 2 for x in images: tensorX = tf.convert_to_tensor(x) processedTensor = tf.math.divide(tensorX,2) tensors.append(processedTensor) # Convert back to numpy array for x in tensors: processedArrays.append(x.numpy()) # Convert to tif for x in processedArrays: tiffStack.append(Image.fromarray(x)) img = tiffStack[0].save(self.name + ".tiff", compression="tiff_deflate", save_all=True, append_images=tiffStack[1:]) img.save(self) The issue I'm running … -
Django equivalent of ASP.NET Parameter Binding or Ruby on Rails Action Controller Parameters
I'm wondering what's mentioned in the title. This are links to the examples mentioned, regarding other techs: ASP.NET Parameter Binding Ruby on Rails Action Controller Parameters Currently I'm building an API using DRF and using custom code in views or serializers validate methods to validate parameters, like this: class AnimalWriteSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = '__all__' def validate_dicose_category(self, value): raise serializers.ValidationError('Dicose Category cannot be set manually.') Is there a better way? -
Heroku throwing error H10 for my Django site
When I go to my site it tells me to run heroku logs --tail, and when I do that I get: 2022-01-16T05:23:01.227344+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=riseupontario.herokuapp.com request_id=49558b9a-5030-4ed9-bf0a-cc8642531c44 fwd="204.128.182.15" dyno= connect= service= status=503 bytes= protocol=https 2022-01-16T05:23:01.528171+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=riseupontario.herokuapp.com request_id=41626c63-e4e6-4e72-90e7-c0e36d3c928d fwd="204.128.182.15" dyno= connect= service= status=503 bytes= protocol=https I can't find anything on how to fix this. Help! -
HTML Not Picking Up Bootstrap & Won't Combine
I am creating an page that allows the user to filter a dataset, hit search, and see the results update below. Whenever I updated my week function to pick_list.html instead of filter_list.html, I get the error below. My filter_list.html doesnt show any bootstrap visuals or colors from the rest of my app, just a plain list. The pick_list.html shows a search button, but no search fields and zero data. Why am I struggling so much to combine these two? views.py: def week(request): #orders = Pick.objects.get(id=pk_test) orders = Pick.objects.all() #orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'myFilter':myFilter} return render(request, 'app/filter_list.html',context) pick_list.html: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <ul> <table class="table table-hover" id="table-ajax" style="background-color: white;"> <thead style="background-color: #de5246; color:white; border-bottom:white"> <tr> {% comment %} <th></th> {% … -
django celery delay function use guest user
Hello I want to use celery tasks in my Django project When I run the celery -A proj worker -l INFO all good it connects to the rabbitmq server But I have a problem when I run the task add.delay(1, 1) I get a response (403) ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. In the logfile I can see 2022-01-16 23:15:51.898981+00:00 [erro] <0.1093.0> PLAIN login refused: user 'guest' - invalid credentials I understand celery delay function using the wrong user guest and not saar my file in my project celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings.py CELERY_TASK_TRACK_STARTED = True CELERY_BROKER_URL = 'amqp://saar:1234567s@localhost' init.py from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y my packages: Django 3.2.11, celery 5.2.3, flower 1.0.0, django-celery-beat 2.2.1 What can I do to fix it? -
Django and HTMX I am looking for not "hacky" way to update class of link that calls HTMX request. Like "refresh-self" or something along those lines
I have a problem with HTMX in Django. I basically have two important components on page. List of categories and content that is being shown after you click on category. I was working nicely with just standard htmx "out of the box". But I started having problems when I wanted to add active css class on category link after you click it (to show user where he is currently). I did a lot of experiments with hx-swap-oob and hx-swap but the only thing that work was this: (it is the most relevant part of the code) <div class="col-sm-4"> <div class="card"> <div class="card-body" hx-boost="true" hx-target="#manual_results"> <div id="manual_categories"> {% include 'partials/manual_categories.html' %} </div> </div> </div> </div> <div class="col-sm-8"> <div id="manual_results"> {% include 'partials/manual_entries_list.html' %} </div> </div> and in manual_entries_list.html: <some html results> <div id="manual_categories" hx-swap-oob="true"> {% include 'partials/manual_categories.html' %} </div> Each category has simple if statement in django template code that is checking if it is selected (based on url path.) And it is working, thing is, on the first request the categories are rendered twice (which is logical since I have 2 includes on the same HTML). After I select one category, everything goes back to normal because HTMX "starts to … -
Django - Uploaded image gets saved twice: under original and validated name
I'm trying to solve a problem. On image file upload, I want to rename the file and resize it. I came up with a method below. I managed to get the image resized and saved under a valid name. Unfortunately the file gets saved twice, also under the invalid name. And the invalid one is stored in my object. How can I fix this? Thanks in advance class SparePartImages(models.Model): sparepart = models.ForeignKey('SparePart', on_delete=models.CASCADE) image = models.ImageField(upload_to='spare-part/', blank=True, null=True) def save(self, *args, **kwargs): super(SparePartImages, self).save(*args, **kwargs) max_size = settings.IMAGE_MAX_SIZE file = Image.open(self.image) (width, height) = file.size if (width/max_size < height/max_size): factor = height/max_size else: factor = width/max_size size = (int(width/factor), int(height/factor)) file = file.resize(size, Image.ANTIALIAS) file.save(removeAccent(self.image.path)) -
Why is the response i recieve at the front-end undefined
Why am i getting an when sending the post request.When i pass in the response body a string i dont get errors and it works perfectly fine but when i pass an complex element like this in json-like form it doesnt work. def main(request): if request.method == 'GET': return Response({ "name": "PPP", "lastName": "UUU" }) elif request.method == 'POST': try: data = request.body data = json.loads(data) P.pom1=data['poz1'] P.pom2=data['poz2'] CompMove() return Response({"poz1":P.pom1, "poz2":P.pom2}) except: return Response({"GRESKA"}) - List item -
How to display a StackedInline item from a Model in Django?
i want to get the value of my field "is_verified" from aStakedInline model of my Post model class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'words', 'date', 'is_verified') list_filter = ('date', 'author') def is_verified(self, obj): # HERE MY UNKNOWN CODE TO GET IS_VERIFIED VALUE FROM VerifiedPost Model def words(self, obj): return len(obj.content.split()) class AccountInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profiles' class PostInline(admin.StackedInline): model = VerifiedPost can_delete = False verbose_name_plural = 'Verified' models.py If anyone can help me -
Django download images from s3 bucket
i want to download the files i uploaded to the s3 bucket but i can't. Whenever i click on the things i want to download nothing happens and when i right click and open in new tab it shows me this link: "statichttps://airport-comsroom.s3.us-east-2.amazonaws.com/uploaded_files/Adobe_Photoshop_2021_v22.5.3.561_x64_2021_MULTILANG_RUS_rutracker-6148156.torrent?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential="cant show this"%2F20220117%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20220117T000020Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=2f6a8924ac5d9ced877d572bc901b40cce85f8dfd90cb70b1d64483e4bf369b4" settings.py AWS_ACCESS_KEY_ID = 'Can't show this' AWS_SECRET_ACCESS_KEY = 'Can't show this' AWS_STORAGE_BUCKET_NAME = 'airport-comsroom' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION= 's3v4' AWS_S3_ADDRESSING_STYLE = 'virtual' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' html file {% for file in dic.user_files %} <a href="static{{file.files.url}}" class="files" download> <div class="flex-file"> <p class="file-text">{{file.files}}</p> <img src="{%static 'Images/File.png'%}" class="file-image"alt=""> </div> </a> {% endfor %} I don't know if the download at the end of the a tag is the problem or even the correct way to do it. but this is what I got. it downloads fine when I serve the static files locally. and the file can be anything like word, pdf, excel, ect. please tell me if you need to view other pages. -
failing to index values using django-rest and elasticsearch
My DB is postgreSQL and I am using django_elasticsearch_dsl to connect django with elasticsearch. for some reason when i run the command: python manage.py search_index --rebuild I recieve this error massage: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x058AEE38>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) Its my first time using elasticsearch so I dont really know why I am recieving the error. anyone has a clue how to solve it? -
How to make token authentication redirect to a url instead of showing an error message in json?
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I need token authentication to redirect to a url instead of showing the error message in json, in case of error 401 Unauthorized: { "detail": "Authentication credentials were not provided." } -
creating post on a review model
I need help leaving a review to a another model as a user, ive been having errrors and tried a lot of solutions. error FieldError at /reviews/1 Cannot resolve keyword 'user' into field. Choices are: id, pet_owner, pet_owner_id, rating, review, sitter, sitter_id def post(self, request, pk): user = Review(pet_owner = request.user) sitter = get_object_or_404(Sitter, pk=pk) data = request.data review = Review.objects.create( pet_owner_id = user, sitter= sitter, rating=data['rating'], review=data['review'] ) return Response('Review Added', status=status.HTTP_400_BAD_REQUEST) ``` ``` class Review(models.Model): review = models.CharField(max_length=500) rating = models.DecimalField(max_digits=7, decimal_places=2) sitter = models.ForeignKey(Sitter,on_delete=models.CASCADE,null=True) pet_owner = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,null=True) ``` class Sitter(models.Model): first_name = models.CharField(max_length=255, default='Jane') last_name = models.CharField(max_length=255, default='Doe') zipcode = models.CharField(max_length = 5, default='12345') supersitter = models.BooleanField(null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) numReviews = models.IntegerField(null=True, blank=True, default=0) rating = models.DecimalField(max_digits=7, decimal_places=2, default=0) this is my review model and sitter model -
Django Form, save to multiple tables
I'm working on an order entry system where it'll track products, recipes, and orders for customers. I'm trying to figure out how to create a recipe_ingredient form/template that will create a product entry, a recipe entry and an associated recipe ingredient entry(s) when the user creates a new recipe. The form should ask for the recipe name, description, along with the ingredients(products table), and percentage. Database Design (I don't know if I got the symbols correct) Here's my models.py for the product/recipe/recipe ingredient class Product(models.Model): name = models.CharField(max_length=200, null=True) sku = models.CharField(max_length=200, null=True, blank=True) supplier = models.ForeignKey(Supplier, null=True, on_delete= models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) cost_per_pound = models.DecimalField(max_digits=7, decimal_places=2, blank=True) cost_per_ounce = models.DecimalField(max_digits=7, decimal_places=2, blank=True) note = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Recipe(models.Model): name = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete=models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) I've got a semi-working recipe ingredient form, but the user will need to create the product first and then select it when creating the recipe and recipe ingredients. def recipeCreate(request): RecipeIngredientFormSet = forms.inlineformset_factory(Recipe, Recipe_Ingredient, form=RecipeIngredientForm, extra=10, fields=('ingredient', 'recipe_percent',)) form = RecipeForm() formset = RecipeIngredientFormSet() if request.method == … -
Hot to create cart endpoints with Django Rest framework?
im going to start develop an order functionality. Im building rest api's and i dont really understand what is right for a future SPA. Because i looked at examples on github and some people do endpoints for every action (add/delete/update/list) and some just for list and all decrement or increment quantity is on Vue side. So what should i do? How to do it right? I want it to be like every modern app, for example, delivery club or some. And by the way, do i need to use sessions in rest api? Because in Antonio Mele book he do e-shop but not rest framework and uses sessions with cart. -
How can I re-run a Django For Loop inside a HTML Div using Javascript on Click Event
I have a HTML div like this, <div class="coment-area "> <ul class="we-comet"> {% for j in comment %} <div id="delete_comment{{j.id}}" class="mt-3"> {% if j.post_id.id == i.id %} <li > <div class="comet-avatar"> {% if j.user_id.User_Image %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src= {{ j.user_id.User_Image.url }} alt=""> {% else %} <img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg"> {% endif %} </div> Inside of it is a For Loop that is executed when the page is first loaded. Below this For Loop is a Comments Button <div > <button type="submit" onclick="comment_save(event,{{i.id}})" class= "my-2 ml-2 px-2 py-1 btn-info active hover:bg-gray-400 rounded ">Comment</button> </div> </div> </li> </ul> </div> Whenever this button of Comments is clicked, a function in Javascript is called which is defined below, function comment_save(event,post_id) { var comment_value=$("#comment_value"+post_id).val(); var user_id=$("#comment_user_id"+post_id).val() postdata={ "comment_value":comment_value, "user_id":user_id, "post_id":post_id } SendDataToServer("readmore",postdata,function() { alert() }) $("#comment_value"+post_id).val(" ") <! --- document.location.reload().. Something here that refresh that for loop ---> } What I want is this that whenever the button is clicked, it re-executes that for Loop inside my main div without having to refresh the page. I have been trying to do this for two days but could not find any solution to this. Can … -
How can I define a check constraint on a string length (Django)
I am looking to do the following: constraints = [models.CheckConstraint(check=Length('code')==5, name='code_length')] It fails because the check argument needs to be a A Q object or boolean Expression that specifies the check you want the constraint to enforce I'm not seeing string length field lookup nor am I seeing a way to incorporate the Length database function into a Q object argument. The only other option is a boolean expression (which is what I aimed at in my failed attempt above) but apparently this is an API that I have to implement. I am new to Django and would appreciate the help. -
Django Filter Returning Attribute Errors
I have the following code, that is purposed to create a filtered view of my dataset based on a few dropdown selections defined in MyFilter. In my /picks url, I see the search bar but no criteria to filter with. When I navigate to /picks/8 to test the filtering, I get the following attribute with my model. I've also tried orders = Pick.order_set.all() with no luck as well. Any suggestions on how to get this working? error: 'Pick' object has no attribute 'order_set' pick_list.html: <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> views.py def week(request, pk_test): week = Pick.objects.get(id=pk_test) orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'order_count':order_count, 'myFilter':myFilter} return render(request, 'app/pick_list.html',context) filters.py class PickFilter(django_filters.FilterSet): age = CharFilter(field_name='name', lookup_expr='icontains') name = CharFilter(field_name='name', lookup_expr='icontains') class Meta: model = Pick fields = '__all__' exclude = ['photo'] models.py class Pick(models.Model): submitter = models.CharField(max_length=50, verbose_name='Submitter', null=True, blank=True) week = models.CharField(max_length=50, verbose_name='Week', null=True, blank=True) name = models.CharField(max_length=50, verbose_name='Name', null=True, blank=True) photo = models.CharField(max_length=50, verbose_name='Photo', null=True, blank=True) #photo = models.ImageField(upload_to="media", max_length=500, verbose_name='Photo', null=True, blank=True) hometown = models.CharField(max_length=50, verbose_name='Hometown', null=True, blank=True) age = models.IntegerField(verbose_name='Age', null=True, blank=True) progress = models.IntegerField(verbose_name='Progress', null=True, blank=True) occupation = models.CharField(max_length=50, verbose_name='Occupation', null=True, blank=True) elim_week = models.CharField(max_length=50, verbose_name='Week … -
Get values from another table python
I would like to get column named 'work_id' from table Duties. The common column in table User and Duties is account_id(for User) and ID(for Duties), this is the same value. The Duties is pk in model User. Right now I have function, that sending csv file to email with id, name and account_id column from table User. def send_csv(): data = {} person_data= User.objects.values('uid', 'state', 'account_id') buffer = io.StringIO() writer = csv.writer(buffer) for person_data in User.objects.filter(state=User.Active): writer.writerow([person_data.uid, person_data.account_id) buffer = io.StringIO() writer = csv.writer(buffer) for person_data in User.objects.filter(state=User.Disabled): writer.writerow([person_data.uid, person_data.account_id) email = EmailMessage('CSV statistic', to=settings.MAIL) email.attach('active.csv', buffer.getvalue(), 'text/csv') email.attach('disabled.csv', buffer2.getvalue(), 'text/csv') email.send() Please help me with this, a little bit stuck. I would like also send column work_id with correct uid and account_id from table User Tables example: User uid name last_name state account_id 1ldwd John Black active 123 2fcsc Drake Bell disabled 456 3gscsc Pep Guardiola active 789 4vdded Steve Salt disabled 012 Table Duties uid rate hobbie account_id work_id 1sdeed part football 456 007 3rdfd full hockey 789 022 45ffdf full regbie 123 4567 455ggg part fishing 012 332 -
With django, how to control the server's stop and start again by batch.bat via a button on the screen, use the Windows operating system
With django, how to control the server's stop and start again by batch.bat via a button on the screen, use the Windows operating system all the methods I got The process is done manually and I didn't find an automated way or code that works on it for example: 1-I have to Open Windows PowerShell as Administrator Find PID (ProcessID) for port 8080: netstat -aon | findstr 8000 TCP 0.0.0.0:8080 0.0.0.0:0 LISTEN 77777 Kill the zombie process: taskkill /f /pid 77777 Now we return to the question how can I do this process automatically, either through the batch.bat file or through the django code