Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get list of values from object in FastApi
I want to get list of values on a query instead of objects. Coming from a Django World I want to get something like values = list(MyModel.objects.filter(data=data).values('field_1', 'field_2')) Which would directly coming me something like values = [ { 'field_1': 'data_1', 'field_2': 'data_2' }, { 'field_1': 'data_1', 'field_2': 'data_2' } ] -
How to access a Uvicorn web server with it's domain name rather than it's IP address and port number?
I use uvicorn and Django to run an ASGI application and I would like to access the web server with it's domain name. I create a A record in the DNS server to point to the correct IP address and it is now reachable with http://my-domain.com:8000 How can I tell him to accept the URL without the port number ? The desired URL is http://my-domain.com This is how I run the server with systemd: uvicorn myapp.asgi:application --host 0.0.0.0 --port 8000 --lifespan off settings.py ALLOWED_HOSTS=['my-domain.com', '1.22.333.332'] Firewall rules : (env) user@ubuntu-1cpu-2gb-pl-waw1:/var/www/myapp$ sudo ufw status Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 8000 ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) -
Django importing excel in not good format
I am a starting programmer and I need to create a site in django, with the ability to add an excel file, where some columns are merged, there is a header and convert it to a normal view. Can anyone please tell me some advices/books/paccages, that can help me to do this? The example of excel file in the screen below image Thank you very much! -
TypeError at /admin/ , 'QueryDict' object is not callable
I am getting this error when i am check this validation ,in django forms , how i can solve this error form.py d=[] b=[] my_tuple = [] for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) d.append((start_new,start_old)) b.append((end_new,end_old)) my_tuple.append((d[0],b[0])) for i in my_tuple[0]: my_result = [sub for sub in i if all(element >= 0 for element in sub)] if len(my_result)>2: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
I can only login with an administrator account but I need to do it with a custom user model
Users can register without any problem, but they cannot login, only a super user Im using a custom user model, so i can login with just the email and the password, i already tried using the django build-in templates for login but they doesn't work, it give the same error When i try to login as a normal user, it gives me this error <ul class="errorlist"><li>__all__<ul class="errorlist nonfield"><li>Invalid login</li></ul></li></ul> My models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=150, unique=True) username = models.CharField(max_length=150, unique=True) # password = models.CharField(max_length=150) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def … -
Why doesn't Azure show me my design files CSS, HTML, JavaScript
When I enter the command: 'az webapp up' My Django/Python site appears but with no design at all. When I enter the command: 'python manage.py runserver' in the terminal, the app works as usual with the design. Am I missing a command? Or maybe something in the settings is not correct? -
Django admin inlines: single inline for multiple foreign keys
I have a model that stores Conversations as follows: class Conversation: sender_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_starter_user") recipient_user = models.ForeignKey("test_app.User", on_delete=models.PROTECT, related_name="conv_recipient_user") It references the User model twice. I would like to be able to go to Django Admin and see a section called 'Conversations' that would list all conversations that the user participates in, both as a starter and as a recipient. Currently, I am creating two separate inlines ConversationRecipientInline and ConversationSenderInline that I add to the User admin. This splits the Conversation view into two which is not ideal. -
Attempting to Bulk Update A Priority List - DRF
I'm attempting to Bulk Update my entire priority list. Here's the model: class OrderPriority(models.Model): order = models.OneToOneField(Order, related_name='priority_order', on_delete=models.CASCADE) priority = models.BigIntegerField(unique=True) Here's my Bulk Update Serializer and List Serializer Class: class BulkPriorityUpdateListSerializer(serializers.ListSerializer): def update(self, instances, validated_data): instance_hash = {index: instance for index, instance in enumerate(instances)} result = [ self.child.update(instance_hash[index], attrs) for index, attrs in enumerate(validated_data) ] writable_fields = [ x for x in self.child.Meta.fields if x not in self.child.Meta.read_only_fields ] try: self.child.Meta.model.objects.bulk_update(result, writable_fields) except IntegrityError as e: raise ValidationError(e) return result def to_representation(self, instances): rep_list = [] for instance in instances: rep_list.append( dict( id=instance.id, order=instance.order.id, priority=instance.priority, ) ) return rep_list class BulkOrderPrioritySerializer(serializers.ModelSerializer): class Meta: model = OrderPriority fields = ("id", "order", "priority") read_only_fields = ("id",) list_serializer_class = BulkPriorityUpdateListSerializer Here's my view along with the custom bulk update view: class CustomBulkUpdateAPIView(generics.UpdateAPIView): def update(self, request, *args, **kwargs): def validate_ids(data, field="id", unique=True): if isinstance(data, list): id_list = [int(x[field]) for x in data] if unique and len(id_list) != len(set(id_list)): raise ValidationError("Multiple updates to a single {} found".format(field)) return id_list return [data] ids = validate_ids(request.data) instances = self.get_queryset(ids=ids) serializer = self.get_serializer( instances, data=request.data, partial=False, many=True ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) class OrderPriorityUpdateAPIView(CustomBulkUpdateAPIView): serializer_class = BulkOrderPrioritySerializer def get_queryset(self, ids=None): return OrderPriority.objects.filter( id__in=ids, ) I then … -
How to define headers for authorization in django testing?
I want to write a test case for a function in my views in my Django project. I am just a beginner in this field, I have changed my settings.py and added the below line of code to the DATABASES dictionary, and also create a new user using MySQL shell based on this post: 'TEST': { 'NAME': 'test_sepantadb', } In function, there is a try/catch for checking the authorization using the request.headers. Here is the API code: @api_view(['GET']) def Get_users(request, **kwargs): try: user = request.headers['Authorization'] p = Profile.objects.get(username=user) except Exception as e: print(e) return Response(status=status.HTTP_401_UNAUTHORIZED) users = Device.objects.filter(owner=p) res = [] for u in users: user_inf = {} try: pdm = PersonDeviceMapper.objects.filter(device=u)[0] prof = pdm.person user_inf['name'] = prof.name user_inf['username'] = prof.username except Exception as e: print(e) user_inf['name'] = u.name user_inf['username'] = "default_" + str(u.id) user_inf['created_at'] = u.created_at user_inf['id'] = u.id user_inf['device_id'] = u.device_id res.append(user_inf) return Response(res) And here is the code in models.py for Profile class: class Profile(models.Model): GENDER_MALE = 1 GENDER_FEMALE = 2 GENDER_CHOICES = [ (GENDER_MALE, _("Male")), (GENDER_FEMALE, _("Female")), ] code = models.IntegerField(null=True, blank=True) username = models.CharField(max_length=128, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) lastname = models.CharField(max_length=50, null=True, blank=True) birthday = models.DateField(null=True, … -
How to make django_cron works in setted time
I have the following code: class ChangeStatusJob(CronJobBase): hours = [f"{str(el).zfill(2)}:30" if yel else f"{str(el).zfill(2)}:00" for el in range(0, 24) for yel in (0, 1)] schedule = Schedule(run_at_times=hours) code = "project.cron.ChangeStatusJob" def do(self): pass Cron doesn't work at a time which in run_at_times value and as a result, he works with a default 5 min delay. How to fix it? PS. cron should work every hour at **:00 and **:30 -
Unable to open unix socket in redis - Permission denied while firing up docker container
I am trying to fire up a separate redis container which will work as a broker for celery. Can someone help me with as to why the docker user is not able to open the UNIX socket. I have even tried making the user as root but it doesn't seem to work. Please find below the Dockerfile, docker-compose file and redis.conf file Dockerfile FROM centos/python-36-centos7 USER root ENV DockerHOME=/home/django RUN mkdir -p $DockerHOME ENV PYTHONWRITEBYCODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH=/home/django/.local/bin:$PATH COPY ./oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm /home/django COPY ./oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm /home/django COPY ./oracle.conf /home/django RUN yum install -y dnf RUN dnf install -y libaio libaio-devel RUN rpm -i /home/django/oracle-instantclient18.3-basiclite-18.3.0.0.0-3.x86_64.rpm && \ cp /home/django/oracle.conf /etc/ld.so.conf.d/ && \ ldconfig && \ ldconfig -p | grep client64 COPY ./requirements /home/django/requirements WORKDIR /home/django RUN pip install --upgrade pip RUN pip install --no-cache-dir -r ./requirements/development.txt COPY . . RUN chmod 777 /home/django EXPOSE 8000 ENTRYPOINT ["/bin/bash", "-e", "docker-entrypoint.sh"] Docker-compose file version : '3.8' services: app: build: . volumes: - .:/django - cache:/var/run/redis image: app_name:django container_name: app_name ports: - 8000:8000 depends_on: - db - redis db: image: postgres:10.0-alpine volumes: - postgres_data:/var/lib/postgresql/data ports: - 5432:5432 environment: - POSTGRES_USER=app_name - POSTGRES_PASSWORD=app_password - POSTGRES_DB=app_db labels: description : "Postgres Database" container_name: app_name-db-1 redis: image: … -
A state mutation was detected between dispatches
I've got this issue which I do not understand. I am getting an invariant error that says a state mutation has occurred, but at a very awkward place. Basically I've got this page: import React, { useState, useEffect } from "react"; import { Link, useLocation, useNavigate, useSearchParams, } from "react-router-dom"; import { Form, Button, Row, Col, Table } from "react-bootstrap"; import { LinkContainer } from "react-router-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loader from "../components/Loader"; import Message from "../components/Message"; import FormContainer from "../components/FormContainer"; import { register } from "../actions/userActions"; import { getUserDetails, updateUserProfile } from "../actions/userActions"; import { USER_UPDATE_PROFILE_RESET } from "../constants/userConstants"; import { listMyOrders } from "../actions/orderActions"; function ProfileScreen() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [message, setMessage] = useState(""); const dispatch = useDispatch(); const location = useLocation(); const userDetails = useSelector((state) => state.userDetails); const navigate = useNavigate(); const { error, loading, user } = userDetails; const userLogin = useSelector((state) => state.userLogin); const { userInfo } = userLogin; const userUpdateProfile = useSelector((state) => state.userUpdateProfile); const { success } = userUpdateProfile; const orderListMy = useSelector((state) => state.orderListMy); const { loading: loadingOrders, error: errorOrders, … -
How to test dynamically changing parameters within an sql query to the database using pytest
Function to test def get_adgroups_not_taked_share( campaign_ids: List[str], src_table: str, spend_src_table: str ) -> List[Tuple[str, str]]: start_date = ( date.today() - timedelta(days=get_redshift_query_param_value('start_date')) ).strftime('%Y-%m-%d') end_date = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d') loses_adgroups: List[Tuple[str, str]] = [] with RedshiftCursor() as cursor: cursor.execute( """ SELECT ad_group, spends.campaign_id, ad_spend FROM ( SELECT ... SUM(spend_eur) AS ad_spend FROM %(src_table)s WHERE ...... ) as spends LEFT JOIN (SELECT ... AS total_spend FROM %(spend_src_table)s GROUP BY campaign_id, spend_eur ) AS sg ON ... WHERE ad_spend * 100 / %(cutoff_percent)s < total_spend """, { 'campaign_ids': tuple(campaign_ids), 'start_date': start_date, 'end_date': end_date, 'cutoff_percent': get_redshift_query_param_value('cutoff_percent'), 'src_table': AsIs(src_table), 'spend_src_table': AsIs(spend_src_table), }, ) for row in cursor.fetchall(): loses_adgroups.append((row[0], str(row[1]))) return loses_adgroups Within it, the function get_redshift_query_param_value is called def get_redshift_query_param_value(param: str) -> int: params = { 'cutoff_percent': RedshiftQuery.CUTOFF_PERCENT, 'min_place': RedshiftQuery.MIN_PLACE, 'start_date': RedshiftQuery.START_DATE, } return int(RedshiftQueryParam.objects.get(name=params[param]).value) which retrieves a numeric value from the databases based on the key passed in. Wrote a test that wets the database access and the return value test.py import pytest from google_panel.logic.clean_creative import get_adgroups_not_taked_share @pytest.fixture def campaigns_redshift_cursor_mock(mocker): cursor_mock = mocker.MagicMock() cursor_mock.fetchall.return_value = [ ('hs_video544', '123123123', 100), ('hs_video547', '123123123', 50), ] rs_cursor_creator = mocker.patch('google_panel.logic.clean_creative.RedshiftCursor') rs_cursor_creator.return_value.__enter__.return_value = cursor_mock return rs_cursor_creator @pytest.fixture def get_redshift_query_param_value_mock(mocker): return mocker.patch('google_panel.logic.clean_creative.get_redshift_query_param_value') @pytest.mark.django_db def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, get_redshift_query_param_value_mock): campaign_ids = ['1111', '2222', … -
Django storages: Need authenticated way of reading static files from google cloud storage
I am trying to read static files from GCP storage using a service account key. The problem is while most of the requests are authenticated django-storages, some of the requests are public. Developer console: Networks tab And because of which I am getting a broken Django admin UI. Broken Django admin UI Here's my static file settings in settings.py file. STATIC_URL = "/static/" if DEPLOYED_URL: DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = env("GS_BUCKET_NAME") GS_CREDENTIALS = service_account.Credentials.from_service_account_info( json.loads(get_secret(PROJECT_NAME, "service_account_json")) ) GS_DEFAULT_ACL = "projectPrivate" My restrictions are I have Fine-grained: Object-level ACLs enabled bucket on which public access cannot be given. PS: Since there are restrictions to the project I cannot use a public bucket. Alternate ways other than the usage of django-storages package are also appreciated. The only condition is reads should be authenticated and not public. -
How to refresh page for new request in Django
I want to receive a request.POST values N times, where N is a number entered by the user. The views.py is: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): form=Form(request.POST) c = int(request.POST.get('peso_u')) d = int(request.POST.get('preco_u')) peso_unitario.append(c) preco_unitario.append(d) return render(request, 'valores.html') return render(request, 'pacote_m.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) In this code in the end I have two returns, where the first is inside the for loop because I want to receive the values N times and return them to the template "valores.html". The last return is in the end, after the for loop will redirect to a new template, this template "pacote.html" will show the values calculated according to I programmed, but it isn't the problem. The template valores.html is: {% extends 'basic.html' %} {% block content %} <form action="page2" method="GET"> {% csrf_token %} <h1>Digitados:</h1> numero de objetos={{n_objetos}}<br> peso peso maximo={{peso_maximo}}<br> <!--- Peso unitario: <input type="text" name="peso_u"><br><br> Preco unitario: <input type="text" name="preco_u"><br><br> ---> <table> <thead> <tr> <th>Peso unitario</th> <th>Preco unitario</th> </tr> </thead> <tbody> <tr> <td><input type="text" name="peso_u"></td> {{form.peso_u}} <td><input type="text" name="preco_u"></td> {{form.preco_u}} </tr> </table> <input type="submit"> </form> {% endblock %} My forms.py is: class Form(forms.Form): peso_u=forms.CharField(max_length=50) preco_u=forms.CharField(max_length=50) The problem is I can't get the N … -
can we use prefetch_related with many-to-many relationship in django
hey guys let's say i have models like this class CouponCode(models.Model): ...... class Product(models.Model): codes = models.ManyToManyField(CouponCode) how can I use perefetch_related with reverse many to many relationships I did this and I looked at the queries and I found i didn't make a query for the second table CouponCode.objects.all().perefetch_related('product_set') -
how to stop ajax waiting for its response after sending request
def openFile(request): record = Verification.objects.filter(farmRegNo= request.POST['farmRegNo']) filepath = os.path.join('', str(record[0].certificate)) # not working line #return FileResponse(open(filepath, 'rb'), content_type='application/pdf') return HttpResponse(Respon) This is code using django, since i call this openFile() by ajax, i cant work for FileResponse, it only expects HttpResponse, I want to open this file....is there any way to do this??? -
Incorrect display of children's models on the form in django
I tried to make a creation form for vacancy on my job search site, but i faced with problem. I have User model, company model and vacancy model. They are inherited by foreignkeys. And the problem is that user can use all companies for creation a vacancy instead of created by this user companies(User can create several companies). I tried to change creation form and view by filtering, but it didn't work out for me. I am new at django and i dint find anything to resolve my problem. Model of company: class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(('Title of Shop'), blank=True, max_length=255) info = models.TextField(('Information about Shop'), null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) Model of vacancy: class Vacancies(models.Model): title = models.CharField(('Title of Vacancy'), blank=True, max_length=255) city = models.ForeignKey(City, on_delete=models.CASCADE, default='363') description = models.TextField(('Information about Vacancy'), null=True, blank=True) employer = models.ForeignKey(Company, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return str(self.title) Create vacancy view: @login_required(login_url='login') def createVacancy(request): form = VacanciesForm() cities = City.objects.all() if request.method == 'POST': form = VacanciesForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form, 'cities': cities} return render(request, 'vacancy_form.html', context) … -
can't get data from Django to html
//views.py def index(request): if request.method == 'POST': data = request.POST['data'] context = {'mydata': data} return render(request, 'home/index.html', context) else: html_template = loader.get_template('home/index.html') HttpResponse(html_template.render(request)) //index.html <form method = 'POST' id = 'post-form'> <select name = 'data' id = 'data'> <option> 1 </option> <option> 2 </option> </select> <button type="submit" name = 'post-form'> submit </button> </form> <h2> {{ mydata}} </h2> // this line print nothing. When I click the submit button, I can access data from html submit in views.py. However, I can't access 'mydata ' from dajngo in html. how can i solve it? -
when I try to render tags I get Wallpaper.Wallpaper.None
views.py def download(request, wallpaper_name): try: wallpaper = Wallpaper.objects.get(name=wallpaper_name) similar_wallpapers = wallpaper.tags.similar_objects()[:2] except Exception as exc: wallpaper = None similar_wallpapers = None messages.error = (request, 'Sorry! data does not exist') context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = TaggableManager() Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name download.html <div class="tag"> <h3>Tags</h3> <ul> <li>{{wallpaper.tags}}</li> </ul> </div> I want all the tags of that particular wallpaper to be rendered and if possible please tell me if there is any other way to handle tags, because using taggit its very difficult i am getting manny errors -
django multiple random questions with same answer options
Have this small app with a model for questions and their answers are picked from a tuple. My current challenge is to display the questions with a dropdown for the answers using a modelform. Once submitted the form should save noting the question id and answer option selected. class Question(models.Model): question = models.CharField(max_length=100) active = models.BooleanField(default=True) class Answer(models.Model): answer_options = [ ('EM', 'Exceeded Expectations'), ('ME', 'Met Expectations'), ('BE', 'Below Expectations'), ] question = models.ForeignKey(Question, blank=True, Null=True, on_delete=models.CASCADE) answer_selected = models.CharField(max_length=20, choices=answer_options, default='ME') The form layout is as follows: Question 1 Answer option dropdown Question 2 Answer option dropdown Kindly assist -
Django Handling Public API use (anonymouse users making calls to API)
I am making a simple website with as Django as backend. Ideally, you should be able to use it without creating an account and then all of your saved items ('notes') in there would be visible to anyone. For now I have created a dummy user on Django, and every time an anonymous user makes an API call to add/delete/modify a notes, on Django's side it selects dummy user as a user. It would work okey (I think) but one of Django's API can take a really long time to run (~1-2 minutes). Meaning that if multiple people are trying to make API calls while being anonymous, at some point the server will freeze until the long API finishes run. Is there a way such case should be handed on the server side to prevent freezing of server ? -
Reverse for 'tutorial_home' with arguments '('',)' not found. 1 pattern(s) tried: ['tutorial/(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
Reverse for 'tutorial_home' with arguments '('',)' not found. 1 pattern(s) tried: ['tutorial/(?P[-a-zA-Z0-9_]+)/\Z'] views.py from django.shortcuts import HttpResponse, render from tutorial.models import IndexTutorial # Create your views here. def tutorial_home(request, slug): main_topic = IndexTutorial.objects.filter(slug=slug).first() print(main_topic) context = {'main_topic':main_topic} return render(request, 'tutorial/main.html', context) urls.py from django.urls import path from .import views app_name = 'tutorial' urlpatterns = [ path('<slug:slug>/', views.tutorial_home, name='tutorial_home'), ] index.html <div class="position-absolute bottom-0 start-0 w-100"> <a href="{% url 'tutorial:tutorial_home' main_topic.slug %}" class="btn btn- danger d-block rounded-0">Start Learning</a> </div> -
How to specify the value column for CSV output of data model with ForeignKey in Django
I would like to export CSV file of a Django Model that is using ForeignKey. By default, the file is exported with ID value of ForeignKey model, but I want have other column's data as value of the CSV file. Here is example models.py class Task(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) assign = models.ForeignKey(Member, on_delete=models.CASCADE) class Member(models.Model): name = models.CharField(max_length=100) role = models.CharField(max_length=100) views.py def export_to_csv(request): task = task_set.all() task_list = task.values() df = pd.DataFrame(list(task_list.values())) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=task.csv' df.to_csv(path_or_buf=response) return response If I implement as above, column for Member model would be ID. But I want to have name column of Member model on CSV file. Thank you! -
django pytest --log-level not works
I have .ini file where specified -s --log-level=WARNING And in django's settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(asctime)s [%(levelname)s] " + " %(module)s - %(name)s: %(message)s", }, }, "handlers": { "console": { "level": "WARNING", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "loggers": { "": {"handlers": ["console"], "level": "INFO", "propagate": False}, }, } But logger.info is being seen in pytest running