Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : is it possible to display multiple edit forms as one consolidated form in django admin?
I have three EDIT forms, an environment has one or multiple machines, then a machine has one or multiple users. Now my question is there a way to display the three EDIT forms in one consolidated form with one save button. I want to display three tabs one for Environment and one for Machines (multiple) and one for Users (Multiple), Similar to this : I have already achieved similar results using custom HTML template, but I'm not satisfied, it would be better if I got it done using Django admin configurations my current solution : <div class="tab-content mt-3" id="pills-tabContent"> <div class="tab-pane fade show active" id="environment" role="tabpanel" aria-labelledby="environment-tab"> <div class="step"> <h2>Environment general information</h2> {% for field in environment_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> </div> <div class="tab-pane fade" id="machine" role="tabpanel" aria-labelledby="machine-tab"> <div class="step"> <h2>Machines information</h2> {% for machine_form in machine_forms %} <h3>Machine {{ forloop.counter }}</h3> {% for field in machine_form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} {% if … -
Celery worker is not starting for my django project hosted on elastic beanstalk
Good day by co-developers. I have a project working on aws elasticbeanstalk and i want to integerate celery to it but the celery worker is not starting and everything is workking fine in development but when i deploy it to elastic ebeanstalk it wont start the worker. my question is that is there any way to start the celery worker or i am during it wrong. below is my Procfile file where i start it with the error i am getting the coonsoole and the log in the instance. thanks in advance. Procfile web: gunicorn --timeout 90 ayjayproject.wsgi celery_beat: celery -A ayjayproject.celery beat -l INFO celery_worker: celery -A ayjayproject.celery worker -l INFO -P solo Log fiile 2023/10/23 10:35:00.909620 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_beat.service 2023/10/23 10:35:00.919175 [INFO] Running command /bin/sh -c systemctl is-active celery_beat.service 2023/10/23 10:35:00.927731 [INFO] Running command /bin/sh -c systemctl start celery_beat.service 2023/10/23 10:35:00.958395 [INFO] Registering the proc: celery_worker 2023/10/23 10:35:00.958424 [INFO] Running command /bin/sh -c systemctl show -p PartOf celery_worker.service 2023/10/23 10:35:00.975817 [INFO] Running command /bin/sh -c systemctl daemon-reload 2023/10/23 10:35:01.145963 [INFO] Running command /bin/sh -c systemctl reset-failed 2023/10/23 10:35:01.159697 [INFO] Running command /bin/sh -c systemctl is-enabled eb-app.target 2023/10/23 10:35:01.171728 [INFO] Running command … -
Import iso_date_prefix from django_minio_backend problem
I have this exception when running django dev-server: File "/Users/maxim/PycharmProjects/inventory3/inventory/main/models.py", line 22, in <module> **from django_minio_backend import iso_date_prefix** File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/__init__.py", line 1, in <module> from .apps import * File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/apps.py", line 3, in <module> from .models import MinioBackend, MinioBackendStatic File "/Users/maxim/PycharmProjects/inventory3/venv/lib/python3.11/site-packages/django_minio_backend/models.py", line 30, in <module> from django.utils.timezone import utc **ImportError: cannot import name 'utc' from 'django.utils.timezone'** It started from updating Python's packages to latest versions... -
DRF serializer for many-to-many through tree
here are my models (simplified): class Template(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) areas = models.ManyToManyField("Area", through="AreasOrder") class Area(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) items = models.ManyToManyField("Item", through="ItemsOrder") class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) further_into_tree= models.ManyToManyField("SomeModel", through="SomeModelOrder") class AreasOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) template = models.ForeignKey(Template, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) class ItemsOrder(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True) I want to build serializer for getting template by id with all it depedencies. I'm struggling with putting items into area serializer. Can you help me? Serializers: class TemplateSerializer(serializers.ModelSerializer): areas = AreaSerializer(many=True, source="areasorder_set") class Meta: model = Template fields = ("id", "title", "areas", ) class AreaSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() order_id = serializers.SerializerMethodField() id = serializers.ReadOnlyField(source="area.id") title = serializers.ReadOnlyField(source="area.title") def get_order_id(self, obj): return obj.id def get_items(self, obj): How to access items assigned to area? return ItemSerializer(many=True, source=obj.area.itemsorder_set) # doesn't work - raises error "'RelatedManager' object is not iterable" class Meta: model = AreasOrder fields = ( "id", "title", "items", "order_id" ) I also tried basing AreaSerializer on model Area: class AreaSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, required=False) class Meta: model = Area fields … -
additional fields in ModelSerializer with override update in django
I have a product model like this: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) category = models.ForeignKey(ProductCategories, on_delete=models.CASCADE) brand = models.ForeignKey(ProductBrand, on_delete=models.SET_NULL, blank=True, null=True) score = models.PositiveIntegerField(blank=True, null=True) insurnace = models.PositiveIntegerField(blank=True, null=True) property = models.ManyToManyField(ProductProperty, blank=True) is_flagship = models.BooleanField(default=False) is_exhibition = models.BooleanField(default=False) seen = models.IntegerField(default=0) for saving images, prices and details i wrote this three model: class ProductImage(models.Model): image = models.ImageField(upload_to='product_image/') product = models.ForeignKey(Product, related_name='image', on_delete=models.SET_NULL, blank=True, null=True) is_main_image = models.BooleanField(default=False) class ProductDetail(models.Model): title = models.ForeignKey(ProductDetailTitle, related_name='value', on_delete=models.CASCADE) value = models.CharField(max_length=500) product = models.ForeignKey(Product, related_name='detail', on_delete=models.CASCADE) class ProductPrice(models.Model): product = models.ForeignKey(Product, related_name='price', on_delete=models.CASCADE) color = models.ForeignKey(ProductColor, on_delete=models.CASCADE) price = models.PositiveIntegerField() quantity = models.PositiveIntegerField() i wrote this serializer for manage product class ProductAdminSerializer(serializers.ModelSerializer): images = serializers.ListSerializer(child=serializers.IntegerField()) prices = ProductPriceForProductAdminSerializer(many=True) properties = serializers.ListSerializer(child=serializers.IntegerField()) details = ProductDetailForProductAdminSerializer(many=True) class Meta: model = Product fields = ['id', 'title', 'category', 'brand', 'images', 'description', 'properties', 'is_flagship', 'is_exhibition', 'prices', 'score', 'insurnace', 'details'] def create(self, validated_data): title = validated_data.get('title') category = validated_data.get('category') brand = validated_data.get('brand') description = validated_data.get('description') is_flagship = validated_data.get('is_flagship') is_exhibition = validated_data.get('is_exhibition') score = validated_data.get('score') insurnace = validated_data.get('insurnace') product = Product.objects.create(title=title, category=category, brand=brand, description=description, is_flagship=is_flagship, is_exhibition=is_exhibition, score=score, insurnace=insurnace) image_ids = validated_data.get('images') ProductImage.objects.filter(id__in=image_ids).update(product=product) properties = validated_data.get('properties') if properties is not None: property_objs = ProductProperty.objects.filter(id__in=properties) product.property.set(property_objs) prices … -
Django JSONB find value less than
I have a sample JSONB dataset below, this is one column entry from a single row: [ { "id": "xxx", "type": "thing", "value": { "date": "2023-10-21" } }, { "id": "xxy", "type": "thing", "value": { "date": "2023-10-19" } } ] I need to find if one of the 'date' values is less than 'some_value' - please see pseudocode below: Q(columnName__{arrayOfItems}__value__date__lt=some_value) I can find if an exact value exists but need the value to be variable, for example the below works: Q(columnName__contains=[{"value": {"date": "2023-10-21"}}]) I think I need to add a subquery for the date itself ("2023-10-21") to see if it is less than some other date but currently unable to do this. Spent a few days so far, any comments welcome to help guide me. Many thanks in advance. -
feign client response does not retrive cookie named sessionid while postman does
I have to connect to django web application using feign client. First, i checked the flow in postman. In postman I'm using GET on myapp/accounts/login/?next=/ and retrive csrftoken as entry Set-Cookie in response headers I'm using POST on myapp/accounts/login/?next=/ with body as x-www-form-urlencoded "username=login&password=password&csrfmiddlewaretoken=token&next=/" and retrive NEW csrftoken and sessionid as entry in Set-Cookie. The response code is 302 (Found) I need those two cookies to use as request headers with another endpoints and i checked it's working fine The problem is that i cannot reproduce the same in feign client which i have to use The feign response from POST doesn't have second cookie (sessionId) The csrftoken is not refreshed I think i was trying almost everything : cookieinterceptor, turning off follow redirects in okhttp client, session interceptor in okhttp My simple code looks like : public class Main { private static final String AUTHENTICATION_TEMPLATE = "username=%s&password=%s&csrfmiddlewaretoken=%s&next=/"; public static void main(String[] args) throws IOException { RouteClient routeClient = Feign.builder() .client(new OkHttpClient()) .logger(new CustomFeignLogger()) .logLevel(Logger.Level.FULL) .encoder(new JacksonEncoder()) .decoder(new JacksonDecoder()) .target(RouteClient.class, DataInput.url); Response getResponse = routeClient.getToken(); String cookie = extractCookie(getResponse); String token = extractToken(cookie); Response postResponse = routeClient.postDataWithParametersInBody(insertHeaderMap(token), insertBody(AUTHENTICATION_TEMPLATE, token)); System.out.println(postResponse); } public static String insertBody(String template, String token) { return … -
Task threadpoolexecutor disappeared suddenly after 10 minutes of running - python
The Task that created using ThreadPoolExecutor disappear if they are not completed within 10 minutes, this makes me unable to execute tasks that run for a long time. I'm running a background scheduler in Django with an execution time window of every 5 seconds. scheduler = BackgroundScheduler() scheduler.add_job(start_etl_caller, 'interval', seconds=5) def execute_api(etl_id, endpoint, is_running, updated_at, threshold_time): try: print(f'start etl caller - etl_id : {etl_id}') x = requests.get(endpoint) print(endpoint, x.content) print(f'end etl caller - etl_id : {etl_id}') except: raise update_state(etl_id, False) def start_etl_caller(): etl_list = get_active_apis() threshold_time = (timezone.localtime() - timedelta(hours=1)).replace(tzinfo=None) executor = ThreadPoolExecutor() for etl_record in etl_list: if etl_record[2]: if etl_record[3] <= threshold_time: update_state(etl_record[0], False) continue update_state(etl_record[0], True) try: executor.submit(execute_api, etl_record[0], etl_record[1], etl_record[2], etl_record[3], threshold_time) except: raise The task is to call the API using ThreadPoolExecutor, so that processes do not wait for each other. However, if requests.get(endpoint) takes more than 10 minutes, the code after that will not be executed (print - update). My assumption is that tasks created using ThreadPoolExecutor will automatically disappear if the process does not complete before 10 minutes. Is there any enlightenment on how I can solve this problem? I want my task to continue running even though 10 minutes have passed. Thank You! -
Is There a Django Library for Email-Based OTP Password Resets?
I recently transitioned my Django project from a web app to a mobile app. While Djoser worked great for password resets on the web using UIDs and tokens, this approach doesn't work well on mobile due to the lack of explicit URLs. I'd like to avoid deep linking, as it seems it might be error-prone. So, I'm trying to figure out a different approach that lets users reset their passwords through email. I'm considering a one-time password (OTP). However, I haven't found a specific library that offers this feature. Could someone please help? Or, are there better ways to reset passwords via email other than using OTP? Thank you! -
How to get user groups from Django?
I'm trying to get the user groups that exist in a user in Django but unfortunately in the console it says: Uncaught ReferenceError: user is not defined at 6/:643:33 The function is supposed to redirect the user depending on if he has those groups or not. This is my current code: if (data.includes('The process is done.')) { alert('Success!.'); setTimeout(function () { if (user.groups.filter(name='group1').exists() || user.groups.filter(name='group2').exists()) { window.location.href = "{% url 'red' %}"; } else { window.location.href = "{% url 'blue' %}"; } }, 2000); } The code above is inside a success AJAX function. -
can using multiple threads in python and sending a POST request to the same api endpoint cause problems?
I'm currently using 3 threads to run my django app and I've noticed sporadic errors in the return response from a POST request that I'm making that uploads some info unto a database. responseObject = requests.post(url, params=params) I'll get an error back saying that "the entry already exists",now I don't control this endpoint myself so I can't look into it but I guess that particular message is irrelevant since I make sure that each request is different and also the error appears randomly and I can't really replicate it. I have ruled out anything wrong with the parameters, url or anything like that in this case. My suspicion is that the error comes from the threads making the request at the same time or something like that. Now I've read that django is supposedly thread safe and that the requests library in python is also thread safe so I don't know why it would cause trouble, I don't think these 3 requests would cause any trouble for the endpoint as a server is most likely made to handle concurrent web requests? I have tried making this request under a lock like lock = threading.Lock() with lock:responseObject = requests.post(url, params=params) and … -
how to display the names of all my applied filters in django, and then remove one by one or any filter just by clicking on it
Problem Statement I am working on a data filtering project using Django, and I want to implement a feature where applied filters are displayed on the screen, and users can remove them by clicking on a cross (X) button next to the filter name. Requirements When a filter is applied, it should be displayed at the top of the screen with a cross (X) button, allowing users to remove that specific filter. For example, if I apply a filter for charge_holder_name with the value 'rock', the filter name 'charge_holder_name', so it should be shown at the top of the screen with a cross button, so I can remove this filter by clicking on it. The same case should apply when multiple filters are applied, such as 'date', 'amount', 'id', etc. All applied filter names should be displayed at the top of the screen. Implementation Filters.py from bootstrap_datepicker_plus.widgets import DateTimePickerInput import django_filters from .models import RocCharge, RocCompany from django import forms # You can use a set comprehension to get unique values from RocCharge, loop to get unique values unique_charge_holder_names = {i.charge_holder_name for i in RocCharge.objects.all()} unique_company_names = {company.company_name for company in RocCompany.objects.all()} class Orderfilter(django_filters.FilterSet): # Specify the choices as a … -
How can I order a Django query by a field of a related model?
I have these two models, ChatRoom and ChatMessage, which are related. My goal is to order the ChatRoom queries in a way that the room with the most recent message, as determined by the sent_timestamp, appears at the top of the results. While I've found some similar questions on this platform, none of them seem to precisely address my specific issue. I'm aware of the annotate method, which I can use to achieve this outside of the model's Meta class, but I'm interested in setting the ordering directly in the Meta class of the ChatRoom model. Is there a way to achieve this ordering within the Meta class, or is there an alternative approach I should consider? class ChatRoom(models.Model): members = models.ManyToManyField(User, related_name="chat_rooms") class Meta: # Intended for this to order the chat rooms so that the room that # has the most recent chat message come first, but it's not working ordering = ("-messages__sent_timestamp",) class ChatMessage(models.Model): room = models.ForeignKey(ChatRoom, models.CASCADE, related_name="messages") sender = models.ForeignKey(User, models.CASCADE) text = models.TextField(validators=[MaxLengthValidator(280)]) sent_timestamp = models.DateTimeField(auto_now_add=True) delivery_timestamp = models.DateTimeField(null=True, blank=True) read_timestamp = models.DateTimeField(null=True, blank=True) class Meta: ordering = ("-sent_timestamp",) This is the test I've written to check the ordering, but it's failing at this … -
python-docx Hyperlink The hyperlink is created but not clickable
I was taking tuples from the database and creating a document with those values. Among them, I needed a hyperlink, so I wrote a function for it. However, the document was created, but it didn't work when I clicked on it, so when the document is completed and I do additional line break processing, It's working fine. Please tell me about this problem! def add_hyperlink(paragraph,text, url): # Create a new hyperlink element hyperlink = OxmlElement('w:hyperlink') hyperlink.set(qn('w:anchor'), url) # 하이퍼링크 URL 설정 # Create ‘w:t’, a sub-element of hyperlink t = OxmlElement('w:t') t.text = text hyperlink.append(t) # Show hyperlink text in blue run = paragraph.add_run() run._r.append(hyperlink) run.font.color.rgb = RGBColor(0, 0, 255) In the text, it is used like this: p1 = doc.add_paragraph(f"file : ", style='Normal') add_hyperlink(p1,base_url + path, base_url + path) run = p1.runs[0] run.add_break(WD_BREAK.LINE) # 줄바꿈 추가 -
In vs code django rest framework not showing autocomplete
This is my setting.json { "files.autoSave": "afterDelay", "python.defaultInterpreterPath": "/bin/python", "python.analysis.indexing": true, } Why vscode not show autocomplete for django rest framework? -
Django Admin page queryset dynamic filter
in the following Django Admin page I want the Model query set to be filtered by the Brand_id whenever adding a year This is the way that my models are setup: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Model(models.Model): name = models.CharField(max_length=100) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) def __str__(self): return self.name class Year(models.Model): year = models.IntegerField() brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default= None, blank = True, null= True) model = models.ForeignKey(Model, on_delete=models.CASCADE, default=None) def __str__(self): return str(self.year) I tried many attempts and searched for solutions but all of them in vain. My starting point now is to use the get_form function in the following way: class YearAdmin(admin.ModelAdmin): list_display = ['year', 'model', 'brand'] list_filter = ['brand', 'model'] def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields["model"].queryset = Model.objects.filter(brand_id=2) return form instead of having "brand_id=2" I would like to have something like "brand_id = currently_chosen_brand_id" in a dynamic way. How can this be done? Thank you in advance! -
After submitting the Booking form, there's nothing in the database
I've been trying to get this form to work. I created the model, forms.py, views, and linking in the URL files. The form was submitted and I got the 200 status code, so it seems like the POST method went through, but when I logged into the admin panel, there was nothing under the Booking model. This is what the lesson_details.html looks like. This is what it looks like with the booking modal open. Models.py from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Coach(models.Model): RECREATIONAL = 'recreational' FREESTYLE = 'freestyle' DANCE = 'dance' PAIRS = 'pairs' SPECIALIZATION_CHOICES = [ (RECREATIONAL, 'Recreational'), (FREESTYLE, 'Freestyle'), (DANCE, 'Dance'), (PAIRS, 'Pairs'), ] first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField(max_length=100) bio = models.CharField(max_length=140, help_text="Enter a brief bio") image = CloudinaryField('image', default='placeholder', help_text="Image must be a square") specialization = models.CharField(max_length=20, choices=SPECIALIZATION_CHOICES, default=RECREATIONAL) years_of_experience = models.PositiveIntegerField(default='1', help_text="Enter a positive integer.") status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['pk'] def __str__(self): return f'Coach {self.first_name} {self.last_name}' class Lesson(models.Model): # code from https://adamj.eu/tech/2020/01/27/moving-to-django-3-field-choices-enumeration-types/ BEGINNER = 'beginner' INTERMEDIATE = 'intermediate' ADVANCED = 'advanced' LEVEL_CHOICES = [ (BEGINNER, 'Beginner'), (INTERMEDIATE, 'Intermediate'), (ADVANCED, 'Advanced'), ] title = models.CharField(max_length=100, unique=True) … -
using queryset in forms django
hi My friends, I want to show only the professors of the same branch in the form, but it is not possible forms.py class ClassesForm(forms.ModelForm): class Meta: model = Classes fields = [ 'sath', 'code', 'name', 'gender', 'teacher', 'meeting', 'holding', 'teadadjalasat', 'sen', 'datestart', 'miantermstart', 'dateend', 'description', 'room', ] def __init__(self, *args, **kwargs): super(ClassesForm, self).__init__(*args, **kwargs) self.fields['teacher'].queryset = Profile.objects.filter(semat__icontains="teacher", status=1,branch=request.user.branch) NameError at /operation/classes/create/ name 'request' is not defined vlews.py class classesCreate(ClassesInline, CreateView): def get_context_data(self, **kwargs): ctx = super(classesCreate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_named_formsets(self): if self.request.method == "GET": return { 'reservs': ReservationFormSet(prefix='reservs'), } else: return { 'reservs': ReservationFormSet(self.request.POST or None, self.request.FILES or None, prefix='reservs'), } -
Count number of regexp matches in a Queryset regexp filter in Django
I've a queryset I'm running in a django view. sp = Session.objects.filter(year__gte=start_year, year__lte=end_year, data__iregex=word_to_search_for_re) Although it says word_to_search_for, this can be a couple of words separated by whitespace. What I want to do is count how many times the match occurs in data. At the moment, I'm pulling the results from this queryset back and doing this manually, which seems like a grossly inefficient code smell. I've seen something called annotations (https://medium.com/@singhgautam7/django-annotations-steroids-to-your-querysets-766231f0823a), but not sure how to get this to work in this case or if I'm asking too much. -
Celery Beat not Scheduling Task in Django Project
I'm working on a Django project where I'm using Celery for task scheduling. I have a periodic task that should run every minute, but it seems that Celery Beat is not picking up this task. Here's my setup: tasks.py: from celery.schedules import crontab from ..apps.scraper.scrapers.updates import get_updates from .settings import app app.conf.beat_schedule = { "get_updates": { "task": "..apps.scraper.scrapers.updates.get_updates", "schedule": crontab(minute="*/1"), # Run every 1 minute }, } celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "manga_project.settings") app = Celery("manga_project") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.broker_url = "redis://localhost:6379/0" updates.py: @app.task def get_updates(): print("Looking for manga updates...") mangas = Manga.objects.all() for manga in mangas: print("Checking ", manga.title, " ...") scrape_chapters("str", manga.url) I expect the get_updates task to run every minute, but it's not happening. When I start Celery Beat, it doesn't seem to pick up this task when I check the debbuger. I tried restarting celery and adding some error handling, but the tasks just simply doesnt get picked up so I am not sure how to handle this. Any advice would be appreciated. -
I am deploying a django web app with Docker on railway and getting app failed to respond. locally the app works fine and has no errors on logs
Here is my build logs Performing system checks... 2023-10-22 18:47:59.212964: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2023-10-22 18:47:59.213026: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2023-10-22 18:47:59.213120: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/usr/src/app/static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). October 22, 2023 - 18:48:02 Django version 4.1.7, using settings 'apitutorial.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. They look like the ones I get on my local machine, my fear then is there could be a networking issue, as a result the domain that I am clicking doesn't point to my web app. Its a django rest app. The page loads with app failed to respond. -
type object 'N_ns' has no attribute 'nominations_set'
In views.py I'm trying to take all the objects that are associated with the N_ns model through a many-to-one relationship. But I still don't understand how to register the function: obj=N_ns.nominations_set.all() class CandidateTeacher class CandidateTeacher(models.Model): nominations=models.ForeignKey('N_ns', on_delete=models.CASCADE, related_name='nominations') ... I wrote the function `obj=N_ns.nominations_set.all()' like a = Department.objects.get(id=1) b = a.employee_set.all() But I did not understand how this function appeared and how to register it -
how to import pillow into cpanel django project
good afternoon everyone, thank you very much if you are watching this. I want to make an update to my website which is made with django, I want to add an online store section that is managed from the django administrator, but when I want to do the makemigrations, it tells me that I cannot use imageFields, since it does not I have Pillow installed in the project, but it doesn't let me install pillow, I tried other versions, in many ways in the requirements.txt, but there is no way to let me add pillow to the django app. One very important thing is that I do not have the terminal in cpanel, I cannot have it, they only let me add the scripts and pip install in the way you will see in the following image: Here you can see what the format is like to add scripts or pip install and when I want to install using pip install the requirements.txt tells me this: Running setup.py (path:/tmp/pip-build-32phlj94/Pillow/setup.py) egg_info for package Pillow produced metadata for project name unknown. Fix your #egg=Pillow fragments. Failed building wheel for unknown Failed building wheel for unknownCommand "/home2/cannareiscom/virtualenv/CANNAb/3.9/bin/python3.9_bin -u -c "import setuptools, tokenize;file='/tmp/pip-build-32phlj94/Pillow/setup.py';f=getattr(tokenize, 'open', … -
intento instalar mysqlclient y me da un error
C:\Users\usuario1>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [39 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\\lib\\mariadb', 'C:/mariadb-connector\\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\\include\\mariadb', 'C:/mariadb-connector\\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('__version__', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\__init__.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\__init__.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running egg_info writing src\mysqlclient.egg-info\PKG-INFO writing dependency_links to src\mysqlclient.egg-info\dependency_links.txt writing top-level names to src\mysqlclient.egg-info\top_level.txt reading manifest file 'src\mysqlclient.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' adding license file 'LICENSE' writing manifest file 'src\mysqlclient.egg-info\SOURCES.txt' copying src\MySQLdb\_mysql.c -> build\lib.win-amd64-cpython-312\MySQLdb … -
Access to XMLHttpRequest has been blocked by CORS policy in Django
I have deployed a web app and created a sub domain for it as the url of its backend (e.g main url is domain.com and subdomain is api.domain.com) and both are in https, too. While I request from frontend to my created api in Django Rest Framework error Access to XMLHttpRequest has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource is given. Code below is the part of my settings.py. CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I shall be thankful for giving me the solution.